Landin library reference discuss source

platform/windows/sockets

Importable on every target; it declares its items only where compiler.os == windows.

Windows Sockets, ws2_32's calls, and iphlpapi's interface names, raw, under the Windows x64 C convention: making, binding, connecting and closing sockets, sending and receiving, their options, select, and the overlapped calls WSARecv, WSASend, WSARecvFrom and WSASendTo, with ConnectEx and AcceptEx reached through WSAIoctl. A call that fails returns socket_error or invalid_socket and leaves the reason for socket_last_error; started makes the one WSAStartup call a process needs before its first socket.

It is a module of its own because refine links platform/windows into every Windows program. Its calls' C names are send, connect and bind, which a program may give its own C code, so only a program that imports this module, as the hosted network providers do, has them declared (D2281). Every hosted system may import it, and off Windows it declares nothing.

Items

When compiler.os == windows

public accept_routine: type = extern(c)
    (listener: windows.handle, accepted: windows.handle, addresses: ptr mut u8,
     count: u32, local_room: u32, remote_room: u32,
     received: ptr mut u32, record: usize) -> (done: i32)

AcceptEx: accept a connection on listener into accepted, a new socket of its family, receiving nothing, both addresses into addresses, each given address_room bytes.

When compiler.os == windows

public connect_routine: type = extern(c)
    (socket: windows.handle, name: ptr u8, name_length: i32, bytes: usize,
     count: u32, sent: ptr mut u32, record: usize) -> (done: i32)

ConnectEx: connect socket, which must be bound, to the address at name, sending nothing, with record an overlapped.

When compiler.os == windows

public socket_address: type = struct
    bytes: [28]u8
    length: i32
end socket_address

An address of either family as the system lays it out: room for a SOCKADDR_IN6, which is the larger, and its length in bytes.

When compiler.os == windows

public socket_buffer: type = struct
    length: u32
    reserved: u32
    bytes: usize
end socket_buffer

WSABUF: one buffer of a call, its length and its first byte.

When compiler.os == windows

public socket_set: type = struct
    count: u32
    sockets: [1]windows.handle
end socket_set

fd_set as Windows Sockets lays it out: a count and the sockets, room for one here.

When compiler.os == windows

public time_limit: type = struct
    seconds: i32
    microseconds: i32
end time_limit

timeval: seconds and microseconds, 32 bits each.

When compiler.os == windows

public accept_extension: [16]u8 =
    [0xF1, 0x7D, 0x36, 0xB5, 0xAC, 0xCB, 0xCF, 0x11,
     0x95, 0xCA, 0x00, 0x80, 0x5F, 0x48, 0xA1, 0x92]

The GUID that names AcceptEx, WSAID_ACCEPTEX.

When compiler.os == windows

public address_room: u32 = 44

What AcceptEx takes for each address: the largest socket address and 16 bytes more.

When compiler.os == windows

public af_inet: i32 = 2

The address families, AF_INET and AF_INET6.

When compiler.os == windows

public af_inet6: i32 = 23

AF_INET6: IPv6.

When compiler.os == windows

public connect_extension: [16]u8 =
    [0xB9, 0x07, 0xA2, 0x25, 0xF3, 0xDD, 0x60, 0x46,
     0x8E, 0xE9, 0x76, 0xE5, 0x8C, 0x74, 0x06, 0x3E]

The GUID that names ConnectEx, WSAID_CONNECTEX, as the 16 bytes socket_control is given.

When compiler.os == windows

public fionbio: i32 = -2147195266

Set a socket to block or not, ioctlsocket with FIONBIO.

When compiler.os == windows

public get_extension_function: u32 = 0xC8000006

SIO_GET_EXTENSION_FUNCTION_POINTER.

When compiler.os == windows

public invalid_socket: windows.handle = 0xFFFFFFFFFFFFFFFF

INVALID_SOCKET: what a call that makes a socket gives when it fails, all ones.

When compiler.os == windows

public ipproto_ipv6: i32 = 41

IPPROTO_IPV6: the level of IPv6's options.

When compiler.os == windows

