socket_freebsd.odin 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. err = cast(Dial_Error)errno
  101. return
  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. bind(socket, interface_endpoint) or_return
  121. errno := freebsd.listen(cast(Fd)socket, backlog)
  122. if errno != nil {
  123. err = cast(Listen_Error)errno
  124. return
  125. }
  126. return
  127. }
  128. @(private)
  129. _bound_endpoint :: proc(sock: Any_Socket) -> (ep: Endpoint, err: Network_Error) {
  130. sockaddr: freebsd.Socket_Address_Storage
  131. errno := freebsd.getsockname(cast(Fd)any_socket_to_socket(sock), &sockaddr)
  132. if errno != nil {
  133. err = cast(Listen_Error)errno
  134. return
  135. }
  136. ep = _sockaddr_to_endpoint(&sockaddr)
  137. return
  138. }
  139. @(private)
  140. _accept_tcp :: proc(sock: TCP_Socket, options := default_tcp_options) -> (client: TCP_Socket, source: Endpoint, err: Network_Error) {
  141. sockaddr: freebsd.Socket_Address_Storage
  142. result, errno := freebsd.accept(cast(Fd)sock, &sockaddr)
  143. if errno != nil {
  144. err = cast(Accept_Error)errno
  145. return
  146. }
  147. client = cast(TCP_Socket)result
  148. source = _sockaddr_to_endpoint(&sockaddr)
  149. return
  150. }
  151. @(private)
  152. _close :: proc(socket: Any_Socket) {
  153. real_socket := cast(Fd)any_socket_to_socket(socket)
  154. // TODO: This returns an error number, but the `core:net` interface does not handle it.
  155. _ = freebsd.close(real_socket)
  156. }
  157. @(private)
  158. _recv_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_read: int, err: Network_Error) {
  159. if len(buf) == 0 {
  160. return
  161. }
  162. result, errno := freebsd.recv(cast(Fd)socket, buf, .NONE)
  163. if errno != nil {
  164. err = cast(TCP_Recv_Error)errno
  165. return
  166. }
  167. return result, nil
  168. }
  169. @(private)
  170. _recv_udp :: proc(socket: UDP_Socket, buf: []byte) -> (bytes_read: int, remote_endpoint: Endpoint, err: Network_Error) {
  171. if len(buf) == 0 {
  172. return
  173. }
  174. from: freebsd.Socket_Address_Storage
  175. result, errno := freebsd.recvfrom(cast(Fd)socket, buf, .NONE, &from)
  176. if errno != nil {
  177. err = cast(UDP_Recv_Error)errno
  178. return
  179. }
  180. return result, _sockaddr_to_endpoint(&from), nil
  181. }
  182. @(private)
  183. _send_tcp :: proc(socket: TCP_Socket, buf: []byte) -> (bytes_written: int, err: Network_Error) {
  184. for bytes_written < len(buf) {
  185. limit := min(int(max(i32)), len(buf) - bytes_written)
  186. remaining := buf[bytes_written:][:limit]
  187. result, errno := freebsd.send(cast(Fd)socket, remaining, .NONE)
  188. if errno != nil {
  189. err = cast(TCP_Send_Error)errno
  190. return
  191. }
  192. bytes_written += result
  193. }
  194. return
  195. }
  196. @(private)
  197. _send_udp :: proc(socket: UDP_Socket, buf: []byte, to: Endpoint) -> (bytes_written: int, err: Network_Error) {
  198. toaddr := _endpoint_to_sockaddr(to)
  199. for bytes_written < len(buf) {
  200. limit := min(int(max(i32)), len(buf) - bytes_written)
  201. remaining := buf[bytes_written:][:limit]
  202. result, errno := freebsd.sendto(cast(Fd)socket, remaining, .NONE, &toaddr)
  203. if errno != nil {
  204. err = cast(UDP_Send_Error)errno
  205. return
  206. }
  207. bytes_written += result
  208. }
  209. return
  210. }
  211. @(private)
  212. _shutdown :: proc(socket: Any_Socket, manner: Shutdown_Manner) -> (err: Network_Error) {
  213. real_socket := cast(Fd)any_socket_to_socket(socket)
  214. errno := freebsd.shutdown(real_socket, cast(freebsd.Shutdown_Method)manner)
  215. if errno != nil {
  216. return cast(Shutdown_Error)errno
  217. }
  218. return
  219. }
  220. @(private)
  221. _set_option :: proc(socket: Any_Socket, option: Socket_Option, value: any, loc := #caller_location) -> Network_Error {
  222. // NOTE(Feoramund): I found that FreeBSD, like Linux, requires at least 32
  223. // bits for a boolean socket option value. Nothing less will work.
  224. bool_value: b32
  225. // TODO: Assuming no larger than i32, but the system may accept i64.
  226. int_value: i32
  227. timeval_value: freebsd.timeval
  228. ptr: rawptr
  229. len: freebsd.socklen_t
  230. switch option {
  231. case
  232. .Reuse_Address,
  233. .Keep_Alive,
  234. .Broadcast,
  235. .Use_Loopback,
  236. .Out_Of_Bounds_Data_Inline,
  237. .Reuse_Port,
  238. .No_SIGPIPE_From_EPIPE,
  239. .Reuse_Port_Load_Balancing:
  240. switch real in value {
  241. case bool: bool_value = cast(b32)real
  242. case b8: bool_value = cast(b32)real
  243. case b16: bool_value = cast(b32)real
  244. case b32: bool_value = real
  245. case b64: bool_value = cast(b32)real
  246. case:
  247. panic("set_option() value must be a boolean here", loc)
  248. }
  249. ptr = &bool_value
  250. len = size_of(bool_value)
  251. case
  252. .Linger,
  253. .Send_Timeout,
  254. .Receive_Timeout:
  255. t, ok := value.(time.Duration)
  256. if !ok {
  257. panic("set_option() value must be a time.Duration here", loc)
  258. }
  259. micros := cast(freebsd.time_t)time.duration_microseconds(t)
  260. timeval_value.usec = cast(freebsd.suseconds_t)micros % 1e6
  261. timeval_value.sec = (micros - cast(freebsd.time_t)timeval_value.usec) / 1e6
  262. ptr = &timeval_value
  263. len = size_of(timeval_value)
  264. case
  265. .Receive_Buffer_Size,
  266. .Send_Buffer_Size:
  267. switch real in value {
  268. case i8: int_value = cast(i32)real
  269. case u8: int_value = cast(i32)real
  270. case i16: int_value = cast(i32)real
  271. case u16: int_value = cast(i32)real
  272. case i32: int_value = real
  273. case u32:
  274. if real > u32(max(i32)) { return .Value_Out_Of_Range }
  275. int_value = cast(i32)real
  276. case i64:
  277. if real > i64(max(i32)) || real < i64(min(i32)) { return .Value_Out_Of_Range }
  278. int_value = cast(i32)real
  279. case u64:
  280. if real > u64(max(i32)) { return .Value_Out_Of_Range }
  281. int_value = cast(i32)real
  282. case i128:
  283. if real > i128(max(i32)) || real < i128(min(i32)) { return .Value_Out_Of_Range }
  284. int_value = cast(i32)real
  285. case u128:
  286. if real > u128(max(i32)) { return .Value_Out_Of_Range }
  287. int_value = cast(i32)real
  288. case int:
  289. if real > int(max(i32)) || real < int(min(i32)) { return .Value_Out_Of_Range }
  290. int_value = cast(i32)real
  291. case uint:
  292. if real > uint(max(i32)) { return .Value_Out_Of_Range }
  293. int_value = cast(i32)real
  294. case:
  295. panic("set_option() value must be an integer here", loc)
  296. }
  297. ptr = &int_value
  298. len = size_of(int_value)
  299. case:
  300. unimplemented("set_option() option not yet implemented", loc)
  301. }
  302. real_socket := any_socket_to_socket(socket)
  303. errno := freebsd.setsockopt(cast(Fd)real_socket, .SOCKET, cast(freebsd.Socket_Option)option, ptr, len)
  304. if errno != nil {
  305. return cast(Socket_Option_Error)errno
  306. }
  307. return nil
  308. }
  309. @(private)
  310. _set_blocking :: proc(socket: Any_Socket, should_block: bool) -> (err: Network_Error) {
  311. real_socket := any_socket_to_socket(socket)
  312. flags, errno := freebsd.fcntl_getfl(cast(freebsd.Fd)real_socket)
  313. if errno != nil {
  314. return cast(Set_Blocking_Error)errno
  315. }
  316. if should_block {
  317. flags &= ~{ .NONBLOCK }
  318. } else {
  319. flags |= { .NONBLOCK }
  320. }
  321. errno = freebsd.fcntl_setfl(cast(freebsd.Fd)real_socket, flags)
  322. if errno != nil {
  323. return cast(Set_Blocking_Error)errno
  324. }
  325. return
  326. }
  327. @(private)
  328. _endpoint_to_sockaddr :: proc(ep: Endpoint) -> (sockaddr: freebsd.Socket_Address_Storage) {
  329. switch addr in ep.address {
  330. case IP4_Address:
  331. (cast(^freebsd.Socket_Address_Internet)(&sockaddr))^ = {
  332. len = size_of(freebsd.Socket_Address_Internet),
  333. family = .INET,
  334. port = cast(freebsd.in_port_t)ep.port,
  335. addr = transmute(freebsd.IP4_Address)addr,
  336. }
  337. case IP6_Address:
  338. (cast(^freebsd.Socket_Address_Internet6)(&sockaddr))^ = {
  339. len = size_of(freebsd.Socket_Address_Internet),
  340. family = .INET6,
  341. port = cast(freebsd.in_port_t)ep.port,
  342. addr = transmute(freebsd.IP6_Address)addr,
  343. }
  344. }
  345. return
  346. }
  347. @(private)
  348. _sockaddr_to_endpoint :: proc(native_addr: ^freebsd.Socket_Address_Storage) -> (ep: Endpoint) {
  349. #partial switch native_addr.family {
  350. case .INET:
  351. addr := cast(^freebsd.Socket_Address_Internet)native_addr
  352. ep = {
  353. address = cast(IP4_Address)addr.addr.addr8,
  354. port = cast(int)addr.port,
  355. }
  356. case .INET6:
  357. addr := cast(^freebsd.Socket_Address_Internet6)native_addr
  358. ep = {
  359. address = cast(IP6_Address)addr.addr.addr16,
  360. port = cast(int)addr.port,
  361. }
  362. case:
  363. panic("native_addr is neither an IP4 or IP6 address")
  364. }
  365. return
  366. }