net: drop core:os dependency for Darwin

This commit is contained in:
Laytan Laats
2025-03-29 23:27:03 +01:00
parent e7ae7b8fd4
commit 327d9f134d
3 changed files with 291 additions and 249 deletions
+95 -92
View File
@@ -21,184 +21,187 @@ package net
*/ */
import "core:c" import "core:c"
import "core:os" import "core:sys/posix"
@(private)
ESHUTDOWN :: 58
Create_Socket_Error :: enum c.int { Create_Socket_Error :: enum c.int {
None = 0, None = 0,
Family_Not_Supported_For_This_Socket = c.int(os.EAFNOSUPPORT), Family_Not_Supported_For_This_Socket = c.int(posix.EAFNOSUPPORT),
No_Socket_Descriptors_Available = c.int(os.EMFILE), No_Socket_Descriptors_Available = c.int(posix.EMFILE),
No_Buffer_Space_Available = c.int(os.ENOBUFS), No_Buffer_Space_Available = c.int(posix.ENOBUFS),
No_Memory_Available_Available = c.int(os.ENOMEM), No_Memory_Available = c.int(posix.ENOMEM),
Protocol_Unsupported_By_System = c.int(os.EPROTONOSUPPORT), Protocol_Unsupported_By_System = c.int(posix.EPROTONOSUPPORT),
Wrong_Protocol_For_Socket = c.int(os.EPROTONOSUPPORT), Wrong_Protocol_For_Socket = c.int(posix.EPROTONOSUPPORT),
Family_And_Socket_Type_Mismatch = c.int(os.EPROTONOSUPPORT), Family_And_Socket_Type_Mismatch = c.int(posix.EPROTONOSUPPORT),
} }
Dial_Error :: enum c.int { Dial_Error :: enum c.int {
None = 0, None = 0,
Port_Required = -1, // Attempted to dial an endpointing without a port being set. Port_Required = -1, // Attempted to dial an endpointing without a port being set.
Address_In_Use = c.int(os.EADDRINUSE), Address_In_Use = c.int(posix.EADDRINUSE),
In_Progress = c.int(os.EINPROGRESS), In_Progress = c.int(posix.EINPROGRESS),
Cannot_Use_Any_Address = c.int(os.EADDRNOTAVAIL), Cannot_Use_Any_Address = c.int(posix.EADDRNOTAVAIL),
Wrong_Family_For_Socket = c.int(os.EAFNOSUPPORT), Wrong_Family_For_Socket = c.int(posix.EAFNOSUPPORT),
Refused = c.int(os.ECONNREFUSED), Refused = c.int(posix.ECONNREFUSED),
Is_Listening_Socket = c.int(os.EACCES), Is_Listening_Socket = c.int(posix.EACCES),
Already_Connected = c.int(os.EISCONN), Already_Connected = c.int(posix.EISCONN),
Network_Unreachable = c.int(os.ENETUNREACH), // Device is offline Network_Unreachable = c.int(posix.ENETUNREACH), // Device is offline
Host_Unreachable = c.int(os.EHOSTUNREACH), // Remote host cannot be reached Host_Unreachable = c.int(posix.EHOSTUNREACH), // Remote host cannot be reached
No_Buffer_Space_Available = c.int(os.ENOBUFS), No_Buffer_Space_Available = c.int(posix.ENOBUFS),
Not_Socket = c.int(os.ENOTSOCK), Not_Socket = c.int(posix.ENOTSOCK),
Timeout = c.int(os.ETIMEDOUT), Timeout = c.int(posix.ETIMEDOUT),
// TODO: we may need special handling for this; maybe make a socket a struct with metadata? // TODO: we may need special handling for this; maybe make a socket a struct with metadata?
Would_Block = c.int(os.EWOULDBLOCK), Would_Block = c.int(posix.EWOULDBLOCK),
} }
Bind_Error :: enum c.int { Bind_Error :: enum c.int {
None = 0, None = 0,
Privileged_Port_Without_Root = -1, // Attempted to bind to a port less than 1024 without root access. Privileged_Port_Without_Root = -1, // Attempted to bind to a port less than 1024 without root access.
Address_In_Use = c.int(os.EADDRINUSE), // Another application is currently bound to this endpoint. Address_In_Use = c.int(posix.EADDRINUSE), // Another application is currently bound to this endpoint.
Given_Nonlocal_Address = c.int(os.EADDRNOTAVAIL), // The address is not a local address on this machine. Given_Nonlocal_Address = c.int(posix.EADDRNOTAVAIL), // The address is not a local address on this machine.
Broadcast_Disabled = c.int(os.EACCES), // To bind a UDP socket to the broadcast address, the appropriate socket option must be set. Broadcast_Disabled = c.int(posix.EACCES), // To bind a UDP socket to the broadcast address, the appropriate socket option must be set.
Address_Family_Mismatch = c.int(os.EFAULT), // The address family of the address does not match that of the socket. Address_Family_Mismatch = c.int(posix.EFAULT), // The address family of the address does not match that of the socket.
Already_Bound = c.int(os.EINVAL), // The socket is already bound to an address. Already_Bound = c.int(posix.EINVAL), // The socket is already bound to an address.
No_Ports_Available = c.int(os.ENOBUFS), // There are not enough ephemeral ports available. No_Ports_Available = c.int(posix.ENOBUFS), // There are not enough ephemeral ports available.
} }
Listen_Error :: enum c.int { Listen_Error :: enum c.int {
None = 0, None = 0,
Address_In_Use = c.int(os.EADDRINUSE), Address_In_Use = c.int(posix.EADDRINUSE),
Already_Connected = c.int(os.EISCONN), Already_Connected = c.int(posix.EISCONN),
No_Socket_Descriptors_Available = c.int(os.EMFILE), No_Socket_Descriptors_Available = c.int(posix.EMFILE),
No_Buffer_Space_Available = c.int(os.ENOBUFS), No_Buffer_Space_Available = c.int(posix.ENOBUFS),
Nonlocal_Address = c.int(os.EADDRNOTAVAIL), Nonlocal_Address = c.int(posix.EADDRNOTAVAIL),
Not_Socket = c.int(os.ENOTSOCK), Not_Socket = c.int(posix.ENOTSOCK),
Listening_Not_Supported_For_This_Socket = c.int(os.EOPNOTSUPP), Listening_Not_Supported_For_This_Socket = c.int(posix.EOPNOTSUPP),
} }
Accept_Error :: enum c.int { Accept_Error :: enum c.int {
None = 0, None = 0,
// TODO(tetra): Is this error actually possible here? Or is like Linux, in which case we can remove it. // TODO(tetra): Is this error actually possible here? Or is like Linux, in which case we can remove it.
Reset = c.int(os.ECONNRESET), Reset = c.int(posix.ECONNRESET),
Not_Listening = c.int(os.EINVAL), Not_Listening = c.int(posix.EINVAL),
No_Socket_Descriptors_Available_For_Client_Socket = c.int(os.EMFILE), No_Socket_Descriptors_Available_For_Client_Socket = c.int(posix.EMFILE),
No_Buffer_Space_Available = c.int(os.ENOBUFS), No_Buffer_Space_Available = c.int(posix.ENOBUFS),
Not_Socket = c.int(os.ENOTSOCK), Not_Socket = c.int(posix.ENOTSOCK),
Not_Connection_Oriented_Socket = c.int(os.EOPNOTSUPP), Not_Connection_Oriented_Socket = c.int(posix.EOPNOTSUPP),
// TODO: we may need special handling for this; maybe make a socket a struct with metadata? // TODO: we may need special handling for this; maybe make a socket a struct with metadata?
Would_Block = c.int(os.EWOULDBLOCK), Would_Block = c.int(posix.EWOULDBLOCK),
} }
TCP_Recv_Error :: enum c.int { TCP_Recv_Error :: enum c.int {
None = 0, None = 0,
Shutdown = c.int(os.ESHUTDOWN), Shutdown = ESHUTDOWN,
Not_Connected = c.int(os.ENOTCONN), Not_Connected = c.int(posix.ENOTCONN),
// TODO(tetra): Is this error actually possible here? // TODO(tetra): Is this error actually possible here?
Connection_Broken = c.int(os.ENETRESET), Connection_Broken = c.int(posix.ENETRESET),
Not_Socket = c.int(os.ENOTSOCK), Not_Socket = c.int(posix.ENOTSOCK),
Aborted = c.int(os.ECONNABORTED), Aborted = c.int(posix.ECONNABORTED),
// TODO(tetra): Determine when this is different from the syscall returning n=0 and maybe normalize them? // TODO(tetra): Determine when this is different from the syscall returning n=0 and maybe normalize them?
Connection_Closed = c.int(os.ECONNRESET), Connection_Closed = c.int(posix.ECONNRESET),
Offline = c.int(os.ENETDOWN), Offline = c.int(posix.ENETDOWN),
Host_Unreachable = c.int(os.EHOSTUNREACH), Host_Unreachable = c.int(posix.EHOSTUNREACH),
Interrupted = c.int(os.EINTR), Interrupted = c.int(posix.EINTR),
// NOTE: No, really. Presumably this means something different for nonblocking sockets... // NOTE: No, really. Presumably this means something different for nonblocking sockets...
Timeout = c.int(os.EWOULDBLOCK), Timeout = c.int(posix.EWOULDBLOCK),
} }
UDP_Recv_Error :: enum c.int { UDP_Recv_Error :: enum c.int {
None = 0, None = 0,
Buffer_Too_Small = c.int(os.EMSGSIZE), // The buffer is too small to fit the entire message, and the message was truncated. When this happens, the rest of message is lost. Buffer_Too_Small = c.int(posix.EMSGSIZE), // The buffer is too small to fit the entire message, and the message was truncated. When this happens, the rest of message is lost.
Not_Socket = c.int(os.ENOTSOCK), // The so-called socket is not an open socket. Not_Socket = c.int(posix.ENOTSOCK), // The so-called socket is not an open socket.
Not_Descriptor = c.int(os.EBADF), // The so-called socket is, in fact, not even a valid descriptor. Not_Descriptor = c.int(posix.EBADF), // The so-called socket is, in fact, not even a valid descriptor.
Bad_Buffer = c.int(os.EFAULT), // The buffer did not point to a valid location in memory. Bad_Buffer = c.int(posix.EFAULT), // The buffer did not point to a valid location in memory.
Interrupted = c.int(os.EINTR), // A signal occurred before any data was transmitted. See signal(7). Interrupted = c.int(posix.EINTR), // A signal occurred before any data was transmitted. See signal(7).
// The send timeout duration passed before all data was sent. See Socket_Option.Send_Timeout. // The send timeout duration passed before all data was sent. See Socket_Option.Send_Timeout.
// NOTE: No, really. Presumably this means something different for nonblocking sockets... // NOTE: No, really. Presumably this means something different for nonblocking sockets...
Timeout = c.int(os.EWOULDBLOCK), Timeout = c.int(posix.EWOULDBLOCK),
Socket_Not_Bound = c.int(os.EINVAL), // The socket must be bound for this operation, but isn't. Socket_Not_Bound = c.int(posix.EINVAL), // The socket must be bound for this operation, but isn't.
} }
TCP_Send_Error :: enum c.int { TCP_Send_Error :: enum c.int {
None = 0, None = 0,
Aborted = c.int(os.ECONNABORTED), Aborted = c.int(posix.ECONNABORTED),
Connection_Closed = c.int(os.ECONNRESET), Connection_Closed = c.int(posix.ECONNRESET),
Not_Connected = c.int(os.ENOTCONN), Not_Connected = c.int(posix.ENOTCONN),
Shutdown = c.int(os.ESHUTDOWN), Shutdown = ESHUTDOWN,
// The send queue was full. // The send queue was full.
// This is usually a transient issue. // This is usually a transient issue.
// //
// This also shouldn't normally happen on Linux, as data is dropped if it // This also shouldn't normally happen on Linux, as data is dropped if it
// doesn't fit in the send queue. // doesn't fit in the send queue.
No_Buffer_Space_Available = c.int(os.ENOBUFS), No_Buffer_Space_Available = c.int(posix.ENOBUFS),
Offline = c.int(os.ENETDOWN), Offline = c.int(posix.ENETDOWN),
Host_Unreachable = c.int(os.EHOSTUNREACH), Host_Unreachable = c.int(posix.EHOSTUNREACH),
Interrupted = c.int(os.EINTR), // A signal occurred before any data was transmitted. See signal(7). Interrupted = c.int(posix.EINTR), // A signal occurred before any data was transmitted. See signal(7).
// NOTE: No, really. Presumably this means something different for nonblocking sockets... // NOTE: No, really. Presumably this means something different for nonblocking sockets...
// The send timeout duration passed before all data was sent. See Socket_Option.Send_Timeout. // The send timeout duration passed before all data was sent. See Socket_Option.Send_Timeout.
Timeout = c.int(os.EWOULDBLOCK), Timeout = c.int(posix.EWOULDBLOCK),
Not_Socket = c.int(os.ENOTSOCK), // The so-called socket is not an open socket. Not_Socket = c.int(posix.ENOTSOCK), // The so-called socket is not an open socket.
} }
// TODO // TODO
UDP_Send_Error :: enum c.int { UDP_Send_Error :: enum c.int {
None = 0, None = 0,
Message_Too_Long = c.int(os.EMSGSIZE), // The message is larger than the maximum UDP packet size. No data was sent. Message_Too_Long = c.int(posix.EMSGSIZE), // The message is larger than the maximum UDP packet size. No data was sent.
// TODO: not sure what the exact circumstances for this is yet // TODO: not sure what the exact circumstances for this is yet
Network_Unreachable = c.int(os.ENETUNREACH), Network_Unreachable = c.int(posix.ENETUNREACH),
No_Outbound_Ports_Available = c.int(os.EAGAIN), // There are no more emphemeral outbound ports available to bind the socket to, in order to send. No_Outbound_Ports_Available = c.int(posix.EAGAIN), // There are no more emphemeral outbound ports available to bind the socket to, in order to send.
// The send timeout duration passed before all data was sent. See Socket_Option.Send_Timeout. // The send timeout duration passed before all data was sent. See Socket_Option.Send_Timeout.
// NOTE: No, really. Presumably this means something different for nonblocking sockets... // NOTE: No, really. Presumably this means something different for nonblocking sockets...
Timeout = c.int(os.EWOULDBLOCK), Timeout = c.int(posix.EWOULDBLOCK),
Not_Socket = c.int(os.ENOTSOCK), // The so-called socket is not an open socket. Not_Socket = c.int(posix.ENOTSOCK), // The so-called socket is not an open socket.
Not_Descriptor = c.int(os.EBADF), // The so-called socket is, in fact, not even a valid descriptor. Not_Descriptor = c.int(posix.EBADF), // The so-called socket is, in fact, not even a valid descriptor.
Bad_Buffer = c.int(os.EFAULT), // The buffer did not point to a valid location in memory. Bad_Buffer = c.int(posix.EFAULT), // The buffer did not point to a valid location in memory.
Interrupted = c.int(os.EINTR), // A signal occurred before any data was transmitted. See signal(7). Interrupted = c.int(posix.EINTR), // A signal occurred before any data was transmitted. See signal(7).
// The send queue was full. // The send queue was full.
// This is usually a transient issue. // This is usually a transient issue.
// //
// This also shouldn't normally happen on Linux, as data is dropped if it // This also shouldn't normally happen on Linux, as data is dropped if it
// doesn't fit in the send queue. // doesn't fit in the send queue.
No_Buffer_Space_Available = c.int(os.ENOBUFS), No_Buffer_Space_Available = c.int(posix.ENOBUFS),
No_Memory_Available = c.int(os.ENOMEM), // No memory was available to properly manage the send queue. No_Memory_Available = c.int(posix.ENOMEM), // No memory was available to properly manage the send queue.
} }
Shutdown_Manner :: enum c.int { Shutdown_Manner :: enum c.int {
Receive = c.int(os.SHUT_RD), Receive = c.int(posix.SHUT_RD),
Send = c.int(os.SHUT_WR), Send = c.int(posix.SHUT_WR),
Both = c.int(os.SHUT_RDWR), Both = c.int(posix.SHUT_RDWR),
} }
Shutdown_Error :: enum c.int { Shutdown_Error :: enum c.int {
None = 0, None = 0,
Aborted = c.int(os.ECONNABORTED), Aborted = c.int(posix.ECONNABORTED),
Reset = c.int(os.ECONNRESET), Reset = c.int(posix.ECONNRESET),
Offline = c.int(os.ENETDOWN), Offline = c.int(posix.ENETDOWN),
Not_Connected = c.int(os.ENOTCONN), Not_Connected = c.int(posix.ENOTCONN),
Not_Socket = c.int(os.ENOTSOCK), Not_Socket = c.int(posix.ENOTSOCK),
Invalid_Manner = c.int(os.EINVAL), Invalid_Manner = c.int(posix.EINVAL),
} }
Socket_Option_Error :: enum c.int { Socket_Option_Error :: enum c.int {
None = 0, None = 0,
Offline = c.int(os.ENETDOWN), Offline = c.int(posix.ENETDOWN),
Timeout_When_Keepalive_Set = c.int(os.ENETRESET), Timeout_When_Keepalive_Set = c.int(posix.ENETRESET),
Invalid_Option_For_Socket = c.int(os.ENOPROTOOPT), Invalid_Option_For_Socket = c.int(posix.ENOPROTOOPT),
Reset_When_Keepalive_Set = c.int(os.ENOTCONN), Reset_When_Keepalive_Set = c.int(posix.ENOTCONN),
Not_Socket = c.int(os.ENOTSOCK), Not_Socket = c.int(posix.ENOTSOCK),
} }
Set_Blocking_Error :: enum c.int { Set_Blocking_Error :: enum c.int {
+69 -39
View File
@@ -20,60 +20,57 @@ package net
Feoramund: FreeBSD platform code Feoramund: FreeBSD platform code
*/ */
import "core:os"
import "core:strings" import "core:strings"
import "core:sys/posix"
foreign import lib "system:System.framework"
@(private) @(private)
_enumerate_interfaces :: proc(allocator := context.allocator) -> (interfaces: []Network_Interface, err: Network_Error) { _enumerate_interfaces :: proc(allocator := context.allocator) -> (interfaces: []Network_Interface, err: Network_Error) {
context.allocator = allocator context.allocator = allocator
head: ^os.ifaddrs head: ^ifaddrs
if getifaddrs(&head) != .OK {
if res := os._getifaddrs(&head); res < 0 {
return {}, .Unable_To_Enumerate_Network_Interfaces return {}, .Unable_To_Enumerate_Network_Interfaces
} }
defer freeifaddrs(head)
/* ifaces: map[string]Network_Interface
Unlike Windows, *nix regrettably doesn't return all it knows about an interface in one big struct.
We're going to have to iterate over a list and coalesce information as we go.
*/
ifaces: map[string]^Network_Interface
defer delete(ifaces) defer delete(ifaces)
for ifaddr := head; ifaddr != nil; ifaddr = ifaddr.next { for ifaddr := head; ifaddr != nil; ifaddr = ifaddr.next {
adapter_name := string(ifaddr.name) adapter_name := string(ifaddr.name)
/* key_ptr, iface, inserted, mem_err := map_entry(&ifaces, adapter_name)
Check if we have seen this interface name before so we can reuse the `Network_Interface`. if mem_err == nil && inserted {
Else, create a new one. key_ptr^, mem_err = strings.clone(adapter_name)
*/ iface.adapter_name = key_ptr^
if adapter_name not_in ifaces { }
ifaces[adapter_name] = new(Network_Interface) if mem_err != nil {
ifaces[adapter_name].adapter_name = strings.clone(adapter_name) return {}, .Unable_To_Enumerate_Network_Interfaces
} }
iface := ifaces[adapter_name]
address: Address address: Address
netmask: Netmask netmask: Netmask
if ifaddr.address != nil { if ifaddr.addr != nil {
switch int(ifaddr.address.family) { #partial switch ifaddr.addr.sa_family {
case os.AF_INET, os.AF_INET6: case .INET, .INET6:
address = _sockaddr_basic_to_endpoint(ifaddr.address).address address = _sockaddr_basic_to_endpoint(ifaddr.addr).address
} }
} }
if ifaddr.netmask != nil { if ifaddr.netmask != nil {
switch int(ifaddr.netmask.family) { #partial switch ifaddr.netmask.sa_family {
case os.AF_INET, os.AF_INET6: case .INET, .INET6:
netmask = Netmask(_sockaddr_basic_to_endpoint(ifaddr.netmask).address) netmask = Netmask(_sockaddr_basic_to_endpoint(ifaddr.netmask).address)
} }
} }
if ifaddr.broadcast_or_dest != nil && .BROADCAST in ifaddr.flags { if ifaddr.dstaddr != nil && .BROADCAST in ifaddr.flags {
switch int(ifaddr.broadcast_or_dest.family) { #partial switch ifaddr.dstaddr.sa_family {
case os.AF_INET, os.AF_INET6: case .INET, .INET6:
broadcast := _sockaddr_basic_to_endpoint(ifaddr.broadcast_or_dest).address broadcast := _sockaddr_basic_to_endpoint(ifaddr.dstaddr).address
append(&iface.multicast, broadcast) append(&iface.multicast, broadcast)
} }
} }
@@ -105,18 +102,51 @@ _enumerate_interfaces :: proc(allocator := context.allocator) -> (interfaces: []
iface.link.state = state iface.link.state = state
} }
/* interfaces = make([]Network_Interface, len(ifaces))
Free the OS structures. i: int
*/
os._freeifaddrs(head)
/*
Turn the map into a slice to return.
*/
_interfaces := make([dynamic]Network_Interface, 0, allocator)
for _, iface in ifaces { for _, iface in ifaces {
append(&_interfaces, iface^) interfaces[i] = iface
free(iface) i += 1
} }
return _interfaces[:], {} return interfaces, nil
}
@(private)
IF_Flag :: enum u32 {
UP,
BROADCAST,
DEBUG,
LOOPBACK,
POINTTOPOINT,
NOTRAILERS,
RUNNING,
NOARP,
PROMISC,
ALLMULTI,
OACTIVE,
SIMPLEX,
LINK0,
LINK1,
LINK2,
MULTICAST,
}
@(private)
IF_Flags :: bit_set[IF_Flag; u32]
@(private)
ifaddrs :: struct {
next: ^ifaddrs,
name: cstring,
flags: IF_Flags,
addr: ^posix.sockaddr,
netmask: ^posix.sockaddr,
dstaddr: ^posix.sockaddr,
data: rawptr,
}
@(private)
foreign lib {
getifaddrs :: proc(ifap: ^^ifaddrs) -> posix.result ---
freeifaddrs :: proc(ifp: ^ifaddrs) ---
} }
+126 -117
View File
@@ -21,44 +21,45 @@ package net
*/ */
import "core:c" import "core:c"
import "core:os"
import "core:sys/posix" import "core:sys/posix"
import "core:time" import "core:time"
Socket_Option :: enum c.int { Socket_Option :: enum c.int {
Broadcast = c.int(os.SO_BROADCAST), Broadcast = c.int(posix.Sock_Option.BROADCAST),
Reuse_Address = c.int(os.SO_REUSEADDR), Reuse_Address = c.int(posix.Sock_Option.REUSEADDR),
Keep_Alive = c.int(os.SO_KEEPALIVE), Keep_Alive = c.int(posix.Sock_Option.KEEPALIVE),
Out_Of_Bounds_Data_Inline = c.int(os.SO_OOBINLINE), Out_Of_Bounds_Data_Inline = c.int(posix.Sock_Option.OOBINLINE),
TCP_Nodelay = c.int(os.TCP_NODELAY), TCP_Nodelay = c.int(posix.TCP_NODELAY),
Linger = c.int(os.SO_LINGER), Linger = c.int(posix.Sock_Option.LINGER),
Receive_Buffer_Size = c.int(os.SO_RCVBUF), Receive_Buffer_Size = c.int(posix.Sock_Option.RCVBUF),
Send_Buffer_Size = c.int(os.SO_SNDBUF), Send_Buffer_Size = c.int(posix.Sock_Option.SNDBUF),
Receive_Timeout = c.int(os.SO_RCVTIMEO), Receive_Timeout = c.int(posix.Sock_Option.RCVTIMEO),
Send_Timeout = c.int(os.SO_SNDTIMEO), Send_Timeout = c.int(posix.Sock_Option.SNDTIMEO),
} }
@(private) @(private)
_create_socket :: proc(family: Address_Family, protocol: Socket_Protocol) -> (socket: Any_Socket, err: Network_Error) { _create_socket :: proc(family: Address_Family, protocol: Socket_Protocol) -> (socket: Any_Socket, err: Network_Error) {
c_type, c_protocol, c_family: int c_type: posix.Sock
c_protocol: posix.Protocol
c_family: posix.AF
switch family { switch family {
case .IP4: c_family = os.AF_INET case .IP4: c_family = .INET
case .IP6: c_family = os.AF_INET6 case .IP6: c_family = .INET6
case: case:
unreachable() unreachable()
} }
switch protocol { switch protocol {
case .TCP: c_type = os.SOCK_STREAM; c_protocol = os.IPPROTO_TCP case .TCP: c_type = .STREAM; c_protocol = .TCP
case .UDP: c_type = os.SOCK_DGRAM; c_protocol = os.IPPROTO_UDP case .UDP: c_type = .DGRAM; c_protocol = .UDP
case: case:
unreachable() unreachable()
} }
sock, sock_err := os.socket(c_family, c_type, c_protocol) sock := posix.socket(c_family, c_type, c_protocol)
if sock_err != nil { if sock < 0 {
err = Create_Socket_Error(os.is_platform_error(sock_err) or_else -1) err = Create_Socket_Error(posix.errno())
return return
} }
@@ -86,10 +87,10 @@ _dial_tcp_from_endpoint :: proc(endpoint: Endpoint, options := default_tcp_optio
_ = set_option(skt, .Reuse_Address, true) _ = set_option(skt, .Reuse_Address, true)
sockaddr := _endpoint_to_sockaddr(endpoint) sockaddr := _endpoint_to_sockaddr(endpoint)
res := os.connect(os.Socket(skt), (^os.SOCKADDR)(&sockaddr), i32(sockaddr.len)) if posix.connect(posix.FD(skt), (^posix.sockaddr)(&sockaddr), posix.socklen_t(sockaddr.ss_len)) != .OK {
if res != nil { errno := posix.errno()
close(skt) close(skt)
return {}, Dial_Error(os.is_platform_error(res) or_else -1) return {}, Dial_Error(errno)
} }
return return
@@ -102,14 +103,15 @@ MAX_PRIVILEGED_PORT :: 1023
_bind :: proc(skt: Any_Socket, ep: Endpoint) -> (err: Network_Error) { _bind :: proc(skt: Any_Socket, ep: Endpoint) -> (err: Network_Error) {
sockaddr := _endpoint_to_sockaddr(ep) sockaddr := _endpoint_to_sockaddr(ep)
s := any_socket_to_socket(skt) s := any_socket_to_socket(skt)
res := os.bind(os.Socket(s), (^os.SOCKADDR)(&sockaddr), i32(sockaddr.len)) if posix.bind(posix.FD(s), (^posix.sockaddr)(&sockaddr), posix.socklen_t(sockaddr.ss_len)) != .OK {
if res != nil { errno := posix.errno()
if res == os.EACCES && ep.port <= MAX_PRIVILEGED_PORT { if errno == .EACCES && ep.port <= MAX_PRIVILEGED_PORT {
err = .Privileged_Port_Without_Root err = .Privileged_Port_Without_Root
} else { } else {
err = Bind_Error(os.is_platform_error(res) or_else -1) err = Bind_Error(errno)
} }
} }
return return
} }
@@ -131,9 +133,8 @@ _listen_tcp :: proc(interface_endpoint: Endpoint, backlog := 1000) -> (skt: TCP_
bind(sock, interface_endpoint) or_return bind(sock, interface_endpoint) or_return
res := os.listen(os.Socket(skt), backlog) if posix.listen(posix.FD(skt), i32(backlog)) != .OK {
if res != nil { err = Listen_Error(posix.errno())
err = Listen_Error(os.is_platform_error(res) or_else -1)
return return
} }
@@ -144,34 +145,34 @@ _listen_tcp :: proc(interface_endpoint: Endpoint, backlog := 1000) -> (skt: TCP_
_bound_endpoint :: proc(sock: Any_Socket) -> (ep: Endpoint, err: Network_Error) { _bound_endpoint :: proc(sock: Any_Socket) -> (ep: Endpoint, err: Network_Error) {
addr: posix.sockaddr_storage addr: posix.sockaddr_storage
addr_len := posix.socklen_t(size_of(addr)) addr_len := posix.socklen_t(size_of(addr))
res := posix.getsockname(posix.FD(any_socket_to_socket(sock)), (^posix.sockaddr)(&addr), &addr_len) if posix.getsockname(posix.FD(any_socket_to_socket(sock)), (^posix.sockaddr)(&addr), &addr_len) != .OK {
if res != .OK {
err = Listen_Error(posix.errno()) err = Listen_Error(posix.errno())
return return
} }
ep = _sockaddr_to_endpoint((^os.SOCKADDR_STORAGE_LH)(&addr))
ep = _sockaddr_to_endpoint(&addr)
return return
} }
@(private) @(private)
_accept_tcp :: proc(sock: TCP_Socket, options := default_tcp_options) -> (client: TCP_Socket, source: Endpoint, err: Network_Error) { _accept_tcp :: proc(sock: TCP_Socket, options := default_tcp_options) -> (client: TCP_Socket, source: Endpoint, err: Network_Error) {
sockaddr: os.SOCKADDR_STORAGE_LH addr: posix.sockaddr_storage
sockaddrlen := c.int(size_of(sockaddr)) addr_len := posix.socklen_t(size_of(addr))
client_sock := posix.accept(posix.FD(sock), (^posix.sockaddr)(&addr), &addr_len)
client_sock, client_sock_err := os.accept(os.Socket(sock), cast(^os.SOCKADDR) &sockaddr, &sockaddrlen) if client_sock < 0 {
if client_sock_err != nil { err = Accept_Error(posix.errno())
err = Accept_Error(os.is_platform_error(client_sock_err) or_else -1)
return return
} }
client = TCP_Socket(client_sock) client = TCP_Socket(client_sock)
source = _sockaddr_to_endpoint(&sockaddr) source = _sockaddr_to_endpoint(&addr)
return return
} }
@(private) @(private)
_close :: proc(skt: Any_Socket) { _close :: proc(skt: Any_Socket) {
s := any_socket_to_socket(skt) s := any_socket_to_socket(skt)
os.close(os.Handle(os.Socket(s))) posix.close(posix.FD(s))
} }
@(private) @(private)
@@ -179,11 +180,13 @@ _recv_tcp :: proc(skt: TCP_Socket, buf: []byte) -> (bytes_read: int, err: Networ
if len(buf) <= 0 { if len(buf) <= 0 {
return return
} }
res, res_err := os.recv(os.Socket(skt), buf, 0)
if res_err != nil { res := posix.recv(posix.FD(skt), raw_data(buf), len(buf), {})
err = TCP_Recv_Error(os.is_platform_error(res_err) or_else -1) if res < 0 {
err = TCP_Recv_Error(posix.errno())
return return
} }
return int(res), nil return int(res), nil
} }
@@ -193,11 +196,11 @@ _recv_udp :: proc(skt: UDP_Socket, buf: []byte) -> (bytes_read: int, remote_endp
return return
} }
from: os.SOCKADDR_STORAGE_LH from: posix.sockaddr_storage
fromsize := c.int(size_of(from)) fromsize := posix.socklen_t(size_of(from))
res, res_err := os.recvfrom(os.Socket(skt), buf, 0, cast(^os.SOCKADDR) &from, &fromsize) res := posix.recvfrom(posix.FD(skt), raw_data(buf), len(buf), {}, (^posix.sockaddr)(&from), &fromsize)
if res_err != nil { if res < 0 {
err = UDP_Recv_Error(os.is_platform_error(res_err) or_else -1) err = UDP_Recv_Error(posix.errno())
return return
} }
@@ -211,15 +214,19 @@ _send_tcp :: proc(skt: TCP_Socket, buf: []byte) -> (bytes_written: int, err: Net
for bytes_written < len(buf) { for bytes_written < len(buf) {
limit := min(int(max(i32)), len(buf) - bytes_written) limit := min(int(max(i32)), len(buf) - bytes_written)
remaining := buf[bytes_written:][:limit] remaining := buf[bytes_written:][:limit]
res, res_err := os.send(os.Socket(skt), remaining, os.MSG_NOSIGNAL) res := posix.send(posix.FD(skt), raw_data(remaining), len(remaining), {.NOSIGNAL})
if res_err == os.EPIPE { if res < 0 {
// EPIPE arises if the socket has been closed remotely. errno := posix.errno()
err = TCP_Send_Error.Connection_Closed if errno == .EPIPE {
return // EPIPE arises if the socket has been closed remotely.
} else if res_err != nil { err = TCP_Send_Error.Connection_Closed
err = TCP_Send_Error(os.is_platform_error(res_err) or_else -1) return
}
err = TCP_Send_Error(errno)
return return
} }
bytes_written += int(res) bytes_written += int(res)
} }
return return
@@ -231,15 +238,19 @@ _send_udp :: proc(skt: UDP_Socket, buf: []byte, to: Endpoint) -> (bytes_written:
for bytes_written < len(buf) { for bytes_written < len(buf) {
limit := min(1<<31, len(buf) - bytes_written) limit := min(1<<31, len(buf) - bytes_written)
remaining := buf[bytes_written:][:limit] remaining := buf[bytes_written:][:limit]
res, res_err := os.sendto(os.Socket(skt), remaining, os.MSG_NOSIGNAL, cast(^os.SOCKADDR)&toaddr, i32(toaddr.len)) res := posix.sendto(posix.FD(skt), raw_data(remaining), len(remaining), {.NOSIGNAL}, (^posix.sockaddr)(&toaddr), posix.socklen_t(toaddr.ss_len))
if res_err == os.EPIPE { if res < 0 {
// EPIPE arises if the socket has been closed remotely. errno := posix.errno()
err = UDP_Send_Error.Not_Socket if errno == .EPIPE {
return // EPIPE arises if the socket has been closed remotely.
} else if res_err != nil { err = UDP_Send_Error.Not_Socket
err = UDP_Send_Error(os.is_platform_error(res_err) or_else -1) return
}
err = UDP_Send_Error(errno)
return return
} }
bytes_written += int(res) bytes_written += int(res)
} }
return return
@@ -248,26 +259,25 @@ _send_udp :: proc(skt: UDP_Socket, buf: []byte, to: Endpoint) -> (bytes_written:
@(private) @(private)
_shutdown :: proc(skt: Any_Socket, manner: Shutdown_Manner) -> (err: Network_Error) { _shutdown :: proc(skt: Any_Socket, manner: Shutdown_Manner) -> (err: Network_Error) {
s := any_socket_to_socket(skt) s := any_socket_to_socket(skt)
res := os.shutdown(os.Socket(s), int(manner)) if posix.shutdown(posix.FD(s), posix.Shut(manner)) != .OK {
if res != nil { err = Shutdown_Error(posix.errno())
return Shutdown_Error(os.is_platform_error(res) or_else -1)
} }
return return
} }
@(private) @(private)
_set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #caller_location) -> Network_Error { _set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #caller_location) -> Network_Error {
level := os.SOL_SOCKET if option != .TCP_Nodelay else os.IPPROTO_TCP level := posix.SOL_SOCKET if option != .TCP_Nodelay else posix.IPPROTO_TCP
// NOTE(tetra, 2022-02-15): On Linux, you cannot merely give a single byte for a bool; // NOTE(tetra, 2022-02-15): On Linux, you cannot merely give a single byte for a bool;
// it _has_ to be a b32. // it _has_ to be a b32.
// I haven't tested if you can give more than that. // I haven't tested if you can give more than that.
bool_value: b32 bool_value: b32
int_value: i32 int_value: posix.socklen_t
timeval_value: os.Timeval timeval_value: posix.timeval
ptr: rawptr ptr: rawptr
len: os.socklen_t len: posix.socklen_t
switch option { switch option {
case case
@@ -302,8 +312,8 @@ _set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #ca
t := value.(time.Duration) or_else panic("set_option() value must be a time.Duration here", loc) t := value.(time.Duration) or_else panic("set_option() value must be a time.Duration here", loc)
micros := i64(time.duration_microseconds(t)) micros := i64(time.duration_microseconds(t))
timeval_value.microseconds = int(micros % 1e6) timeval_value.tv_usec = posix.suseconds_t(micros % 1e6)
timeval_value.seconds = (micros - i64(timeval_value.microseconds)) / 1e6 timeval_value.tv_sec = posix.time_t(micros - i64(timeval_value.tv_usec)) / 1e6
ptr = &timeval_value ptr = &timeval_value
len = size_of(timeval_value) len = size_of(timeval_value)
@@ -312,12 +322,12 @@ _set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #ca
.Send_Buffer_Size: .Send_Buffer_Size:
// TODO: check for out of range values and return .Value_Out_Of_Range? // TODO: check for out of range values and return .Value_Out_Of_Range?
switch i in value { switch i in value {
case i8, u8: i2 := i; int_value = os.socklen_t((^u8)(&i2)^) case i8, u8: i2 := i; int_value = posix.socklen_t((^u8)(&i2)^)
case i16, u16: i2 := i; int_value = os.socklen_t((^u16)(&i2)^) case i16, u16: i2 := i; int_value = posix.socklen_t((^u16)(&i2)^)
case i32, u32: i2 := i; int_value = os.socklen_t((^u32)(&i2)^) case i32, u32: i2 := i; int_value = posix.socklen_t((^u32)(&i2)^)
case i64, u64: i2 := i; int_value = os.socklen_t((^u64)(&i2)^) case i64, u64: i2 := i; int_value = posix.socklen_t((^u64)(&i2)^)
case i128, u128: i2 := i; int_value = os.socklen_t((^u128)(&i2)^) case i128, u128: i2 := i; int_value = posix.socklen_t((^u128)(&i2)^)
case int, uint: i2 := i; int_value = os.socklen_t((^uint)(&i2)^) case int, uint: i2 := i; int_value = posix.socklen_t((^uint)(&i2)^)
case: case:
panic("set_option() value must be an integer here", loc) panic("set_option() value must be an integer here", loc)
} }
@@ -326,9 +336,8 @@ _set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #ca
} }
skt := any_socket_to_socket(s) skt := any_socket_to_socket(s)
res := os.setsockopt(os.Socket(skt), int(level), int(option), ptr, len) if posix.setsockopt(posix.FD(skt), i32(level), posix.Sock_Option(option), ptr, len) != .OK {
if res != nil { return Socket_Option_Error(posix.errno())
return Socket_Option_Error(os.is_platform_error(res) or_else -1)
} }
return nil return nil
@@ -338,42 +347,42 @@ _set_option :: proc(s: Any_Socket, option: Socket_Option, value: any, loc := #ca
_set_blocking :: proc(socket: Any_Socket, should_block: bool) -> (err: Network_Error) { _set_blocking :: proc(socket: Any_Socket, should_block: bool) -> (err: Network_Error) {
socket := any_socket_to_socket(socket) socket := any_socket_to_socket(socket)
flags, getfl_err := os.fcntl(int(socket), os.F_GETFL, 0) flags_ := posix.fcntl(posix.FD(socket), .GETFL, 0)
if getfl_err != nil { if flags_ < 0 {
return Set_Blocking_Error(os.is_platform_error(getfl_err) or_else -1) return Set_Blocking_Error(posix.errno())
} }
flags := transmute(posix.O_Flags)flags_
if should_block { if should_block {
flags &~= int(os.O_NONBLOCK) flags -= {.NONBLOCK}
} else { } else {
flags |= int(os.O_NONBLOCK) flags += {.NONBLOCK}
} }
_, setfl_err := os.fcntl(int(socket), os.F_SETFL, flags) if posix.fcntl(posix.FD(socket), .SETFL, flags) < 0 {
if setfl_err != nil { return Set_Blocking_Error(posix.errno())
return Set_Blocking_Error(os.is_platform_error(setfl_err) or_else -1)
} }
return nil return nil
} }
@private @private
_endpoint_to_sockaddr :: proc(ep: Endpoint) -> (sockaddr: os.SOCKADDR_STORAGE_LH) { _endpoint_to_sockaddr :: proc(ep: Endpoint) -> (sockaddr: posix.sockaddr_storage) {
switch a in ep.address { switch a in ep.address {
case IP4_Address: case IP4_Address:
(^os.sockaddr_in)(&sockaddr)^ = os.sockaddr_in { (^posix.sockaddr_in)(&sockaddr)^ = posix.sockaddr_in {
sin_port = u16be(ep.port), sin_port = u16be(ep.port),
sin_addr = transmute(os.in_addr) a, sin_addr = transmute(posix.in_addr)a,
sin_family = u8(os.AF_INET), sin_family = .INET,
sin_len = size_of(os.sockaddr_in), sin_len = size_of(posix.sockaddr_in),
} }
return return
case IP6_Address: case IP6_Address:
(^os.sockaddr_in6)(&sockaddr)^ = os.sockaddr_in6 { (^posix.sockaddr_in6)(&sockaddr)^ = posix.sockaddr_in6 {
sin6_port = u16be(ep.port), sin6_port = u16be(ep.port),
sin6_addr = transmute(os.in6_addr) a, sin6_addr = transmute(posix.in6_addr)a,
sin6_family = u8(os.AF_INET6), sin6_family = .INET6,
sin6_len = size_of(os.sockaddr_in6), sin6_len = size_of(posix.sockaddr_in6),
} }
return return
} }
@@ -381,21 +390,21 @@ _endpoint_to_sockaddr :: proc(ep: Endpoint) -> (sockaddr: os.SOCKADDR_STORAGE_LH
} }
@private @private
_sockaddr_to_endpoint :: proc(native_addr: ^os.SOCKADDR_STORAGE_LH) -> (ep: Endpoint) { _sockaddr_to_endpoint :: proc(native_addr: ^posix.sockaddr_storage) -> (ep: Endpoint) {
switch native_addr.family { #partial switch native_addr.ss_family {
case u8(os.AF_INET): case .INET:
addr := cast(^os.sockaddr_in) native_addr addr := cast(^posix.sockaddr_in)native_addr
port := int(addr.sin_port) port := int(addr.sin_port)
ep = Endpoint { ep = Endpoint {
address = IP4_Address(transmute([4]byte) addr.sin_addr), address = IP4_Address(transmute([4]byte)addr.sin_addr),
port = port, port = port,
} }
case u8(os.AF_INET6): case .INET6:
addr := cast(^os.sockaddr_in6) native_addr addr := cast(^posix.sockaddr_in6)native_addr
port := int(addr.sin6_port) port := int(addr.sin6_port)
ep = Endpoint { ep = Endpoint {
address = IP6_Address(transmute([8]u16be) addr.sin6_addr), address = IP6_Address(transmute([8]u16be)addr.sin6_addr),
port = port, port = port,
} }
case: case:
panic("native_addr is neither IP4 or IP6 address") panic("native_addr is neither IP4 or IP6 address")
@@ -404,21 +413,21 @@ _sockaddr_to_endpoint :: proc(native_addr: ^os.SOCKADDR_STORAGE_LH) -> (ep: Endp
} }
@(private) @(private)
_sockaddr_basic_to_endpoint :: proc(native_addr: ^os.SOCKADDR) -> (ep: Endpoint) { _sockaddr_basic_to_endpoint :: proc(native_addr: ^posix.sockaddr) -> (ep: Endpoint) {
switch u16(native_addr.family) { #partial switch native_addr.sa_family {
case u16(os.AF_INET): case .INET:
addr := cast(^os.sockaddr_in) native_addr addr := cast(^posix.sockaddr_in)native_addr
port := int(addr.sin_port) port := int(addr.sin_port)
ep = Endpoint { ep = Endpoint {
address = IP4_Address(transmute([4]byte) addr.sin_addr), address = IP4_Address(transmute([4]byte)addr.sin_addr),
port = port, port = port,
} }
case u16(os.AF_INET6): case .INET6:
addr := cast(^os.sockaddr_in6) native_addr addr := cast(^posix.sockaddr_in6)native_addr
port := int(addr.sin6_port) port := int(addr.sin6_port)
ep = Endpoint { ep = Endpoint {
address = IP6_Address(transmute([8]u16be) addr.sin6_addr), address = IP6_Address(transmute([8]u16be)addr.sin6_addr),
port = port, port = port,
} }
case: case:
panic("native_addr is neither IP4 or IP6 address") panic("native_addr is neither IP4 or IP6 address")