public ipproto_tcp: i32 = 6

IPPROTO_TCP: the level of TCP's options.

When compiler.os == windows

public ipv6_only: i32 = 27

IPV6_V6ONLY: an IPv6 socket takes IPv6 alone.

When compiler.os == windows

public sd_both: i32 = 2

SD_BOTH: stop receiving and sending.

When compiler.os == windows

public sd_receive: i32 = 0

Stop receiving, sending or both, shutdown.

When compiler.os == windows

public sd_send: i32 = 1

SD_SEND: stop sending.

When compiler.os == windows

public so_error: i32 = 0x1007

SO_ERROR: the outcome a connection begun without waiting ended with.

When compiler.os == windows

public so_receive_timeout: i32 = 0x1006

SO_RCVTIMEO: how long a receive may wait, in milliseconds.

When compiler.os == windows

public so_send_timeout: i32 = 0x1005

SO_SNDTIMEO: how long a send may wait, in milliseconds.

When compiler.os == windows

public so_update_accept_context: i32 = 0x700B

The same for a socket AcceptEx accepted, SO_UPDATE_ACCEPT_CONTEXT.

When compiler.os == windows

public so_update_connect_context: i32 = 0x7010

The option that gives a socket ConnectEx connected the state getpeername, shutdown and the rest expect, SO_UPDATE_CONNECT_CONTEXT.

When compiler.os == windows

public sock_dgram: i32 = 2

SOCK_DGRAM: datagrams, UDP.

When compiler.os == windows

public sock_stream: i32 = 1

The kinds, SOCK_STREAM and SOCK_DGRAM.

When compiler.os == windows

public socket_error: i32 = -1

What a failing call returns: SOCKET_ERROR, and INVALID_SOCKET, all ones.

When compiler.os == windows

public sol_socket: i32 = 0xFFFF

Socket options, setsockopt and getsockopt: the level, the option and its value's bytes.

When compiler.os == windows

public tcp_no_delay: i32 = 1

TCP_NODELAY: send small writes at once.

When compiler.os == windows

public wsa_access: u32 = 10013

WSAEACCES.

When compiler.os == windows

public wsa_address_in_use: u32 = 10048

WSAEADDRINUSE.

wsa_address_unavailable

value platform/windows/sockets/sockets.ldn:57 ↑ index

When compiler.os == windows

public wsa_address_unavailable: u32 = 10049

WSAEADDRNOTAVAIL.

wsa_connection_aborted

value platform/windows/sockets/sockets.ldn:63 ↑ index

When compiler.os == windows

public wsa_connection_aborted: u32 = 10053

WSAECONNABORTED.

wsa_connection_refused

value platform/windows/sockets/sockets.ldn:73 ↑ index

When compiler.os == windows

public wsa_connection_refused: u32 = 10061

WSAECONNREFUSED.

When compiler.os == windows

public wsa_connection_reset: u32 = 10054

WSAECONNRESET.

wsa_family_unsupported

value platform/windows/sockets/sockets.ldn:53 ↑ index

When compiler.os == windows

public wsa_family_unsupported: u32 = 10047

WSAEAFNOSUPPORT.

wsa_flag_no_handle_inherit

value platform/windows/sockets/sockets.ldn:42 ↑ index

When compiler.os == windows

public wsa_flag_no_handle_inherit: u32 = 0x80

WSA_FLAG_NO_HANDLE_INHERIT: a child does not inherit the socket.

When compiler.os == windows

public wsa_flag_overlapped: u32 = 0x01

WSASocketW's flags: the socket may be used with overlapped calls, and a child does not inherit it.

When compiler.os == windows

public wsa_host_unreachable: u32 = 10065

WSAEHOSTUNREACH.

When compiler.os == windows

public wsa_interrupted: u32 = 10004

The Windows Sockets error codes the providers tell apart: WSAE*.

When compiler.os == windows

public wsa_message_size: u32 = 10040

WSAEMSGSIZE.

When compiler.os == windows

public wsa_network_reset: u32 = 10052

WSAENETRESET.

wsa_network_unreachable

