-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathnet.zig
More file actions
1411 lines (1278 loc) · 51.3 KB
/
net.zig
File metadata and controls
1411 lines (1278 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const builtin = @import("builtin");
const native_os = builtin.os.tag;
const std = @import("../std.zig");
const Io = std.Io;
const assert = std.debug.assert;
pub const HostName = @import("net/HostName.zig");
/// Source of truth: Internet Assigned Numbers Authority (IANA)
pub const Protocol = enum(u32) {
hopopts = 0,
icmp = 1,
igmp = 2,
ipip = 4,
tcp = 6,
egp = 8,
pup = 12,
udp = 17,
idp = 22,
tp = 29,
dccp = 33,
ipv6 = 41,
routing = 43,
fragment = 44,
rsvp = 46,
gre = 47,
esp = 50,
ah = 51,
icmpv6 = 58,
none = 59,
dstopts = 60,
mtp = 92,
beetph = 94,
encap = 98,
pim = 103,
comp = 108,
sctp = 132,
mh = 135,
udplite = 136,
mpls = 137,
ethernet = 143,
raw = 255,
mptcp = 262,
};
/// Windows 10 added support for unix sockets in build 17063, redstone 4 is the
/// first release to support them.
pub const has_unix_sockets = switch (native_os) {
.windows => builtin.os.version_range.windows.isAtLeast(.win10_rs4) orelse false,
.wasi => false,
else => true,
};
pub const default_kernel_backlog = 128;
pub const IpAddress = union(enum) {
ip4: Ip4Address,
ip6: Ip6Address,
pub const Family = @typeInfo(IpAddress).@"union".tag_type.?;
pub const ParseLiteralError = error{ InvalidAddress, InvalidPort };
/// Parse an IP address which may include a port.
///
/// For IPv4, this is written `address:port`.
///
/// For IPv6, RFC 3986 defines this as an "IP literal", and the port is
/// differentiated from the address by surrounding the address part in
/// brackets "[addr]:port". Even if the port is not given, the brackets are
/// mandatory.
pub fn parseLiteral(text: []const u8) ParseLiteralError!IpAddress {
if (text.len == 0) return error.InvalidAddress;
if (text[0] == '[') {
const addr_end = std.mem.findScalar(u8, text, ']') orelse
return error.InvalidAddress;
const addr_text = text[1..addr_end];
const port: u16 = p: {
if (addr_end == text.len - 1) break :p 0;
if (text[addr_end + 1] != ':') return error.InvalidAddress;
break :p std.fmt.parseInt(u16, text[addr_end + 2 ..], 10) catch return error.InvalidPort;
};
return parseIp6(addr_text, port) catch error.InvalidAddress;
}
if (std.mem.findScalar(u8, text, ':')) |i| {
const addr = Ip4Address.parse(text[0..i], 0) catch return error.InvalidAddress;
return .{ .ip4 = .{
.bytes = addr.bytes,
.port = std.fmt.parseInt(u16, text[i + 1 ..], 10) catch return error.InvalidPort,
} };
}
return parseIp4(text, 0) catch error.InvalidAddress;
}
/// Parse the given IP address string into an `IpAddress` value.
///
/// This is a pure function but it cannot handle IPv6 addresses that have
/// scope ids ("%foo" at the end). To also handle those, `resolve` must be
/// called instead.
pub fn parse(text: []const u8, port: u16) !IpAddress {
if (parseIp4(text, port)) |ip4| return ip4 else |err| switch (err) {
error.Overflow,
error.InvalidEnd,
error.InvalidCharacter,
error.Incomplete,
error.NonCanonical,
=> {},
}
return parseIp6(text, port);
}
pub fn parseIp4(text: []const u8, port: u16) Ip4Address.ParseError!IpAddress {
return .{ .ip4 = try Ip4Address.parse(text, port) };
}
/// This is a pure function but it cannot handle IPv6 addresses that have
/// scope ids ("%foo" at the end). To also handle those, `resolveIp6` must be
/// called instead.
pub fn parseIp6(text: []const u8, port: u16) Ip6Address.ParseError!IpAddress {
return .{ .ip6 = try Ip6Address.parse(text, port) };
}
/// This function requires an `Io` parameter because it must query the operating
/// system to convert interface name to index. For example, in
/// "fe80::e0e:76ff:fed4:cf22%eno1", "eno1" must be resolved to an index by
/// creating a socket and then using an `ioctl` syscall.
///
/// For a pure function that cannot handle scopes, see `parse`.
pub fn resolve(io: Io, text: []const u8, port: u16) !IpAddress {
if (parseIp4(text, port)) |ip4| return ip4 else |err| switch (err) {
error.Overflow,
error.InvalidEnd,
error.InvalidCharacter,
error.Incomplete,
error.NonCanonical,
=> {},
}
return resolveIp6(io, text, port);
}
pub fn resolveIp6(io: Io, text: []const u8, port: u16) Ip6Address.ResolveError!IpAddress {
return .{ .ip6 = try Ip6Address.resolve(io, text, port) };
}
/// Returns the port in native endian.
pub fn getPort(a: IpAddress) u16 {
return switch (a) {
inline .ip4, .ip6 => |x| x.port,
};
}
/// `port` is native-endian.
pub fn setPort(a: *IpAddress, port: u16) void {
switch (a) {
inline .ip4, .ip6 => |*x| x.port = port,
}
}
/// Includes the optional scope ("%foo" at the end) in IPv6 addresses.
///
/// See `format` for an alternative that omits scopes and does
/// not require an `Io` parameter.
pub fn formatResolved(a: IpAddress, io: Io, w: *Io.Writer) Ip6Address.FormatError!void {
switch (a) {
.ip4 => |x| return x.format(w),
.ip6 => |x| return x.formatResolved(io, w),
}
}
/// See `formatResolved` for an alternative that additionally prints the optional
/// scope at the end of IPv6 addresses and requires an `Io` parameter.
pub fn format(a: IpAddress, w: *Io.Writer) Io.Writer.Error!void {
switch (a) {
inline .ip4, .ip6 => |x| return x.format(w),
}
}
pub fn eql(a: *const IpAddress, b: *const IpAddress) bool {
return switch (a.*) {
.ip4 => |a_ip4| switch (b.*) {
.ip4 => |b_ip4| a_ip4.eql(b_ip4),
else => false,
},
.ip6 => |a_ip6| switch (b.*) {
.ip6 => |b_ip6| a_ip6.eql(b_ip6),
else => false,
},
};
}
pub const ListenError = error{
/// The address is already taken. Can occur when bound port is 0 but
/// all ephemeral ports are already in use.
AddressInUse,
/// A nonexistent interface was requested or the requested address was not local.
AddressUnavailable,
/// The local network interface used to reach the destination is offline.
NetworkDown,
/// Insufficient memory or other resource internal to the operating system.
SystemResources,
/// Per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// System-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
/// The requested address family (IPv4 or IPv6) is not supported by the operating system.
AddressFamilyUnsupported,
ProtocolUnsupportedBySystem,
ProtocolUnsupportedByAddressFamily,
SocketModeUnsupported,
/// One of the `ListenOptions` is not supported by the Io
/// implementation.
OptionUnsupported,
} || Io.UnexpectedError || Io.Cancelable;
pub const ListenOptions = struct {
/// How many connections the kernel will accept on the application's behalf.
/// If more than this many connections pool in the kernel, clients will start
/// seeing "Connection refused".
kernel_backlog: u31 = default_kernel_backlog,
/// Sets SO_REUSEADDR and SO_REUSEPORT on POSIX.
/// Sets SO_REUSEADDR on Windows, which is roughly equivalent.
reuse_address: bool = false,
/// Only connection-oriented modes may be used here, which includes:
/// * `Socket.Mode.stream`
/// * `Socket.Mode.seqpacket`
mode: Socket.Mode = .stream,
/// Only connection-oriented protocols may be used here, which includes:
/// * `Protocol.tcp`
/// * `Protocol.tp`
/// * `Protocol.dccp`
/// * `Protocol.sctp`
protocol: Protocol = .tcp,
};
/// Waits for a TCP connection. When using this API, `bind` does not need
/// to be called. The returned `Server` has an open `stream`.
pub fn listen(address: IpAddress, io: Io, options: ListenOptions) ListenError!Server {
return io.vtable.netListenIp(io.userdata, address, options);
}
pub const BindError = error{
/// The address is already taken. Can occur when bound port is 0 but
/// all ephemeral ports are already in use.
AddressInUse,
/// A nonexistent interface was requested or the requested address was not local.
AddressUnavailable,
/// The address is not valid for the address family of socket.
AddressFamilyUnsupported,
/// Insufficient memory or other resource internal to the operating system.
SystemResources,
/// The local network interface used to reach the destination is offline.
NetworkDown,
ProtocolUnsupportedBySystem,
ProtocolUnsupportedByAddressFamily,
/// Per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// System-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
SocketModeUnsupported,
/// One of the `BindOptions` is not supported by the Io
/// implementation.
OptionUnsupported,
} || Io.UnexpectedError || Io.Cancelable;
pub const BindOptions = struct {
/// The socket is restricted to sending and receiving IPv6 packets only.
/// In this case, an IPv4 and an IPv6 application can bind to a single port
/// at the same time.
ip6_only: bool = false,
mode: Socket.Mode,
protocol: ?Protocol = null,
};
/// Associates an address with a `Socket` which can be used to receive UDP
/// packets and other kinds of non-streaming messages. See `listen` for a
/// streaming alternative.
///
/// One bound `Socket` can be used to receive messages from multiple
/// different addresses.
pub fn bind(address: *const IpAddress, io: Io, options: BindOptions) BindError!Socket {
return io.vtable.netBindIp(io.userdata, address, options);
}
pub const ConnectError = error{
AddressUnavailable,
AddressFamilyUnsupported,
/// Insufficient memory or other resource internal to the operating system.
SystemResources,
ConnectionPending,
ConnectionRefused,
ConnectionResetByPeer,
HostUnreachable,
NetworkUnreachable,
Timeout,
/// One of the `ConnectOptions` is not supported by the Io
/// implementation.
OptionUnsupported,
/// Per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// System-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
ProtocolUnsupportedBySystem,
ProtocolUnsupportedByAddressFamily,
SocketModeUnsupported,
/// The user tried to connect to a broadcast address without having the socket broadcast flag enabled or
/// the connection request failed because of a local firewall rule.
AccessDenied,
/// Non-blocking was requested and the operation cannot return immediately.
WouldBlock,
NetworkDown,
} || Io.Timeout.Error || Io.UnexpectedError || Io.Cancelable;
pub const ConnectOptions = struct {
mode: Socket.Mode,
protocol: ?Protocol = null,
timeout: Io.Timeout = .none,
};
/// Initiates a connection-oriented network stream.
pub fn connect(address: IpAddress, io: Io, options: ConnectOptions) ConnectError!Stream {
return io.vtable.netConnectIp(io.userdata, &address, options);
}
};
/// An IPv4 address in binary memory layout.
pub const Ip4Address = struct {
bytes: [4]u8,
port: u16,
pub fn loopback(port: u16) Ip4Address {
return .{
.bytes = .{ 127, 0, 0, 1 },
.port = port,
};
}
pub fn unspecified(port: u16) Ip4Address {
return .{
.bytes = .{ 0, 0, 0, 0 },
.port = port,
};
}
pub const ParseError = error{
Overflow,
InvalidEnd,
InvalidCharacter,
Incomplete,
NonCanonical,
};
pub fn parse(buffer: []const u8, port: u16) ParseError!Ip4Address {
var bytes: [4]u8 = @splat(0);
var index: u8 = 0;
var saw_any_digits = false;
var has_zero_prefix = false;
for (buffer) |c| switch (c) {
'.' => {
if (!saw_any_digits) return error.InvalidCharacter;
if (index == 3) return error.InvalidEnd;
index += 1;
saw_any_digits = false;
has_zero_prefix = false;
},
'0'...'9' => {
if (c == '0' and !saw_any_digits) {
has_zero_prefix = true;
} else if (has_zero_prefix) {
return error.NonCanonical;
}
saw_any_digits = true;
bytes[index] = try std.math.mul(u8, bytes[index], 10);
bytes[index] = try std.math.add(u8, bytes[index], c - '0');
},
else => return error.InvalidCharacter,
};
if (index == 3 and saw_any_digits) return .{
.bytes = bytes,
.port = port,
};
return error.Incomplete;
}
pub fn format(a: Ip4Address, w: *Io.Writer) Io.Writer.Error!void {
const bytes = &a.bytes;
try w.print("{d}.{d}.{d}.{d}:{d}", .{ bytes[0], bytes[1], bytes[2], bytes[3], a.port });
}
pub fn eql(a: Ip4Address, b: Ip4Address) bool {
const a_int: u32 = @bitCast(a.bytes);
const b_int: u32 = @bitCast(b.bytes);
return a.port == b.port and a_int == b_int;
}
};
/// An IPv6 address in binary memory layout.
pub const Ip6Address = struct {
/// Native endian
port: u16,
/// Big endian
bytes: [16]u8,
flow: u32 = 0,
interface: Interface = .none,
pub const Policy = struct {
addr: [16]u8,
len: u8,
mask: u8,
prec: u8,
label: u8,
};
pub fn loopback(port: u16) Ip6Address {
return .{
.bytes = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
.port = port,
};
}
pub fn unspecified(port: u16) Ip6Address {
return .{
.bytes = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
.port = port,
};
}
/// Constructs an IPv4-mapped IPv6 address.
pub fn fromIp4(ip4: Ip4Address) Ip6Address {
const b = &ip4.bytes;
return .{
.bytes = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, b[0], b[1], b[2], b[3] },
.port = ip4.port,
};
}
/// Given an `IpAddress`, converts it to an `Ip6Address` directly, or via
/// constructing an IPv4-mapped IPv6 address.
pub fn fromAny(addr: IpAddress) Ip6Address {
return switch (addr) {
.ip4 => |ip4| fromIp4(ip4),
.ip6 => |ip6| ip6,
};
}
/// An IPv6 address but with `Interface` as a name rather than index.
pub const Unresolved = struct {
/// Big endian
bytes: [16]u8,
/// Has not been checked to be a valid native interface name.
/// Externally managed memory.
interface_name: ?[]const u8,
pub const Parsed = union(enum) {
success: Unresolved,
invalid_byte: usize,
incomplete,
junk_after_end: usize,
interface_name_oversized: usize,
invalid_ip4_mapping: usize,
overflow: usize,
};
pub fn parse(text_in: []const u8) Parsed {
var text: []const u8 = text_in; // so we can alias v4_amended if needed
if (text.len < 2) return .incomplete;
// Pre-processing for trailing :IPv4 - If there is no "%iface", and
// the part after the last ':' has a '.', parse it as ipv4 and
// convert to IPv6 ASCII text in v4_amended as the new "text"
var v4_amended: [(8 * 4) + 7]u8 = undefined;
if (std.mem.findScalar(u8, text, '%') == null) {
const first_parts, const last_part = std.mem.cutScalarLast(u8, text, ':') orelse
return .incomplete;
if (std.mem.findScalar(u8, last_part, '.')) |_| {
if (first_parts.len > (6 * 4) + 5) // hhhh:hhhh:hhhh:hhhh:hhhh:hhhh
return .{ .invalid_ip4_mapping = first_parts.len };
const parsed = Ip4Address.parse(last_part, 0) catch
return .{ .invalid_ip4_mapping = first_parts.len + 1 };
@memcpy(v4_amended[0..first_parts.len], first_parts);
const v4_part = v4_amended[first_parts.len..][0..10];
v4_part[0] = ':';
@memcpy(v4_part[1..3], &std.fmt.hex(parsed.bytes[0]));
@memcpy(v4_part[3..5], &std.fmt.hex(parsed.bytes[1]));
v4_part[5] = ':';
@memcpy(v4_part[6..8], &std.fmt.hex(parsed.bytes[2]));
@memcpy(v4_part[8..10], &std.fmt.hex(parsed.bytes[3]));
text = v4_amended[0 .. first_parts.len + 10];
}
}
// Has to be u16 elements to handle 3-digit hex numbers from compression.
var parts: [8]u16 = @splat(0);
var parts_i: u8 = 0;
var text_i: u8 = 0;
var digit_i: u8 = 0;
var compress_start: ?u8 = null;
var interface_name_text: ?[]const u8 = null;
const State = union(enum) { digit, end };
state: switch (State.digit) {
.digit => c: switch (text[text_i]) {
'a'...'f' => |c| {
const digit = c - 'a' + 10;
parts[parts_i] = (std.math.mul(u16, parts[parts_i], 16) catch return .{
.overflow = text_i,
}) + digit;
if (digit_i == 4) return .{ .invalid_byte = text_i };
digit_i += 1;
text_i += 1;
if (text.len - text_i == 0) {
parts_i += 1;
continue :state .end;
}
continue :c text[text_i];
},
'A'...'F' => |c| continue :c c - 'A' + 'a',
'0'...'9' => |c| {
const digit = c - '0';
parts[parts_i] = (std.math.mul(u16, parts[parts_i], 16) catch return .{
.overflow = text_i,
}) + digit;
if (digit_i == 4) return .{ .invalid_byte = text_i };
digit_i += 1;
text_i += 1;
if (text.len - text_i == 0) {
parts_i += 1;
continue :state .end;
}
continue :c text[text_i];
},
':' => {
if (digit_i == 0) {
if (compress_start != null) return .{ .invalid_byte = text_i };
if (text_i == 0) {
text_i += 1;
if (text[text_i] != ':') return .{ .invalid_byte = text_i };
assert(parts_i == 0);
}
compress_start = parts_i;
text_i += 1;
if (text.len - text_i == 0) continue :state .end;
continue :c text[text_i];
} else {
parts_i += 1;
if (parts.len - parts_i == 0) continue :state .end;
digit_i = 0;
text_i += 1;
if (text.len - text_i == 0) return .incomplete;
continue :c text[text_i];
}
},
'%' => {
if (digit_i == 0) return .{ .invalid_byte = text_i };
parts_i += 1;
text_i += 1;
const name = text[text_i..];
if (name.len == 0) return .incomplete;
interface_name_text = name;
text_i = @intCast(text.len);
continue :state .end;
},
else => return .{ .invalid_byte = text_i },
},
.end => {
if (text.len - text_i != 0) return .{ .junk_after_end = text_i };
const remaining = parts.len - parts_i;
if (compress_start) |s| {
const src = parts[s..parts_i];
@memmove(parts[parts.len - src.len ..], src);
@memset(parts[s..][0..remaining], 0);
} else {
if (remaining != 0) return .incomplete;
}
// Workaround that can be removed when this proposal is
// implemented https://github.com/ziglang/zig/issues/19755
if ((comptime @import("builtin").cpu.arch.endian()) != .big) {
for (&parts) |*part| part.* = @byteSwap(part.*);
}
return .{ .success = .{
.bytes = @bitCast(parts),
.interface_name = interface_name_text,
} };
},
}
}
pub const FromAddressError = Interface.NameError;
pub fn fromAddress(a: *const Ip6Address, io: Io) FromAddressError!Unresolved {
if (a.interface.isNone()) return .{
.bytes = a.bytes,
.interface_name = null,
};
return .{
.bytes = a.bytes,
.interface_name = try a.interface.name(io),
};
}
pub fn format(u: *const Unresolved, w: *Io.Writer) Io.Writer.Error!void {
const bytes = &u.bytes;
if (std.mem.eql(u8, bytes[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff }))
return w.print("::ffff:{d}.{d}.{d}.{d}", .{ bytes[12], bytes[13], bytes[14], bytes[15] });
if (std.mem.eql(u8, bytes[0..12], &[_]u8{ 0, 0x64, 0xff, 0x9b, 0, 0, 0, 0, 0, 0, 0, 0 }))
return w.print("64:ff9b::{d}.{d}.{d}.{d}", .{ bytes[12], bytes[13], bytes[14], bytes[15] });
const parts: [8]u16 = .{
std.mem.readInt(u16, bytes[0..2], .big),
std.mem.readInt(u16, bytes[2..4], .big),
std.mem.readInt(u16, bytes[4..6], .big),
std.mem.readInt(u16, bytes[6..8], .big),
std.mem.readInt(u16, bytes[8..10], .big),
std.mem.readInt(u16, bytes[10..12], .big),
std.mem.readInt(u16, bytes[12..14], .big),
std.mem.readInt(u16, bytes[14..16], .big),
};
// Find the longest zero run
var longest_start: usize = 8;
var longest_len: usize = 0;
var current_start: usize = 0;
var current_len: usize = 0;
for (parts, 0..) |part, i| {
if (part == 0) {
if (current_len == 0) {
current_start = i;
}
current_len += 1;
if (current_len > longest_len) {
longest_start = current_start;
longest_len = current_len;
}
} else {
current_len = 0;
}
}
// Only compress if the longest zero run is 2 or more
if (longest_len < 2) {
longest_start = 8;
longest_len = 0;
}
var i: usize = 0;
var abbrv = false;
while (i < parts.len) : (i += 1) {
if (i == longest_start) {
// Emit "::" for the longest zero run
if (!abbrv) {
try w.writeAll(if (i == 0) "::" else ":");
abbrv = true;
}
i += longest_len - 1; // Skip the compressed range
continue;
}
if (abbrv) {
abbrv = false;
}
try w.print("{x}", .{parts[i]});
if (i != parts.len - 1) {
try w.writeAll(":");
}
}
if (u.interface_name) |n| try w.print("%{s}", .{n});
}
};
pub const ParseError = error{
/// If this is returned, more detailed diagnostics can be obtained by
/// calling `Ip6Address.Parsed.init`.
ParseFailed,
/// If this is returned, the IPv6 address had a scope id on it ("%foo"
/// at the end) which requires calling `resolve`.
UnresolvedScope,
};
/// This is a pure function but it cannot handle IPv6 addresses that have
/// scope ids ("%foo" at the end). To also handle those, `resolve` must be
/// called instead, or the lower level `Unresolved` API may be used.
pub fn parse(buffer: []const u8, port: u16) ParseError!Ip6Address {
switch (Unresolved.parse(buffer)) {
.success => |p| return .{
.bytes = p.bytes,
.port = port,
.interface = if (p.interface_name != null) return error.UnresolvedScope else .none,
},
else => return error.ParseFailed,
}
return .{ .ip6 = try Ip6Address.parse(buffer, port) };
}
pub const ResolveError = error{
/// If this is returned, more detailed diagnostics can be obtained by
/// calling the `Parsed.init` function.
ParseFailed,
/// The interface name is longer than the host operating system supports.
NameTooLong,
} || Interface.Name.ResolveError;
/// This function requires an `Io` parameter because it must query the operating
/// system to convert interface name to index. For example, in
/// "fe80::e0e:76ff:fed4:cf22%eno1", "eno1" must be resolved to an index by
/// creating a socket and then using an `ioctl` syscall.
pub fn resolve(io: Io, buffer: []const u8, port: u16) ResolveError!Ip6Address {
return switch (Unresolved.parse(buffer)) {
.success => |p| return .{
.bytes = p.bytes,
.port = port,
.interface = i: {
const text = p.interface_name orelse break :i .none;
const name: Interface.Name = try .fromSlice(text);
break :i try name.resolve(io);
},
},
else => return error.ParseFailed,
};
}
pub const FormatError = Io.Writer.Error || Unresolved.FromAddressError;
/// Includes the optional scope ("%foo" at the end).
///
/// See `format` for an alternative that omits scopes and does
/// not require an `Io` parameter.
pub fn formatResolved(a: Ip6Address, io: Io, w: *Io.Writer) FormatError!void {
const u: Unresolved = try .fromAddress(io);
try w.print("[{f}]:{d}", .{ u, a.port });
}
/// See `formatResolved` for an alternative that additionally prints the optional
/// scope at the end of addresses and requires an `Io` parameter.
pub fn format(a: Ip6Address, w: *Io.Writer) Io.Writer.Error!void {
const u: Unresolved = .{
.bytes = a.bytes,
.interface_name = null,
};
try w.print("[{f}]:{d}", .{ u, a.port });
}
pub fn eql(a: Ip6Address, b: Ip6Address) bool {
return a.port == b.port and std.mem.eql(u8, &a.bytes, &b.bytes);
}
pub fn isMultiCast(a: Ip6Address) bool {
return a.bytes[0] == 0xff;
}
pub fn isLinkLocal(a: Ip6Address) bool {
const b = &a.bytes;
return b[0] == 0xfe and (b[1] & 0xc0) == 0x80;
}
pub fn isLoopBack(a: Ip6Address) bool {
const b = &a.bytes;
return b[0] == 0 and b[1] == 0 and
b[2] == 0 and
b[12] == 0 and b[13] == 0 and
b[14] == 0 and b[15] == 1;
}
pub fn isSiteLocal(a: Ip6Address) bool {
const b = &a.bytes;
return b[0] == 0xfe and (b[1] & 0xc0) == 0xc0;
}
pub fn policy(a: Ip6Address) *const Policy {
const b = &a.bytes;
for (&defined_policies) |*p| {
if (!std.mem.eql(u8, b[0..p.len], p.addr[0..p.len])) continue;
if ((b[p.len] & p.mask) != p.addr[p.len]) continue;
return p;
}
unreachable;
}
pub fn scope(a: Ip6Address) u8 {
if (isMultiCast(a)) return a.bytes[1] & 15;
if (isLinkLocal(a)) return 2;
if (isLoopBack(a)) return 2;
if (isSiteLocal(a)) return 5;
return 14;
}
const defined_policies = [_]Policy{
.{
.addr = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01".*,
.len = 15,
.mask = 0xff,
.prec = 50,
.label = 0,
},
.{
.addr = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00".*,
.len = 11,
.mask = 0xff,
.prec = 35,
.label = 4,
},
.{
.addr = "\x20\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".*,
.len = 1,
.mask = 0xff,
.prec = 30,
.label = 2,
},
.{
.addr = "\x20\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".*,
.len = 3,
.mask = 0xff,
.prec = 5,
.label = 5,
},
.{
.addr = "\xfc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".*,
.len = 0,
.mask = 0xfe,
.prec = 3,
.label = 13,
},
// These are deprecated and/or returned to the address
// pool, so despite the RFC, treating them as special
// is probably wrong.
// { "", 11, 0xff, 1, 3 },
// { "\xfe\xc0", 1, 0xc0, 1, 11 },
// { "\x3f\xfe", 1, 0xff, 1, 12 },
// Last rule must match all addresses to stop loop.
.{
.addr = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".*,
.len = 0,
.mask = 0,
.prec = 40,
.label = 1,
},
};
};
pub const UnixAddress = struct {
path: []const u8,
pub const max_len = 108;
pub const InitError = error{NameTooLong};
pub fn init(p: []const u8) InitError!UnixAddress {
if (p.len > max_len) return error.NameTooLong;
return .{ .path = p };
}
pub const ListenError = error{
AddressFamilyUnsupported,
AddressInUse,
NetworkDown,
SystemResources,
SymLinkLoop,
FileNotFound,
NotDir,
ReadOnlyFileSystem,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
AccessDenied,
PermissionDenied,
AddressUnavailable,
} || Io.Cancelable || Io.UnexpectedError;
pub const ListenOptions = struct {
/// How many connections the kernel will accept on the application's behalf.
/// If more than this many connections pool in the kernel, clients will start
/// seeing "Connection refused".
kernel_backlog: u31 = default_kernel_backlog,
};
pub fn listen(ua: *const UnixAddress, io: Io, options: ListenOptions) ListenError!Server {
assert(ua.path.len <= max_len);
return .{ .socket = .{
.handle = try io.vtable.netListenUnix(io.userdata, ua, options),
.address = .{ .ip4 = .loopback(0) },
} };
}
pub const ConnectError = error{
SystemResources,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
AddressFamilyUnsupported,
ProtocolUnsupportedBySystem,
ProtocolUnsupportedByAddressFamily,
SocketModeUnsupported,
AccessDenied,
PermissionDenied,
SymLinkLoop,
FileNotFound,
NotDir,
ReadOnlyFileSystem,
WouldBlock,
NetworkDown,
} || Io.Cancelable || Io.UnexpectedError;
pub fn connect(ua: *const UnixAddress, io: Io) ConnectError!Stream {
assert(ua.path.len <= max_len);
return .{ .socket = .{
.handle = try io.vtable.netConnectUnix(io.userdata, ua),
.address = .{ .ip4 = .loopback(0) },
} };
}
};
pub const ReceiveFlags = packed struct(u8) {
oob: bool = false,
peek: bool = false,
trunc: bool = false,
_: u5 = 0,
};
pub const IncomingMessage = struct {
/// Populated by receive functions.
from: IpAddress,
/// Populated by receive functions, points into the caller-supplied buffer.
data: []u8,
/// Supplied by caller before calling receive functions; mutated by receive
/// functions.
control: []u8,
/// Populated by receive functions.
flags: Flags,
/// Useful for initializing before calling `receiveManyTimeout`.
pub const init: IncomingMessage = .{
.from = undefined,
.data = undefined,
.control = &.{},
.flags = undefined,
};
pub const Flags = packed struct(u8) {
/// indicates end-of-record; the data returned completed a record
/// (generally used with sockets of type SOCK_SEQPACKET).
eor: bool,
/// indicates that the trailing portion of a datagram was discarded
/// because the datagram was larger than the buffer supplied.
trunc: bool,
/// indicates that some control data was discarded due to lack of
/// space in the buffer for ancil‐ lary data.
ctrunc: bool,
/// indicates expedited or out-of-band data was received.
oob: bool,
/// indicates that no data was received but an extended error from the
/// socket error queue.
errqueue: bool,
_: u3 = 0,
};
};
pub const OutgoingMessage = struct {
address: *const IpAddress,
data_ptr: [*]const u8,
/// Initialized with how many bytes of `data_ptr` to send. After sending
/// succeeds, replaced with how many bytes were actually sent.
data_len: usize,
control: []const u8 = &.{},
};
pub const SendFlags = packed struct(u8) {
confirm: bool = false,
dont_route: bool = false,
eor: bool = false,
oob: bool = false,
fastopen: bool = false,
_: u3 = 0,
};
pub const Interface = struct {
/// Value 0 indicates `none`.
index: u32,
pub const none: Interface = .{ .index = 0 };
pub const Name = struct {
bytes: [max_len:0]u8,
pub const max_len = if (@TypeOf(std.posix.IFNAMESIZE) == void) 0 else std.posix.IFNAMESIZE - 1;
pub fn toSlice(n: *const Name) []const u8 {
return std.mem.sliceTo(&n.bytes, 0);
}
pub fn fromSlice(bytes: []const u8) error{NameTooLong}!Name {
if (bytes.len > max_len) return error.NameTooLong;
return .fromSliceUnchecked(bytes);
}
/// Asserts bytes.len fits in `max_len`.
pub fn fromSliceUnchecked(bytes: []const u8) Name {
assert(bytes.len <= max_len);
var result: Name = undefined;
@memcpy(result.bytes[0..bytes.len], bytes);
result.bytes[bytes.len] = 0;
return result;