Landin library reference discuss source

hosted/blocking/windows_network.ldn

1--  The blocking provider's `net.network` on Windows, over Windows Sockets,
2--  as network.ldn gives it over platform/posix: a socket is a file of
3--  hosted/system's marked as one, so `io.read` and `io.write` take a
4--  connection as they take a file, and every call that waits blocks the
5--  thread.  A socket is made overlapped-capable and not inherited, so
6--  hosted/events may wait on one through its completion port.
7
8import core/io
9import core/net
10import core/time
11import hosted/system
12import platform/windows
13import platform/windows/sockets
14
15fixed if compiler.os == windows then
16    --  How many connections may wait to be accepted.
17    backlog: i32 = 128
18
19    --  Whether a code says the system does not have the address here.
20    unavailable: (code: u32) -> (yes: bool) =
21        yes = code == sockets.wsa_address_unavailable
22              or code == sockets.wsa_family_unsupported
23    end unavailable
24
25    --  Whether a code says the peer has gone.
26    gone: (code: u32) -> (yes: bool) =
27        yes = code == sockets.wsa_connection_reset
28              or code == sockets.wsa_connection_aborted
29              or code == sockets.wsa_not_connected
30              or code == sockets.wsa_shut_down
31              or code == sockets.wsa_network_reset
32              or code == sockets.wsa_timed_out
33    end gone
34
35    --  The code the failing call left.
36    last: () -> (code: u32) =
37        code = sockets.socket_last_error()
38    end last
39
40    --  Close a socket no caller is told about.
41    quietly_closed: (closing: windows.handle) -> none =
42        _ = sockets.close_socket(closing)
43    end quietly_closed
44
45    --  A new socket of `at`'s family and `kind`, or the reason there is
46    --  none: Windows Sockets started first.
47    opened_socket: (at: net.address, kind: i32)
48                   -> (socket: windows.handle, code: u32) =
49        socket = sockets.invalid_socket
50        code = sockets.started()
51        return when code <> 0
52        family: i32 = if at.family == net.ipv4 then sockets.af_inet
53                      else sockets.af_inet6 end if
54        socket = sockets.make_socket(family, kind, 0, 0, 0,
55                                     sockets.wsa_flag_overlapped
56                                     | sockets.wsa_flag_no_handle_inherit)
57        if socket == sockets.invalid_socket then code = last() end if
58    end opened_socket
59
60    --  An IPv6 socket takes IPv6 alone, as on every system.
61    only_ipv6: (socket: windows.handle) -> (code: u32) =
62        code = 0
63        on: u32 = 1
64        if sockets.set_option(socket, sockets.ipproto_ipv6, sockets.ipv6_only,
65                              ptr(usize(addr on)), 4) <> 0 then
66            code = last()
67        end if
68    end only_ipv6
69
70    --  A socket bound to `at`, a listener when `listening`: the reason it
71    --  could not be, or zero.  Windows lets a listener take an address its
72    --  earlier connections still hold without an option, and refuses one
73    --  another socket listens at.
74    bound: (at: net.address, kind: i32, listening: bool)
75           -> (socket: windows.handle, code: u32) =
76        (socket: made, code: given) := opened_socket(at, kind)
77        socket = made
78        code = given
79        return when code <> 0
80        if at.family == net.ipv6 then code = only_ipv6(socket) end if
81        if code == 0 then
82            record: sockets.socket_address =
83                system.internet_address(at) else (problem)
84                    _ = problem
85                    quietly_closed(socket)
86                    socket = sockets.invalid_socket
87                    code = sockets.wsa_address_unavailable
88                    return
89                end
90            if sockets.bind(socket, addr record.bytes[0], record.length) <> 0 then
91                code = last()
92            elsif listening and sockets.listen(socket, backlog) <> 0 then
93                code = last()
94            end if
95        end if
96        if code <> 0 then
97            quietly_closed(socket)
98            socket = sockets.invalid_socket
99        end if
100    end bound
101
102    bind_failure: (self: host, code: u32)
103                  -> none ! net.address_in_use | net.address_unavailable
104                          | io.no_access | io.io_failed =
105        record(self, code)
106        fail net.address_in_use when code == sockets.wsa_address_in_use
107        fail net.address_unavailable when unavailable(code)
108        fail io.no_access when code == sockets.wsa_access
109        fail io.io_failed
110    end bind_failure
111
112    blocking_listen: (self: host, at: net.address) -> (listener: io.file)
113                     ! net.address_in_use | net.address_unavailable
114                     | io.no_access | io.io_failed =
115        cleared(self)
116        (socket, code) := bound(at, sockets.sock_stream, true)
117        if code <> 0 then
118            try bind_failure(self, code)
119        end if
120        listener = system.socket_of(socket)
121    end blocking_listen
122
123    blocking_open_datagram: (self: host, at: net.address) -> (socket: io.file)
124                            ! net.address_in_use | net.address_unavailable
125                            | io.no_access | io.io_failed =
126        cleared(self)
127        (socket: made, code) := bound(at, sockets.sock_dgram, false)
128        if code <> 0 then
129            try bind_failure(self, code)
130        end if
131        socket = system.socket_of(made)
132    end blocking_open_datagram
133
134    connect_failure: (self: host, code: u32)
135                     -> none ! net.refused | net.unreachable
136                             | net.address_unavailable | net.timed_out
137                             | io.io_failed =
138        record(self, code)
139        fail net.refused when code == sockets.wsa_connection_refused
140        fail net.unreachable when code == sockets.wsa_network_unreachable
141          or code == sockets.wsa_host_unreachable
142        fail net.address_unavailable when unavailable(code)
143        fail net.timed_out when code == sockets.wsa_timed_out
144        fail io.io_failed
145    end connect_failure
146
147    --  Set `socket` to block, or with `waiting` false not to.
148    blocking_mode: (socket: windows.handle, waiting: bool) -> (code: u32) =
149        code = 0
150        mut value: u32 = if waiting then 0 else 1 end if
151        if sockets.control(socket, sockets.fionbio, addr value) <> 0 then
152            code = last()
153        end if
154    end blocking_mode
155
156    --  The outcome a connection begun without waiting ended with.
157    pending_error: (socket: windows.handle) -> (code: u32) =
158        mut value: u32 = 0
159        mut length: i32 = 4
160        code = 0
161        if sockets.get_option(socket, sockets.sol_socket, sockets.so_error,
162                              ptr(usize(addr value)), addr length) <> 0 then
163            code = last()
164            return
165        end if
166        code = value
167    end pending_error
168
169    --  Connect `socket` to `to`, waiting at most until `deadline` when it is
170    --  not zero: the reason it was not connected, or zero.  A connection
171    --  with a limit is begun without waiting, watched with `select`, and
172    --  the socket made to block again once it is made (D580).
173    connected: (socket: windows.handle, to: net.address, deadline: u64)
174               -> (code: u32) =
175        record: sockets.socket_address = system.internet_address(to)
176            else (problem)
177            _ = problem
178            code = sockets.wsa_address_unavailable
179            return
180        end
181        if deadline == 0 then
182            code = 0
183            if sockets.connect(socket, addr record.bytes[0], record.length) <> 0 then
184                code = last()
185            end if
186            return
187        end if
188        code = blocking_mode(socket, false)
189        return when code <> 0
190        if sockets.connect(socket, addr record.bytes[0], record.length) <> 0 then
191            code = last()
192            return when code <> sockets.wsa_would_block
193            loop do
194                now: u64 = reading()
195                if now >= deadline then
196                    code = sockets.wsa_timed_out
197                    return
198                end if
199                left: u64 = deadline - now
200                mut micro: u64 = (left + 999) / 1000
201                if micro > 2000000000 then micro = 2000000000 end if
202                limit: sockets.time_limit =
203                    (seconds: i32(micro / 1000000),
204                     microseconds: i32(micro % 1000000))
205                mut writing: sockets.socket_set = (count: 1, sockets: [socket])
206                mut failing: sockets.socket_set = (count: 1, sockets: [socket])
207                found: i32 = sockets.select(0, 0, usize(addr writing),
208                                            usize(addr failing),
209                                            usize(addr limit))
210                if found == sockets.socket_error then
211                    code = last()
212                    return
213                end if
214                break when found > 0
215            end loop
216            code = pending_error(socket)
217            return when code <> 0
218        end if
219        code = blocking_mode(socket, true)
220    end connected
221
222    connect_by: (self: host, to: net.address, deadline: u64)
223                -> (opened: io.file)
224                ! net.refused | net.unreachable | net.address_unavailable
225                | net.timed_out | io.io_failed =
226        cleared(self)
227        (socket, code: made_code) := opened_socket(to, sockets.sock_stream)
228        if made_code <> 0 then
229            try connect_failure(self, made_code)
230        end if
231        code: u32 = connected(socket, to, deadline)
232        if code <> 0 then
233            quietly_closed(socket)
234            try connect_failure(self, code)
235        end if
236        opened = system.socket_of(socket)
237    end connect_by
238
239    blocking_connect: (self: host, to: net.address) -> (opened: io.file)
240                      ! net.refused | net.unreachable | net.address_unavailable
241                      | net.timed_out | io.io_failed =
242        opened = try connect_by(self, to, 0)
243    end blocking_connect
244
245    blocking_connect_within: (self: host, to: net.address,
246                              limit: time.duration)
247                             -> (opened: io.file)
248                             ! net.refused | net.unreachable
249                             | net.address_unavailable | net.timed_out
250                             | io.io_failed =
251        if u64(limit) == 0 then
252            opened = try connect_by(self, to, 0)
253            return
254        end if
255        opened = try connect_by(self, to, deadline_after(limit))
256    end blocking_connect_within
257
258    blocking_accept: (self: host, listener: io.file) -> (accepted: io.file)
259                     ! net.timed_out | io.io_failed =
260        cleared(self)
261        loop do
262            try ready_within(self, system.handle_of(listener), false)
263            made: windows.handle = sockets.accept(system.handle_of(listener),
264                                                  0, 0)
265            if made == sockets.invalid_socket then
266                code: u32 = last()
267                --  A connection its peer reset before it was taken is no
268                --  connection.
269                continue when code == sockets.wsa_connection_reset
270                  or code == sockets.wsa_interrupted
271                record(self, code)
272                fail net.timed_out when code == sockets.wsa_timed_out
273                  or code == sockets.wsa_would_block
274                fail io.io_failed
275            end if
276            _ = windows.set_handle_information(made,
277                                               windows.handle_flag_inherit, 0)
278            accepted = system.socket_of(made)
279            return
280        end loop
281    end blocking_accept
282
283    --  The limit `set_timeouts` gave `socket` for receiving, or with
284    --  `sending` for sending, in milliseconds: zero for none.
285    limit_of: (socket: windows.handle, sending: bool) -> (milliseconds: u32) =
286        mut value: u32 = 0
287        mut length: i32 = 4
288        option: i32 = if sending then sockets.so_send_timeout
289                      else sockets.so_receive_timeout end if
290        milliseconds = 0
291        if sockets.get_option(socket, sockets.sol_socket, option,
292                              ptr(usize(addr value)), addr length) == 0 then
293            milliseconds = value
294        end if
295    end limit_of
296
297    --  Wait until `socket` can be read, or with `sending` written, within
298    --  the limit `set_timeouts` gave it, measured on the monotonic clock
299    --  and never early, and fail `timed_out` with WSAETIMEDOUT once it has
300    --  passed.  Windows' own limit does not cover `accept`, and a receive
301    --  it ends leaves the socket in no state a later call can rely on, so
302    --  the provider waits the limit out itself and calls only once the
303    --  socket is ready, as platform/posix does for an accept on Darwin.
304    ready_within: (self: host, socket: windows.handle, sending: bool)
305                  -> none ! net.timed_out | io.io_failed =
306        limit: u32 = limit_of(socket, sending)
307        return when limit == 0
308        deadline: u64 = deadline_after(time.milliseconds(u64(limit)))
309        loop do
310            now: u64 = reading()
311            if now >= deadline then
312                record(self, sockets.wsa_timed_out)
313                fail net.timed_out
314            end if
315            mut micro: u64 = (deadline - now + 999) / 1000
316            if micro > 2000000000 then micro = 2000000000 end if
317            wait: sockets.time_limit = (seconds: i32(micro / 1000000),
318                                        microseconds: i32(micro % 1000000))
319            mut watched: sockets.socket_set = (count: 1, sockets: [socket])
320            mut failing: sockets.socket_set = (count: 1, sockets: [socket])
321            reading: usize = if sending then 0 else usize(addr watched) end if
322            writing: usize = if sending then usize(addr watched) else 0 end if
323            found: i32 = sockets.select(0, reading, writing, usize(addr failing),
324                                        usize(addr wait))
325            if found == sockets.socket_error then
326                record(self, last())
327                fail io.io_failed
328            end if
329            return when found > 0
330        end loop
331    end ready_within
332
333    --  The most one call sends or receives, which an int counts.
334    most_bytes: usize = 0x40000000
335
336    blocking_send: (self: host, connection: io.file, bytes: []u8)
337                   -> none ! net.disconnected | net.timed_out | io.io_failed =
338        cleared(self)
339        mut sent: usize = 0
340        while sent < lenof bytes do
341            mut want: usize = lenof bytes - sent
342            if want > most_bytes then want = most_bytes end if
343            ready_within(self, system.handle_of(connection), true) else (problem)
344                fail net.timed_out when problem == net.timed_out
345                fail io.io_failed
346            end
347            accepted: i32 = sockets.send(system.handle_of(connection),
348                                         addr bytes[sent], i32(want), 0)
349            if accepted < 0 then
350                code: u32 = last()
351                record(self, code)
352                fail net.timed_out when code == sockets.wsa_timed_out
353                fail net.disconnected when gone(code)
354                fail io.io_failed
355            end if
356            fail io.io_failed when accepted == 0 or usize(accepted) > want
357            sent += usize(accepted)
358        end while
359    end blocking_send
360
361    blocking_receive: (self: host, connection: io.file, into: []mut u8)
362                      -> (count: usize)
363                      ! net.disconnected | net.timed_out | io.io_failed =
364        cleared(self)
365        count = 0
366        return when lenof into == 0
367        mut want: usize = lenof into
368        if want > most_bytes then want = most_bytes end if
369        try ready_within(self, system.handle_of(connection), false)
370        got: i32 = sockets.receive(system.handle_of(connection), addr into[0],
371                                   i32(want), 0)
372        if got < 0 then
373            code: u32 = last()
374            record(self, code)
375            fail net.timed_out when code == sockets.wsa_timed_out
376            fail net.disconnected when gone(code)
377            fail io.io_failed
378        end if
379        count = usize(got)
380    end blocking_receive
381
382    blocking_send_to: (self: host, socket: io.file, bytes: []u8,
383                       to: net.address) -> none
384                      ! net.unreachable | net.timed_out | io.io_failed =
385        cleared(self)
386        target: sockets.socket_address = system.internet_address(to)
387            else (problem)
388            _ = problem
389            record(self, sockets.wsa_address_unavailable)
390            fail net.unreachable
391        end
392        fail io.io_failed when lenof bytes > most_bytes
393        mut spare: [1]u8 = zeroed
394        first: ptr u8 = if lenof bytes > 0 then addr bytes[0]
395                        else addr spare[0] end if
396        accepted: i32 = sockets.send_to(system.handle_of(socket), first,
397                                        i32(lenof bytes), 0,
398                                        addr target.bytes[0], target.length)
399        if accepted < 0 then
400            code: u32 = last()
401            record(self, code)
402            fail net.unreachable when code == sockets.wsa_network_unreachable
403              or code == sockets.wsa_host_unreachable
404            fail net.timed_out when code == sockets.wsa_timed_out
405            fail io.io_failed
406        end if
407        fail io.io_failed when usize(accepted) <> lenof bytes
408    end blocking_send_to
409
410    blocking_receive_from: (self: host, socket: io.file, into: []mut u8)
411                           -> (taken: net.datagram)
412                           ! net.timed_out | io.io_failed =
413        cleared(self)
414        mut sender: sockets.socket_address = (bytes: zeroed, length: 28)
415        mut spare: [1]u8 = zeroed
416        mut want: usize = lenof into
417        if want > most_bytes then want = most_bytes end if
418        first: ptr mut u8 = if want > 0 then addr into[0] else addr spare[0] end if
419        try ready_within(self, system.handle_of(socket), false)
420        got: i32 = sockets.receive_from(system.handle_of(socket), first,
421                                        i32(want), 0, addr sender.bytes[0],
422                                        addr sender.length)
423        mut count: usize = 0
424        if got < 0 then
425            code: u32 = last()
426            --  A datagram longer than `into` is cut to it.
427            if code == sockets.wsa_message_size then
428                count = want
429            else
430                record(self, code)
431                fail net.timed_out when code == sockets.wsa_timed_out
432                fail io.io_failed
433            end if
434        else
435            count = usize(got)
436        end if
437        from_address: net.address = system.address_of(sender) else (problem)
438            _ = problem
439            record(self, sockets.wsa_family_unsupported)
440            fail io.io_failed
441        end
442        taken = (count: count, sender: from_address)
443    end blocking_receive_from
444
445    blocking_shutdown: (self: host, connection: io.file,
446                        stopping: net.direction) -> none ! io.io_failed =
447        cleared(self)
448        how: i32 = match stopping
449            net.receiving: sockets.sd_receive
450            net.sending: sockets.sd_send
451            net.both_directions: sockets.sd_both
452        end match
453        if sockets.shutdown(system.handle_of(connection), how) <> 0 then
454            record(self, last())
455            fail io.io_failed
456        end if
457    end blocking_shutdown
458
459    --  The internet address of a socket's own end, or with `peer` of the
460    --  other end.
461    named: (self: host, socket: io.file, peer: bool) -> (at: net.address)
462           ! io.io_failed =
463        mut found: sockets.socket_address = (bytes: zeroed, length: 28)
464        status: i32 =
465            if peer then sockets.peer_name(system.handle_of(socket),
466                                           addr found.bytes[0], addr found.length)
467            else sockets.socket_name(system.handle_of(socket),
468                                     addr found.bytes[0], addr found.length)
469            end if
470        if status <> 0 then
471            record(self, last())
472            fail io.io_failed
473        end if
474        at = system.address_of(found) else (problem)
475            _ = problem
476            record(self, sockets.wsa_family_unsupported)
477            fail io.io_failed
478        end
479    end named
480
481    blocking_local_address: (self: host, socket: io.file) -> (at: net.address)
482                            ! io.io_failed =
483        cleared(self)
484        at = try named(self, socket, false)
485    end blocking_local_address
486
487    blocking_peer_address: (self: host, connection: io.file)
488                           -> (at: net.address) ! io.io_failed =
489        cleared(self)
490        at = try named(self, connection, true)
491    end blocking_peer_address
492
493    --  A span as Windows Sockets' milliseconds, rounded up so that a limit
494    --  is never shorter than asked, zero for none.
495    milliseconds_of: (span: time.duration) -> (count: u32) =
496        mut whole: u64 = (u64(span) + 999999) / 1000000
497        if whole > 0x7FFFFFFF then whole = 0x7FFFFFFF end if
498        count = u32(whole)
499    end milliseconds_of
500
501    blocking_set_timeouts: (self: host, socket: io.file,
502                            receive_limit: time.duration,
503                            send_limit: time.duration)
504                           -> none ! io.io_failed =
505        cleared(self)
506        receiving: u32 = milliseconds_of(receive_limit)
507        sending: u32 = milliseconds_of(send_limit)
508        made: windows.handle = system.handle_of(socket)
509        if sockets.set_option(made, sockets.sol_socket,
510                              sockets.so_receive_timeout,
511                              ptr(usize(addr receiving)), 4) <> 0
512          or sockets.set_option(made, sockets.sol_socket,
513                                sockets.so_send_timeout,
514                                ptr(usize(addr sending)), 4) <> 0 then
515            record(self, last())
516            fail io.io_failed
517        end if
518    end blocking_set_timeouts
519
520    blocking_set_no_delay: (self: host, connection: io.file, on: bool)
521                           -> none ! io.io_failed =
522        cleared(self)
523        value: u32 = if on then 1 else 0 end if
524        if sockets.set_option(system.handle_of(connection), sockets.ipproto_tcp,
525                              sockets.tcp_no_delay, ptr(usize(addr value)),
526                              4) <> 0 then
527            record(self, last())
528            fail io.io_failed
529        end if
530    end blocking_set_no_delay
531
532    blocking_close_socket: (self: host, sink socket: io.file)
533                           -> none ! io.io_failed =
534        cleared(self)
535        if sockets.close_socket(system.handle_of(socket)) <> 0 then
536            record(self, last())
537            fail io.io_failed
538        end if
539    end blocking_close_socket
540
541    host is net.network
542        (connect: blocking_connect, connect_within: blocking_connect_within,
543         listen: blocking_listen,
544         accept: blocking_accept, open_datagram: blocking_open_datagram,
545         send: blocking_send, receive: blocking_receive,
546         send_to: blocking_send_to,
547         receive_from: blocking_receive_from, shutdown: blocking_shutdown,
548         local_address: blocking_local_address,
549         peer_address: blocking_peer_address,
550         set_timeouts: blocking_set_timeouts,
551         set_no_delay: blocking_set_no_delay,
552         close: blocking_close_socket)
553end if