value platform/windows/sockets/sockets.ldn:59 ↑ index

When compiler.os == windows

public wsa_network_unreachable: u32 = 10051

WSAENETUNREACH.

When compiler.os == windows

public wsa_not_connected: u32 = 10057

WSAENOTCONN.

When compiler.os == windows

public wsa_shut_down: u32 = 10058

WSAESHUTDOWN.

When compiler.os == windows

public wsa_timed_out: u32 = 10060

WSAETIMEDOUT.

When compiler.os == windows

public wsa_would_block: u32 = 10035

WSAEWOULDBLOCK.

When compiler.os == windows

public extern(c) link(symbol: "accept") accept:
    (socket: windows.handle, peer: usize, length: usize) -> (result: windows.handle)

Take the next connection made to the listener socket, accept: its socket or invalid_socket; the peer's address goes to peer when it is not zero.

When compiler.os == windows

public extern(c) link(symbol: "bind") bind:
    (socket: windows.handle, at: ptr u8, length: i32) -> (status: i32)

Bind, connect, listen and accept, bind, connect, listen and accept: zero or socket_error; accept's new socket or invalid_socket, its peer's address in peer when it is not zero.

When compiler.os == windows

public extern(c) link(symbol: "closesocket") close_socket:
    (socket: windows.handle) -> (status: i32)

Close a socket, closesocket: zero or socket_error.

When compiler.os == windows

public extern(c) link(symbol: "connect") connect:
    (socket: windows.handle, to: ptr u8, length: i32) -> (status: i32)

Connect socket to the address at to, connect: zero or socket_error.

When compiler.os == windows

public extern(c) link(symbol: "ioctlsocket") control:
    (socket: windows.handle, command: i32, value: ptr mut u32) -> (status: i32)

Set a socket to block, with value zero, or not, ioctlsocket with FIONBIO.

When compiler.os == windows

public extern(c) link(symbol: "getsockopt") get_option:
    (socket: windows.handle, level: i32, option: i32, value: ptr mut u8,
     length: ptr mut i32) -> (status: i32)

Read a socket option, getsockopt: zero or socket_error.

When compiler.os == windows

public extern(c) link(symbol: "if_nametoindex") interface_index:
    (name: ptr u8) -> (index: u32)

The interface number a name gives and the name of a number, if_nametoindex and if_indextoname: zero, or no name, when there is none.

When compiler.os == windows

public extern(c) link(symbol: "if_indextoname") interface_name:
    (index: u32, into: ptr mut u8) -> (name: usize)

The name of the interface index into into, if_indextoname: zero when there is none.

When compiler.os == windows

public extern(c) link(symbol: "listen") listen:
    (socket: windows.handle, backlog: i32) -> (status: i32)

Make socket a listener, listen: zero or socket_error.

When compiler.os == windows

public extern(c) link(symbol: "WSASocketW") make_socket:
    (family: i32, kind: i32, protocol: i32, information: usize,
     group: u32, flags: u32) -> (socket: windows.handle)

Make a socket, WSASocketW with no protocol information: its handle, or invalid_socket.

When compiler.os == windows

public extern(c) link(symbol: "getpeername") peer_name:
    (socket: windows.handle, into: ptr mut u8, length: ptr mut i32) -> (status: i32)

The address of a connection's peer, getpeername.

When compiler.os == windows

public extern(c) link(symbol: "recv") receive:
    (socket: windows.handle, into: ptr mut u8, count: i32, flags: i32)
    -> (got: i32)

Receive on a connected socket, recv: the bytes taken, zero once the peer has finished sending, or socket_error.

When compiler.os == windows

public extern(c) link(symbol: "recvfrom") receive_from:
    (socket: windows.handle, into: ptr mut u8, count: i32, flags: i32,
     sender: ptr mut u8, length: ptr mut i32) -> (got: i32)

Receive a datagram and its sender's address, recvfrom.

receive_from_overlapped

function platform/windows/sockets/socket_calls.ldn:34 ↑ index

When compiler.os == windows

