socket_linux.odin 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package net
  2. // +build linux
  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. flysand: Move dependency from core:os to core:sys/linux
  17. */
  18. import "core:c"
  19. import "core:time"
  20. import "core:sys/linux"
  21. Socket_Option :: enum c.int {
  22. Reuse_Address = c.int(linux.Socket_Option.REUSEADDR),
  23. Keep_Alive = c.int(linux.Socket_Option.KEEPALIVE),
  24. Out_Of_Bounds_Data_Inline = c.int(linux.Socket_Option.OOBINLINE),
  25. TCP_Nodelay = c.int(linux.Socket_TCP_Option.NODELAY),
  26. Linger = c.int(linux.Socket_Option.LINGER),
  27. Receive_Buffer_Size = c.int(linux.Socket_Option.RCVBUF),
  28. Send_Buffer_Size = c.int(linux.Socket_Option.SNDBUF),
  29. Receive_Timeout = c.int(linux.Socket_Option.RCVTIMEO_NEW),
  30. Send_Timeout = c.int(linux.Socket_Option.SNDTIMEO_NEW),
  31. }
  32. // Wrappers and unwrappers for system-native types
  33. @(private="file")
  34. _unwrap_os_socket :: proc "contextless" (sock: Any_Socket)->linux.Fd {
  35. return linux.Fd(any_socket_to_socket(sock))
  36. }
  37. @(private="file")
  38. _wrap_os_socket :: proc "contextless" (sock: linux.Fd, protocol: Socket_Protocol)->Any_Socket {
  39. switch protocol {
  40. case .TCP: return TCP_Socket(Socket(sock))
  41. case .UDP: return UDP_Socket(Socket(sock))
  42. case:
  43. unreachable()
  44. }
  45. }
  46. @(private="file")
  47. _unwrap_os_family :: proc "contextless" (family: Address_Family)->linux.Address_Family {
  48. switch family {
  49. case .IP4: return .INET
  50. case .IP6: return .INET6
  51. case:
  52. unreachable()
  53. }
  54. }
  55. @(private="file")
  56. _unwrap_os_proto_socktype :: proc "contextless" (protocol: Socket_Protocol)->(linux.Protocol, linux.Socket_Type) {
  57. switch protocol {
  58. case .TCP: return .TCP, .STREAM
  59. case .UDP: return .UDP, .DGRAM
  60. case:
  61. unreachable()
  62. }
  63. }
  64. @(private="file")
  65. _unwrap_os_addr :: proc "contextless" (endpoint: Endpoint)->(linux.Sock_Addr_Any) {
  66. switch address in endpoint.address {
  67. case IP4_Address:
  68. return {
  69. ipv4 = {
  70. sin_family = .INET,
  71. sin_port = u16be(endpoint.port),
  72. sin_addr = transmute([4]u8) endpoint.address.(IP4_Address),
  73. },
  74. }
  75. case IP6_Address:
  76. return {
  77. ipv6 = {
  78. sin6_port = u16be(endpoint.port),
  79. sin6_addr = transmute([16]u8) endpoint.address.(IP6_Address),
  80. sin6_family = .INET6,
  81. },
  82. }
  83. case:
  84. unreachable()
  85. }
  86. }
  87. @(private="file")
  88. _wrap_os_addr :: proc "contextless" (addr: linux.Sock_Addr_Any)->(Endpoint) {
  89. #partial switch addr.family {
  90. case .INET:
  91. return {
  92. address = cast(IP4_Address) addr.sin_addr,
  93. port = cast(int) addr.sin_port,
  94. }
  95. case .INET6:
  96. return {
  97. port = cast(int) addr.sin6_port,
  98. address = transmute(IP6_Address) addr.sin6_addr,
  99. }
  100. case:
  101. unreachable()
  102. }
  103. }
  104. _create_socket :: proc(family: Address_Family, protocol: Socket_Protocol) -> (Any_Socket, Network_Error) {
  105. family := _unwrap_os_family(family)
  106. proto, socktype := _unwrap_os_proto_socktype(protocol)
  107. sock, errno := linux.socket(family, socktype, {}, proto)
  108. if errno != .NONE {
  109. return {}, Create_Socket_Error(errno)
  110. }
  111. return _wrap_os_socket(sock, protocol), nil
  112. }
  113. @(private)
  114. _dial_tcp_from_endpoint :: proc(endpoint: Endpoint, options := default_tcp_options) -> (TCP_Socket, Network_Error) {
  115. errno: linux.Errno
  116. if endpoint.port == 0 {
  117. return 0, .Port_Required
  118. }
  119. // Create new TCP socket
  120. os_sock: linux.Fd
  121. os_sock, errno = linux.socket(_unwrap_os_family(family_from_endpoint(endpoint)), .STREAM, {}, .TCP)
  122. if errno != .NONE {
  123. // TODO(flysand): should return invalid file descriptor here casted as TCP_Socket
  124. return {}, Create_Socket_Error(errno)
  125. }
  126. // NOTE(tetra): This is so that if we crash while the socket is open, we can
  127. // bypass the cooldown period, and allow the next run of the program to
  128. // use the same address immediately.
  129. reuse_addr: b32 = true
  130. _ = linux.setsockopt(os_sock, linux.SOL_SOCKET, linux.Socket_Option.REUSEADDR, &reuse_addr)
  131. addr := _unwrap_os_addr(endpoint)
  132. errno = linux.connect(linux.Fd(os_sock), &addr)
  133. if errno != .NONE {
  134. return cast(TCP_Socket) os_sock, Dial_Error(errno)
  135. }
  136. // NOTE(tetra): Not vital to succeed; error ignored
  137. no_delay: b32 = cast(b32) options.no_delay
  138. _ = linux.setsockopt(os_sock, linux.SOL_TCP, linux.Socket_TCP_Option.NODELAY, &no_delay)
  139. return cast(TCP_Socket) os_sock, nil
  140. }
  141. @(private)
  142. _bind :: proc(sock: Any_Socket, endpoint: Endpoint) -> (Network_Error) {
  143. addr := _unwrap_os_addr(endpoint)
  144. errno := linux.bind(_unwrap_os_socket(sock), &addr)
  145. if errno != .NONE {
  146. return Bind_Error(errno)
  147. }
  148. return nil
  149. }
  150. @(private)
  151. _listen_tcp :: proc(endpoint: Endpoint, backlog := 1000) -> (TCP_Socket, Network_Error) {
  152. errno: linux.Errno
  153. assert(backlog > 0 && i32(backlog) < max(i32))
  154. // Figure out the address family and address of the endpoint
  155. ep_family := _unwrap_os_family(family_from_endpoint(endpoint))
  156. ep_address := _unwrap_os_addr(endpoint)
  157. // Create TCP socket
  158. os_sock: linux.Fd
  159. os_sock, errno = linux.socket(ep_family, .STREAM, {}, .TCP)
  160. if errno != .NONE {
  161. // TODO(flysand): should return invalid file descriptor here casted as TCP_Socket
  162. return {}, Create_Socket_Error(errno)
  163. }
  164. // NOTE(tetra): This is so that if we crash while the socket is open, we can
  165. // bypass the cooldown period, and allow the next run of the program to
  166. // use the same address immediately.
  167. //
  168. // TODO(tetra, 2022-02-15): Confirm that this doesn't mean other processes can hijack the address!
  169. do_reuse_addr: b32 = true
  170. errno = linux.setsockopt(os_sock, linux.SOL_SOCKET, linux.Socket_Option.REUSEADDR, &do_reuse_addr)
  171. if errno != .NONE {
  172. return cast(TCP_Socket) os_sock, Listen_Error(errno)
  173. }
  174. // Bind the socket to endpoint address
  175. errno = linux.bind(os_sock, &ep_address)
  176. if errno != .NONE {
  177. return cast(TCP_Socket) os_sock, Bind_Error(errno)
  178. }
  179. // Listen on bound socket
  180. errno = linux.listen(os_sock, cast(i32) backlog)
  181. if errno != .NONE {
  182. return cast(TCP_Socket) os_sock, Listen_Error(errno)
  183. }
  184. return cast(TCP_Socket) os_sock, nil
  185. }
  186. @(private)
  187. _accept_tcp :: proc(sock: TCP_Socket, options := default_tcp_options) -> (tcp_client: TCP_Socket, endpoint: Endpoint, err: Network_Error) {
  188. addr: linux.Sock_Addr_Any
  189. client_sock, errno := linux.accept(linux.Fd(sock), &addr)
  190. if errno != .NONE {
  191. return {}, {}, Accept_Error(errno)
  192. }
  193. // NOTE(tetra): Not vital to succeed; error ignored
  194. val: b32 = cast(b32) options.no_delay
  195. _ = linux.setsockopt(client_sock, linux.SOL_TCP, linux.Socket_TCP_Option.NODELAY, &val)
  196. return TCP_Socket(client_sock), _wrap_os_addr(addr), nil
  197. }
  198. @(private)
  199. _close :: proc(sock: Any_Socket) {
  200. linux.close(_unwrap_os_socket(sock))
  201. }
  202. @(private)
  203. _recv_tcp :: proc(tcp_sock: TCP_Socket, buf: []byte) -> (int, Network_Error) {
  204. if len(buf) <= 0 {
  205. return 0, nil
  206. }
  207. bytes_read, errno := linux.recv(linux.Fd(tcp_sock), buf, {})
  208. if errno != .NONE {
  209. return 0, TCP_Recv_Error(errno)
  210. }
  211. return int(bytes_read), nil
  212. }
  213. @(private)
  214. _recv_udp :: proc(udp_sock: UDP_Socket, buf: []byte) -> (int, Endpoint, Network_Error) {
  215. if len(buf) <= 0 {
  216. // NOTE(flysand): It was returning no error, I didn't change anything
  217. return 0, {}, {}
  218. }
  219. // NOTE(tetra): On Linux, if the buffer is too small to fit the entire datagram payload, the rest is silently discarded,
  220. // and no error is returned.
  221. // However, if you pass MSG_TRUNC here, 'res' will be the size of the incoming message, rather than how much was read.
  222. // We can use this fact to detect this condition and return .Buffer_Too_Small.
  223. from_addr: linux.Sock_Addr_Any
  224. bytes_read, errno := linux.recvfrom(linux.Fd(udp_sock), buf, {.TRUNC}, &from_addr)
  225. if errno != .NONE {
  226. return 0, {}, UDP_Recv_Error(errno)
  227. }
  228. if bytes_read > len(buf) {
  229. // NOTE(tetra): The buffer has been filled, with a partial message.
  230. return len(buf), {}, .Buffer_Too_Small
  231. }
  232. return bytes_read, _wrap_os_addr(from_addr), nil
  233. }
  234. @(private)
  235. _send_tcp :: proc(tcp_sock: TCP_Socket, buf: []byte) -> (int, Network_Error) {
  236. total_written := 0
  237. for total_written < len(buf) {
  238. limit := min(int(max(i32)), len(buf) - total_written)
  239. remaining := buf[total_written:][:limit]
  240. res, errno := linux.send(linux.Fd(tcp_sock), remaining, {})
  241. if errno != .NONE {
  242. return total_written, TCP_Send_Error(errno)
  243. }
  244. total_written += int(res)
  245. }
  246. return total_written, nil
  247. }
  248. @(private)
  249. _send_udp :: proc(udp_sock: UDP_Socket, buf: []byte, to: Endpoint) -> (int, Network_Error) {
  250. to_addr := _unwrap_os_addr(to)
  251. bytes_written, errno := linux.sendto(linux.Fd(udp_sock), buf, {}, &to_addr)
  252. if errno != .NONE {
  253. return bytes_written, UDP_Send_Error(errno)
  254. }
  255. return int(bytes_written), nil
  256. }
  257. @(private)
  258. _shutdown :: proc(sock: Any_Socket, manner: Shutdown_Manner) -> (err: Network_Error) {
  259. os_sock := _unwrap_os_socket(sock)
  260. errno := linux.shutdown(os_sock, cast(linux.Shutdown_How) manner)
  261. if errno != .NONE {
  262. return Shutdown_Error(errno)
  263. }
  264. return nil
  265. }
  266. // TODO(flysand): Figure out what we want to do with this on core:sys/ level.
  267. @(private)
  268. _set_option :: proc(sock: Any_Socket, option: Socket_Option, value: any, loc := #caller_location) -> Network_Error {
  269. level: int
  270. if option == .TCP_Nodelay {
  271. level = int(linux.SOL_TCP)
  272. } else {
  273. level = int(linux.SOL_SOCKET)
  274. }
  275. os_sock := _unwrap_os_socket(sock)
  276. // NOTE(tetra, 2022-02-15): On Linux, you cannot merely give a single byte for a bool;
  277. // it _has_ to be a b32.
  278. // I haven't tested if you can give more than that. <-- (flysand) probably not, posix explicitly specifies an int
  279. bool_value: b32
  280. int_value: i32
  281. timeval_value: linux.Time_Val
  282. errno: linux.Errno
  283. switch option {
  284. case
  285. .Reuse_Address,
  286. .Keep_Alive,
  287. .Out_Of_Bounds_Data_Inline,
  288. .TCP_Nodelay:
  289. // TODO: verify whether these are options or not on Linux
  290. // .Broadcast, <-- yes
  291. // .Conditional_Accept,
  292. // .Dont_Linger:
  293. switch x in value {
  294. case bool, b8:
  295. x2 := x
  296. bool_value = b32((^bool)(&x2)^)
  297. case b16:
  298. bool_value = b32(x)
  299. case b32:
  300. bool_value = b32(x)
  301. case b64:
  302. bool_value = b32(x)
  303. case:
  304. panic("set_option() value must be a boolean here", loc)
  305. }
  306. errno = linux.setsockopt(os_sock, level, int(option), &bool_value)
  307. case
  308. .Linger,
  309. .Send_Timeout,
  310. .Receive_Timeout:
  311. t, ok := value.(time.Duration)
  312. if !ok {
  313. panic("set_option() value must be a time.Duration here", loc)
  314. }
  315. micros := cast(i64) (time.duration_microseconds(t))
  316. timeval_value.microseconds = cast(int) (micros % 1e6)
  317. timeval_value.seconds = cast(int) ((micros - i64(timeval_value.microseconds)) / 1e6)
  318. errno = linux.setsockopt(os_sock, level, int(option), &timeval_value)
  319. case
  320. .Receive_Buffer_Size,
  321. .Send_Buffer_Size:
  322. // TODO: check for out of range values and return .Value_Out_Of_Range?
  323. switch i in value {
  324. case i8, u8: i2 := i; int_value = i32((^u8)(&i2)^)
  325. case i16, u16: i2 := i; int_value = i32((^u16)(&i2)^)
  326. case i32, u32: i2 := i; int_value = i32((^u32)(&i2)^)
  327. case i64, u64: i2 := i; int_value = i32((^u64)(&i2)^)
  328. case i128, u128: i2 := i; int_value = i32((^u128)(&i2)^)
  329. case int, uint: i2 := i; int_value = i32((^uint)(&i2)^)
  330. case:
  331. panic("set_option() value must be an integer here", loc)
  332. }
  333. errno = linux.setsockopt(os_sock, level, int(option), &int_value)
  334. }
  335. if errno != .NONE {
  336. return Socket_Option_Error(errno)
  337. }
  338. return nil
  339. }
  340. @(private)
  341. _set_blocking :: proc(sock: Any_Socket, should_block: bool) -> (err: Network_Error) {
  342. errno: linux.Errno
  343. flags: linux.Open_Flags
  344. os_sock := _unwrap_os_socket(sock)
  345. flags, errno = linux.fcntl(os_sock, linux.F_GETFL)
  346. if errno != .NONE {
  347. return Set_Blocking_Error(errno)
  348. }
  349. if should_block {
  350. flags &= ~{.NONBLOCK}
  351. } else {
  352. flags |= {.NONBLOCK}
  353. }
  354. errno = linux.fcntl(os_sock, linux.F_SETFL, flags)
  355. if errno != .NONE {
  356. return Set_Blocking_Error(errno)
  357. }
  358. return nil
  359. }