public extern(c) link(symbol: "WSARecvFrom") receive_from_overlapped:
    (socket: windows.handle, buffers: ptr mut socket_buffer, count: u32,
     received: ptr mut u32, flags: ptr mut u32, sender: ptr mut u8,
     sender_length: ptr mut i32, record: usize, routine: usize)
    -> (result: i32)

Receive a datagram into the buffers, its sender's address into the sender_length bytes at sender, WSARecvFrom; both must outlive the call.

When compiler.os == windows

public extern(c) link(symbol: "WSARecv") receive_overlapped:
    (socket: windows.handle, buffers: ptr mut socket_buffer, count: u32,
     received: ptr mut u32, flags: ptr mut u32, record: usize,
     routine: usize) -> (result: i32)

Receive into the count buffers at buffers, WSARecv, with record an overlapped and no completion routine.

When compiler.os == windows

public extern(c) link(symbol: "select") select:
    (ignored: i32, reading: usize, writing: usize, failing: usize,
     limit: usize) -> (count: i32)

Wait until a socket of the set at reading can be read, one of writing written or one of failing has failed, up to the time_limit at limit, select: how many are ready, zero when the time ran out, or socket_error. Each set's address may be zero for none, and each keeps only its ready sockets.

When compiler.os == windows

public extern(c) link(symbol: "send") send:
    (socket: windows.handle, bytes: ptr u8, count: i32, flags: i32) -> (sent: i32)

Send and receive on a connected socket, send and recv: the bytes moved, zero from receive once the peer has finished sending, or socket_error.

When compiler.os == windows

public extern(c) link(symbol: "WSASend") send_overlapped:
    (socket: windows.handle, buffers: ptr mut socket_buffer, count: u32,
     sent: ptr mut u32, flags: u32, record: usize, routine: usize)
    -> (result: i32)

Send the count buffers at buffers, WSASend.

When compiler.os == windows

public extern(c) link(symbol: "sendto") send_to:
    (socket: windows.handle, bytes: ptr u8, count: i32, flags: i32, to: ptr u8,
     length: i32) -> (sent: i32)

Send a datagram to to and receive one with its sender's address, sendto and recvfrom.

When compiler.os == windows

public extern(c) link(symbol: "WSASendTo") send_to_overlapped:
    (socket: windows.handle, buffers: ptr mut socket_buffer, count: u32,
     sent: ptr mut u32, flags: u32, to: ptr u8, to_length: i32,
     record: usize, routine: usize) -> (result: i32)

Send a datagram of the buffers to the address at to, WSASendTo.

When compiler.os == windows

public extern(c) link(symbol: "setsockopt") set_option:
    (socket: windows.handle, level: i32, option: i32, value: ptr u8, length: i32)
    -> (status: i32)

Set a socket option, setsockopt: zero or socket_error.

When compiler.os == windows

public extern(c) link(symbol: "shutdown") shutdown:
    (socket: windows.handle, how: i32) -> (status: i32)

Stop receiving, sending or both, shutdown.

When compiler.os == windows

public extern(c) link(symbol: "WSAIoctl") socket_control:
    (socket: windows.handle, code: u32, given: ptr u8, given_length: u32,
     into: ptr mut usize, into_length: u32, returned: ptr mut u32,
     record: usize, routine: usize) -> (result: i32)

A control call on socket, WSAIoctl, here only to ask for an extension function's address.

When compiler.os == windows

public extern(c) link(symbol: "WSAGetLastError") socket_last_error:
    () -> (code: u32)

The calling thread's last Windows Sockets error, WSAGetLastError.

When compiler.os == windows

public extern(c) link(symbol: "getsockname") socket_name:
    (socket: windows.handle, into: ptr mut u8, length: ptr mut i32) -> (status: i32)

The address of a socket's own end and its peer's, getsockname and getpeername.

socket_overlapped_result

function platform/windows/sockets/socket_calls.ldn:49 ↑ index

When compiler.os == windows

public extern(c) link(symbol: "WSAGetOverlappedResult") socket_overlapped_result:
    (socket: windows.handle, record: ptr mut windows.overlapped, moved: ptr mut u32,
     wait: i32, flags: ptr mut u32) -> (done: i32)

How an overlapped call on socket ended, WSAGetOverlappedResult: nonzero with the bytes it moved, or zero with the Windows Sockets code for socket_last_error.

When compiler.os == windows

public started: () -> (status: u32)

Make the process's one WSAStartup call, asking for Windows Sockets 2.2, before its first socket: zero, or the reason it failed.

Example program

This complete program is one of the compiler's runtime tests. View source.

compiler/tests/fixtures/runtime/network-echo/main.ldn183 lines
--  Echo over loopback: a server and its client in one program, over TCP
--  and over UDP, on IPv4's loopback address and on IPv6's.  The server
--  reads the client's lines through a line reader and writes them back
--  through a buffered writer, the client reads them back through a line
--  reader of its own, and the report goes to standard output through a
--  buffered writer, flushed on every way out.
import core/failure
import core/io
import core/net
import core/text
import core/time
import hosted/blocking

--- What the client sends over TCP: three lines.
request: []u8 = "one\ntwo\nhello, world\n"

--- What the client sends over UDP: two datagrams.
messages: [2][]u8 = ["ping", "hello, datagram"]

--- A reply came from somewhere other than the server it was sent to.
wrong_sender: atom

--- Serve `connection`: read each line through a line reader and write it
--- back through a buffered writer, until the client has finished sending,
--- and then finish sending too.  `lines` is how many it echoed.
serve: (provider: type is net.network, host: provider, connection: io.file)
       -> (lines: usize) ! ... =
    mut incoming: [64]u8 = zeroed
    mut reader := io.lines_over(host, connection, incoming)
    mut outgoing: [64]u8 = zeroed
    mut writer := io.buffered_over(host, connection, outgoing)
    lines = 0
    loop do
        item: io.line = try io.read_line(reader)
        break when item.at_end
        try io.put(writer, item.bytes)
        try io.put(writer, "\n")
        inc lines
    end loop
    try io.flush(writer)
    try net.shutdown(host, connection, net.sending)
end serve

--- Echo `request` over TCP between a server and a client on `family`'s
--- loopback address, and put what the client read back in `echoed`, a line
--- at a time; `lines` is how many the server echoed.  The listener asks for
--- port 0, any free one, and says which it got; the client sends all of
--- its lines and finishes sending before the server accepts, which the
--- system's buffers allow in one thread.
tcp_echo: (provider: type is net.network, host: provider,
           family: net.address_family, inout echoed: text.builder)
          -> (lines: usize) ! ... =
    listener: io.file = try net.listen(host, net.loopback(family, 0))
    defer net.close(host, listener) else none
    at: net.address = try net.local_address(host, listener)
    client: io.file = try net.connect(host, at)
    defer net.close(host, client) else none
    try net.set_timeouts(host, client, time.seconds(5), time.seconds(5))
    try net.send(host, client, request)
    try net.shutdown(host, client, net.sending)
    server: io.file = try net.accept(host, listener)
    defer net.close(host, server) else none
    try net.set_timeouts(host, server, time.seconds(5), time.seconds(5))
    lines = try serve(host, server)
    mut incoming: [64]u8 = zeroed
    mut replies := io.lines_over(host, client, incoming)
    loop do
        item: io.line = try io.read_line(replies)
        break when item.at_end
        try text.append(echoed, item.bytes)
        try text.append_byte(echoed, u8('\n'))
    end loop
end tcp_echo

--- Echo `messages` over UDP between two sockets on `family`'s loopback
--- address: the server sends each datagram back to whoever sent it, and
--- the client puts each reply in `echoed`, a line each.
udp_echo: (provider: type is net.network, host: provider,
           family: net.address_family, inout echoed: text.builder)
          -> none ! ... =
    server: io.file = try net.open_datagram(host, net.loopback(family, 0))
    defer net.close(host, server) else none
    client: io.file = try net.open_datagram(host, net.loopback(family, 0))
    defer net.close(host, client) else none
    try net.set_timeouts(host, server, time.seconds(5), time.seconds(5))
    try net.set_timeouts(host, client, time.seconds(5), time.seconds(5))
    at: net.address = try net.local_address(host, server)
    mut buffer: [64]u8 = zeroed
    for message in messages do
        try net.send_to(host, client, message, at)
        got: net.datagram = try net.receive_from(host, server, buffer)
        try net.send_to(host, server, buffer[0..<got.count], got.sender)
        back: net.datagram = try net.receive_from(host, client, buffer)
        fail wrong_sender when not net.same_address(back.sender, at)
        try text.append(echoed, buffer[0..<back.count])
        try text.append_byte(echoed, u8('\n'))
    end for
end udp_echo

--- Write each line of `bytes` to `out` after a bar.
quoted: (provider: type is io.writer, inout out: io.buffered_writer(provider),
         bytes: []u8) -> none ! ... =
    mut start: usize = 0
    for at in usize(0)..<lenof bytes do
        if bytes[at] == 10 then
            try io.put(out, "| ")
            try io.put(out, bytes[start..<at + 1])
            start = at + 1
        end if
    end for
end quoted

--- Report what came back over `protocol` on `family`'s loopback address:
--- `count` of `what` the server echoed, and each of them.
report: (provider: type is io.writer, inout out: io.buffered_writer(provider),
         protocol: []u8, family: net.address_family, count: usize,
         what: []u8, echoed: []u8) -> none ! ... =
    mut room: [64]u8 = zeroed
    mut line := text.over(room)
    at: net.address = net.loopback(family, 0)
    try text.append(line, protocol)
    try text.append(line, " over ")
    try net.append_ip(line, at)
    try text.format(line, ": the server echoed {} {}\n",
                    [any(addr count), any(addr what)])
    try io.put(out, text.used(line))
    try quoted(out, echoed)
end report

--- Echo over TCP and then UDP on `family`'s loopback address, and report
--- what came back to `out`.
exchange: (host: blocking.host,
           inout out: io.buffered_writer(blocking.host),
           family: net.address_family) -> none ! ... =
    mut room: [256]u8 = zeroed
    mut echoed := text.over(room)
    lines: usize = try tcp_echo(host, family, echoed)
    try report(out, "TCP", family, lines, "lines", text.used(echoed))
    text.clear(echoed)
    try udp_echo(host, family, echoed)
    try report(out, "UDP", family, lenof messages, "datagrams",
               text.used(echoed))
end exchange

--- Say on standard error why the echo could not be run or reported.
complain: (host: blocking.host, problem: wrong_sender | failure.reason)
          -> none =
    reason: []u8 = match problem
        wrong_sender: "a datagram came from the wrong sender"
        _ (rest): failure.words(rest)
    end match
    io.write(host, io.err(host), "echo: ") else none
    io.write(host, io.err(host), reason) else none
    io.write(host, io.err(host), "\n") else none
end complain

public main: () -> (code: i32) =
    host := blocking.new()
    mut storage: [512]u8 = zeroed
    mut out := io.buffered_over(host, io.out(host), storage)
    defer io.flush(out) else none
    code = 1
    families: [2]net.address_family = [net.ipv4, net.ipv6]
    for family in families do
        exchange(host, out, family) else (problem)
            --  A system without IPv6 cannot run the second half, which
            --  says so rather than passing over it.
            if problem == net.address_unavailable then
                io.put(out, "this system has no such loopback address\n")
                    else none
                code = 2
            else
                complain(host, problem)
            end if
            return
        end
    end for
    io.flush(out) else (problem)
        complain(host, problem)
        return
    end
    code = 0
end main
in a terminalprints on standard output
$ refine compile main.ldn -o network-echo && ./network-echo
TCP over 127.0.0.1: the server echoed 3 lines
| one
| two
| hello, world
UDP over 127.0.0.1: the server echoed 2 datagrams
| ping
| hello, datagram
TCP over ::1: the server echoed 3 lines
| one
| two
| hello, world
UDP over ::1: the server echoed 2 datagrams
| ping
| hello, datagram