-
Notifications
You must be signed in to change notification settings - Fork 5
/
x.zig
2586 lines (2383 loc) · 86.3 KB
/
x.zig
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
// Protocol Specification: https://www.x.org/docs/XProtocol/proto.pdf
//
// Request format
// -------------------------
// size | offset | description
// -------------------------
// 1 | 0 | major opcode
// 2 | 1 | total request length (including this header)
// 1 | 3 | data?
//
// Major Opcodes (128 - 255 reserved for extensions)
//
// Every request is implicitly assigned a sequence number, starting with 1, that is used in replies, errors and events
//
//
// Reply Format
// -------------------------
// size | offset | description
// -------------------------
// 4 | 0 | length not including first 32 bytes
// 2 | 4 | sequence number
//
//
// Event Format
// ...todo...
//
const std = @import("std");
const stdext = @import("stdext.zig");
const testing = std.testing;
const builtin = @import("builtin");
const posix = std.posix;
const windows = std.os.windows;
pub const inputext = @import("xinputext.zig");
pub const render = @import("xrender.zig");
pub const dbe = @import("xdbe.zig");
// Expose some helpful stuff
pub const MappedFile = @import("MappedFile.zig");
pub const charset = @import("charset.zig");
pub const Charset = charset.Charset;
pub const DoubleBuffer = @import("DoubleBuffer.zig");
pub const ContiguousReadBuffer = @import("ContiguousReadBuffer.zig");
pub const Slice = @import("x/slice.zig").Slice;
pub const keymap = @import("keymap.zig");
pub const TcpBasePort = 6000;
pub const BigEndian = 'B';
pub const LittleEndian = 'l';
// TODO: is there another way to do this, is this somewhere in std?
pub fn optEql(optLeft: anytype, optRight: anytype) bool {
if (optLeft) |left| {
if (optRight) |right| {
return left == right;
} else return false;
} else {
if (optRight) |_| {
return false;
} else return true;
}
}
const ParsedDisplay = struct {
protoLen: u16, // if not specified, then hostIndex will be 0 causing this to be empty
hostLimit: u16,
display_num: u32, // TODO: is there a maximum display number?
preferredScreen: ?u32,
pub fn asFilePath(self: @This(), ptr: [*]const u8) ?[]const u8 {
if (ptr[0] != '/') return null;
return ptr[0 .. self.hostLimit];
}
pub fn protoSlice(self: @This(), ptr: [*]const u8) []const u8 {
return ptr[0..self.protoLen];
}
fn hostIndex(self: @This()) u16 {
return if (self.protoLen == 0) 0 else (self.protoLen + 1);
}
pub fn hostSlice(self: @This(), ptr: [*]const u8) []const u8 {
return ptr[self.hostIndex()..self.hostLimit];
}
pub fn equals(self: @This(), other: @This()) bool {
return self.protoLen == other.protoLen
and self.hostLimit == other.hostLimit
and self.display_num == other.display_num
and optEql(self.preferredScreen, other.preferredScreen);
}
};
// I think I can get away without an allocator here and without
// freeing it and without error.
pub fn getDisplay() []const u8 {
if (builtin.os.tag == .windows) {
// we'll just make an allocator and never free it, no
// big deal
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
return std.process.getEnvVarOwned(arena.allocator(), "DISPLAY") catch |err| switch (err) {
error.EnvironmentVariableNotFound => return ":0",
error.OutOfMemory => @panic("Out of memory"),
error.InvalidWtf8 => @panic("Environment Variables are invalid wtf8?"),
};
}
return posix.getenv("DISPLAY") orelse ":0";
}
// Return: display if set, otherwise the environment variable DISPLAY
//pub fn getDisplay(display: anytype) @TypeOf(display) {
// if (display.length == 0) {
// const env = posix.getenv("DISPLAY");
// if (@TypeOf(display) == []const u8)
// return env else "";
// @compileError("display string type not implemented");
// }
//}
pub const InvalidDisplayError = error {
IsEmpty, // TODO: is this an error?
HasMultipleProtocols,
IsTooLarge,
NoDisplayNumber,
BadDisplayNumber,
BadScreenNumber,
};
// display format: [PROTOCOL/]HOST:DISPLAYNUM[.SCREEN]
// assumption: display.len > 0
pub fn parseDisplay(display: []const u8) InvalidDisplayError!ParsedDisplay {
if (display.len == 0) return InvalidDisplayError.IsEmpty;
if (display.len >= std.math.maxInt(u16))
return InvalidDisplayError.IsTooLarge;
var parsed : ParsedDisplay = .{
.protoLen = 0,
.hostLimit = undefined,
.display_num = undefined,
.preferredScreen = undefined,
};
var index : u16 = 0;
// TODO: if launchd supported, check for <path to socket>[.<screen>]
while (true) {
const c = display[index];
if (c == ':') {
break;
}
if (c == '/') {
// I guess a DISPLAY that starts with '/' is a file path?
// This is the case on my M1 macos laptop.
if (index == 0) return .{
.protoLen = 0,
.hostLimit = @intCast(display.len),
.display_num = 0,
.preferredScreen = null,
};
if (parsed.protoLen > 0)
return InvalidDisplayError.HasMultipleProtocols;
parsed.protoLen = index;
}
index += 1;
if (index == display.len)
return InvalidDisplayError.NoDisplayNumber;
}
parsed.hostLimit = index;
index += 1;
if (index == display.len)
return InvalidDisplayError.NoDisplayNumber;
while (true) {
const c = display[index];
if (c == '.')
break;
index += 1;
if (index == display.len)
break;
}
//std.debug.warn("num '{}'\n", .{display[parsed.hostLimit + 1..index]});
parsed.display_num = std.fmt.parseInt(u32, display[parsed.hostLimit + 1..index], 10) catch
return InvalidDisplayError.BadDisplayNumber;
if (index == display.len) {
parsed.preferredScreen = null;
} else {
index += 1;
parsed.preferredScreen = std.fmt.parseInt(u32, display[index..], 10) catch
return InvalidDisplayError.BadScreenNumber;
}
return parsed;
}
fn testParseDisplay(display: []const u8, proto: []const u8, host: []const u8, display_num: u32, screen: ?u32) !void {
const parsed = try parseDisplay(display);
try testing.expect(std.mem.eql(u8, proto, parsed.protoSlice(display.ptr)));
try testing.expect(std.mem.eql(u8, host, parsed.hostSlice(display.ptr)));
try testing.expectEqual(display_num, parsed.display_num);
try testing.expectEqual(screen, parsed.preferredScreen);
}
test "parseDisplay" {
// no need to test the empty string case, it triggers an assert and a client passing
// one is a bug that needs to be fixed
try testing.expectError(InvalidDisplayError.HasMultipleProtocols, parseDisplay("a//"));
try testing.expectError(InvalidDisplayError.NoDisplayNumber, parseDisplay("0"));
try testing.expectError(InvalidDisplayError.NoDisplayNumber, parseDisplay("0/"));
try testing.expectError(InvalidDisplayError.NoDisplayNumber, parseDisplay("0/1"));
try testing.expectError(InvalidDisplayError.NoDisplayNumber, parseDisplay(":"));
try testing.expectError(InvalidDisplayError.BadDisplayNumber, parseDisplay(":a"));
try testing.expectError(InvalidDisplayError.BadDisplayNumber, parseDisplay(":0a"));
try testing.expectError(InvalidDisplayError.BadDisplayNumber, parseDisplay(":0a."));
try testing.expectError(InvalidDisplayError.BadDisplayNumber, parseDisplay(":0a.0"));
try testing.expectError(InvalidDisplayError.BadDisplayNumber, parseDisplay(":1x"));
try testing.expectError(InvalidDisplayError.BadDisplayNumber, parseDisplay(":1x."));
try testing.expectError(InvalidDisplayError.BadDisplayNumber, parseDisplay(":1x.10"));
try testing.expectError(InvalidDisplayError.BadScreenNumber, parseDisplay(":1.x"));
try testing.expectError(InvalidDisplayError.BadScreenNumber, parseDisplay(":1.0x"));
// TODO: should this be an error or no????
//try testing.expectError(InvalidDisplayError.BadScreenNumber, parseDisplay(":1."));
try testParseDisplay("proto/host:123.456", "proto", "host", 123, 456);
try testParseDisplay("host:123.456", "", "host", 123, 456);
try testParseDisplay(":123.456", "", "", 123, 456);
try testParseDisplay(":123", "", "", 123, null);
try testParseDisplay("a/:43", "a", "", 43, null);
try testParseDisplay("/", "", "/", 0, null);
try testParseDisplay("/some/file/path/x0", "", "/some/file/path/x0", 0, null);
}
const ConnectError = error {
UnsupportedProtocol,
};
pub fn isUnixProtocol(optionalProtocol: ?[]const u8) bool {
if (optionalProtocol) |protocol| {
return std.mem.eql(u8, "unix", protocol);
}
return false;
}
// The application should probably have access to the DISPLAY
// for logging purposes. This might be too much abstraction.
//pub fn connect() !posix.socket_t {
// const display = posix.getenv("DISPLAY") orelse
// return connectExplicit(null, null, 0);
// return connectDisplay(display);
//}
//pub const ConnectDisplayError = InvalidDisplayError;
pub fn connect(display: []const u8, parsed: ParsedDisplay) !posix.socket_t {
const optional_host: ?[]const u8 = blk: {
const host_slice = parsed.hostSlice(display.ptr);
break :blk if (host_slice.len == 0) null else host_slice;
};
const optional_proto: ?[]const u8 = blk: {
const proto_slice = parsed.protoSlice(display.ptr);
break :blk if (proto_slice.len == 0) null else proto_slice;
};
return connectExplicit(optional_host, optional_proto, parsed.display_num);
}
fn defaultTcpHost(optional_host: ?[]const u8) []const u8 {
return if (optional_host) |host| host else "localhost";
}
fn displayToTcpPort(display_num: u32) error{DisplayNumberOutOfRange}!u16 {
const port = TcpBasePort + display_num;
if (port > std.math.maxInt(u16))
return error.DisplayNumberOutOfRange;
return @intCast(port);
}
pub fn connectExplicit(optional_host: ?[]const u8, optional_protocol: ?[]const u8, display_num: u32) !posix.socket_t {
if (optional_protocol) |proto| {
if (std.mem.eql(u8, proto, "unix")) {
if (optional_host) |_|
@panic("TODO: DISPLAY is unix protocol with a host? Is this possible?");
return connectUnixDisplayNum(display_num);
}
if (std.mem.eql(u8, proto, "tcp") or std.mem.eql(u8, proto, "inet"))
return connectTcp(defaultTcpHost(optional_host), try displayToTcpPort(display_num), .{});
if (std.mem.eql(u8, proto, "inet6"))
return connectTcp(defaultTcpHost(optional_host), try displayToTcpPort(display_num), .{ .inet6 = true });
return error.UnhandledDisplayProtocol;
}
if (optional_host) |host| {
if (std.mem.eql(u8, host, "unix")) {
// I don't want to carry this complexity if I don't have to, so for now I'll just make it an error
std.log.err("host is 'unix' this might mean 'unix domain socket' but not sure, giving up for now", .{});
return error.NotSureIWantToSupportAmbiguousUnixHost;
}
if (host[0] == '/')
return connectUnixPath(host);
return connectTcp(host, try displayToTcpPort(display_num), .{});
} else {
if (builtin.os.tag == .windows) {
std.log.err(
"unsure how to connect to DISPLAY :{} on windows, how about specifing a hostname? i.e. localhost:{0}",
.{display_num},
);
std.process.exit(0xff);
}
// otherwise, strategy is to try connecting to a unix domain socket first
// and fall back to tcp localhost otherwise
return connectUnixDisplayNum(display_num) catch |err| switch (err) {
else => |e| return e,
};
// TODO: uncomment this one we handle some of the errors from connectUnix
//return connectTcp("localhost", try displayToTcpPort(display_num), .{});
}
}
pub const ConnectTcpOptions = struct {
inet6: bool = false,
};
pub fn connectTcp(name: []const u8, port: u16, options: ConnectTcpOptions) !posix.socket_t {
if (options.inet6) return error.Inet6NotImplemented;
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const list = try std.net.getAddressList(arena.allocator(), name, port);
defer list.deinit();
for (list.addrs) |addr| {
return (std.net.tcpConnectToAddress(addr) catch |err| switch (err) {
error.ConnectionRefused => {
continue;
},
else => return err,
}).handle;
}
if (list.addrs.len == 0) return error.UnknownHostName;
return posix.ConnectError.ConnectionRefused;
}
pub fn disconnect(sock: posix.socket_t) void {
posix.shutdown(sock, .both) catch {}; // ignore any error here
posix.close(sock);
}
pub fn connectUnixDisplayNum(display_num: u32) !posix.socket_t {
const path_prefix = "/tmp/.X11-unix/X";
var addr = posix.sockaddr.un { .family = posix.AF.UNIX, .path = undefined };
const path = std.fmt.bufPrintZ(
&addr.path,
"{s}{}",
.{path_prefix, display_num},
) catch unreachable;
return connectUnixAddr(&addr, path.len);
}
pub fn connectUnixPath(socket_path: []const u8) !posix.socket_t {
var addr = posix.sockaddr.un { .family = posix.AF.UNIX, .path = undefined };
const path = std.fmt.bufPrintZ(
&addr.path,
"{s}",
.{socket_path},
) catch unreachable;
return connectUnixAddr(&addr, path.len);
}
pub fn connectUnixAddr(addr: *const posix.sockaddr.un, path_len: usize) !posix.socket_t {
const sock = try posix.socket(posix.AF.UNIX, posix.SOCK.STREAM, 0);
errdefer posix.close(sock);
// TODO: should we set any socket options?
const addr_len: posix.socklen_t = @intCast(@offsetOf(posix.sockaddr.un, "path") + path_len + 1);
posix.connect(sock, @ptrCast(addr), addr_len) catch |err| switch (err) {
// TODO: handle some of these errors and translate them so we can "fall back" to tcp
// for example, we might handle error.FileNotFound, but I would probably
// translate most errors to custom ones so we only fallback when we get
// an error on the "connect" call itself
else => |e| {
std.debug.panic("TODO: connect failed with {}, need to implement fallback to TCP", .{e});
return e;
}
};
return sock;
}
//pub const ClientHello = extern struct {
// byte_order : u8 = if (builtin.endian == .Big) BigEndian else LittleEndian,
// proto_major_version : u16,
// proto_minor_version : u16,
//};
pub fn ArrayPointer(comptime T: type) type {
const err = "ArrayPointer not implemented for " ++ @typeName(T);
switch (@typeInfo(T)) {
.Pointer => |info| {
switch (info.size) {
.One => {
switch (@typeInfo(info.child)) {
.Array => |array_info| {
return @Type(std.builtin.Type { .Pointer = .{
.size = .Many,
.is_const = true,
.is_volatile = false,
.alignment = @alignOf(array_info.child),
.address_space = info.address_space,
.child = array_info.child,
.is_allowzero = false,
.sentinel = array_info.sentinel,
}});
},
else => @compileError("here"),
}
},
.Slice => {
return @Type(std.builtin.Type { .Pointer = .{
.size = .Many,
.is_const = info.is_const,
.is_volatile = info.is_volatile,
.alignment = info.alignment,
.address_space = info.address_space,
.child = info.child,
.is_allowzero = info.is_allowzero,
.sentinel = info.sentinel,
}});
},
else => @compileError(err),
}
},
else => @compileError(err),
}
}
pub fn slice(comptime LenType: type, s: anytype) Slice(LenType, ArrayPointer(@TypeOf(s))) {
switch (@typeInfo(@TypeOf(s))) {
.Pointer => |info| {
switch (info.size) {
.One => {
switch (@typeInfo(info.child)) {
.Array => |array_info| {
_ = array_info;
@compileError("here");
// return @Type(std.builtin.Type { .Pointer = .{
// .size = .Many,
// .is_const = true,
// .is_volatile = false,
// .alignment = @alignOf(array_info.child),
// .child = array_info.child,
// .is_allowzero = false,
// .sentinel = array_info.sentinel,
// }});
},
else => @compileError("here"),
}
},
.Slice => return .{ .ptr = s.ptr, .len = @intCast(s.len) },
else => @compileError("cannot slice"),
}
},
else => @compileError("cannot slice"),
}
}
// returns the number of padding bytes to add to `value` to get to a multiple of 4
// TODO: profile this? is % operator expensive?
// NOTE: using std.mem.alignForward instead
//fn pad4(comptime T: type, value: T) T {
// return (4 - (value % 4)) % 4;
//}
pub const AuthFilename = struct {
str: []const u8,
owned: bool,
pub fn deinit(self: AuthFilename, allocator: std.mem.Allocator) void {
if (self.owned) {
allocator.free(self.str);
}
}
};
// returns the auth filename only if it exists.
pub fn getAuthFilename(allocator: std.mem.Allocator) !?AuthFilename {
if (builtin.os.tag == .windows) {
if (std.process.getEnvVarOwned(allocator, "XAUTHORITY")) |filename| {
return .{ .str = filename, .owned = true };
} else |err| switch (err) {
error.EnvironmentVariableNotFound => {},
else => |e| return e,
}
// TODO: is there a default path on windows?
return null;
}
if (posix.getenv("XAUTHORITY")) |e| {
if (std.fs.cwd().accessZ(e, .{})) {
return .{ .str = e, .owned = false };
} else |err| switch (err) {
error.FileNotFound => return error.BadXAuthorityEnv,
else => return err,
}
}
if (posix.getenv("HOME")) |e| {
const path = try std.fs.path.joinZ(allocator, &.{ e, ".Xauthority" });
errdefer allocator.free(path);
if (std.fs.cwd().accessZ(path, .{})) {
return .{ .str = path, .owned = true };
} else |err| switch (err) {
error.FileNotFound => {},
else => return err,
}
}
return null;
}
pub const AuthFamily = enum(u16) {
inet = 0,
unix = 256,
wild = 65535,
_,
pub fn str(self: AuthFamily) ?[]const u8 {
// TODO: can we use an inline switch?
return switch (self) {
.inet => "inet",
.unix => "unix",
.wild => "wild",
else => null,
};
}
};
pub const AuthFilterReason = enum {
address,
display_num,
};
pub const max_sock_filter_addr = if (builtin.os.tag == .windows) 255 else posix.HOST_NAME_MAX;
pub const Addr = struct {
family: AuthFamily,
data: []const u8,
pub fn format(
self: Addr,
comptime fmt_spec: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) @TypeOf(writer).Error!void {
_ = fmt_spec;
_ = options;
const d = self.data;
switch (self.family) {
.inet => if (d.len == 4) {
try writer.print("{}.{}.{}.{}", .{d[0], d[1], d[2], d[3]});
} else {
// TODO: support ipv6?
try writer.print("{}/inet", .{std.fmt.fmtSliceHexLower(d)});
},
.unix => try writer.print("{s}/unix", .{d}),
.wild => try writer.print("*", .{}),
else => |family| try writer.print("{}/{}", .{
std.fmt.fmtSliceHexLower(d),
family,
}),
}
}
};
pub const AuthFilter = struct {
addr: Addr,
display_num: ?u32,
pub fn applySocket(self: *AuthFilter, sock: std.posix.socket_t, addr_buf: *[max_sock_filter_addr]u8) !void {
var addr: posix.sockaddr.storage = undefined;
var addrlen: posix.socklen_t = @sizeOf(@TypeOf(addr));
try posix.getsockname(sock, @ptrCast(&addr), &addrlen);
if (@hasDecl(posix.AF, "LOCAL")) {
if (addr.family == posix.AF.LOCAL) {
self.addr = .{
.family = .unix,
.data = try posix.gethostname(addr_buf),
};
return;
}
}
switch (addr.family) {
posix.AF.INET, posix.AF.INET6 => {
//var remote_addr: posix.sockaddr = undefined;
//var remote_addrlen: posix.socklen_t = 0;
//try posix.getpeername(sock, &remote_addr, &remote_addrlen);
return error.InternetSocketsNotImplemented;
},
else => {},
}
}
pub fn isFiltered(
self: AuthFilter,
auth_mem: []const u8,
entry: AuthIteratorEntry,
) ?AuthFilterReason {
if (self.addr.family != .wild and entry.family != .wild) {
if (entry.family != self.addr.family) return .address;
if (!std.mem.eql(u8, self.addr.data, entry.addr(auth_mem))) return .address;
}
if (self.display_num) |num| {
if (entry.display_num) |entry_num| {
if (num != entry_num) return .display_num;
}
}
return null;
}
};
pub const AuthIteratorEntry = struct {
family: AuthFamily,
addr_start: usize,
addr_end: usize,
name_start: usize,
display_num: ?u32,
name_end: usize,
data_end: usize,
pub fn addr(self: AuthIteratorEntry, mem: []const u8) []const u8 {
return mem[self.addr_start..self.addr_end];
}
pub fn name(self: AuthIteratorEntry, mem: []const u8) []const u8 {
return mem[self.name_start..self.name_end];
}
pub fn data(self: AuthIteratorEntry, mem: []const u8) []const u8 {
return mem[self.name_end + 2..self.data_end];
}
pub fn fmt(self: AuthIteratorEntry, mem: []const u8) Formatter {
return .{ .mem = mem, .entry = self };
}
const Formatter = struct {
mem: []const u8,
entry: AuthIteratorEntry,
pub fn format(
self: Formatter,
comptime fmt_spec: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) @TypeOf(writer).Error!void {
_ = fmt_spec;
_ = options;
const data_slice = self.entry.data(self.mem);
try writer.print("address={} display={?} name='{}' data {} bytes: {}", .{
Addr{
.family = self.entry.family,
.data = self.entry.addr(self.mem),
},
self.entry.display_num,
std.zig.fmtEscapes(self.entry.name(self.mem)),
data_slice.len,
std.fmt.fmtSliceHexUpper(data_slice),
});
}
};
};
pub const AuthIterator = struct {
mem: []const u8,
idx: usize = 0,
pub fn next(self: *AuthIterator) error{InvalidAuthFile}!?AuthIteratorEntry {
if (self.idx == self.mem.len) return null;
if (self.idx + 10 > self.mem.len) return error.InvalidAuthFile;
// TODO: is big endian guaranteed?
// using a fixed endianness makes it look like these files are supposed
// to be compatible across machines, but then it's using c_short which isn't?
const family = std.mem.readInt(u16, self.mem[self.idx..][0..2], .big);
const addr_len = std.mem.readInt(u16, self.mem[self.idx + 2..][0..2], .big);
const addr_start = self.idx + 4;
const addr_end = addr_start + addr_len;
if (addr_end + 2 > self.mem.len) return error.InvalidAuthFile;
const num_len = std.mem.readInt(u16, self.mem[addr_end..][0..2], .big);
const num_end = addr_end + 2 + num_len;
if (num_end + 2 > self.mem.len) return error.InvalidAuthFile;
const name_len = std.mem.readInt(u16, self.mem[num_end..][0..2], .big);
const name_end = num_end + 2 + name_len;
if (name_end + 2 > self.mem.len) return error.InvalidAuthFile;
const data_len = std.mem.readInt(u16, self.mem[name_end..][0..2], .big);
const data_end = name_end + 2 + data_len;
if (data_end > self.mem.len) return error.InvalidAuthFile;
const num_str = self.mem[addr_end + 2 .. num_end];
const num: ?u32 = blk: {
if (num_str.len == 0) break :blk null;
break :blk std.fmt.parseInt(u32, num_str, 10) catch return error.InvalidAuthFile;
};
self.idx = data_end;
return AuthIteratorEntry{
.family = @enumFromInt(family),
.addr_start = addr_start,
.addr_end = addr_end,
.display_num = num,
.name_start = num_end + 2,
.name_end = name_end,
.data_end = data_end,
};
}
};
pub const connect_setup = struct {
pub const max_auth_name_len = std.math.maxInt(u16);
pub const max_auth_data_len = std.math.maxInt(u16);
pub const max_len = getLen(max_auth_name_len, max_auth_data_len);
pub const auth_offset =
1 // byte-order
+ 1 // unused
+ 2 // proto_major_ver
+ 2 // proto_minor_ver
+ 2 // auth_name_len
+ 2 // auth_data_len
+ 2 // unused
;
pub fn getLen(auth_name_len: u16, auth_data_len: u16) u32 {
return auth_offset
//+ auth_name_len
//+ pad4(u16, auth_name_len)
+ std.mem.alignForward(u32, auth_name_len, 4)
//+ auth_data_len
//+ pad4(u16, auth_data_len)
+ std.mem.alignForward(u32, auth_data_len, 4)
;
}
pub fn serialize(
buf: [*]u8,
proto_major_ver: u16,
proto_minor_ver: u16,
auth_name: Slice(u16, [*]const u8),
auth_data: Slice(u16, [*]const u8),
) void {
buf[0] = @as(u8, if (builtin.target.cpu.arch.endian() == .big) BigEndian else LittleEndian);
buf[1] = 0; // unused
writeIntNative(u16, buf + 2, proto_major_ver);
writeIntNative(u16, buf + 4, proto_minor_ver);
writeIntNative(u16, buf + 6, auth_name.len);
writeIntNative(u16, buf + 8, auth_data.len);
writeIntNative(u16, buf + 10, 0); // unused
@memcpy(buf[12..][0..auth_name.len], auth_name.nativeSlice());
//const off = 12 + pad4(u16, auth_name.len);
const off : u16 = 12 + std.mem.alignForward(u16, auth_name.len, 4);
@memcpy(buf[off..][0..auth_data.len], auth_data.nativeSlice());
std.debug.assert(
getLen(auth_name.len, auth_data.len) ==
off + std.mem.alignForward(u16, auth_data.len, 4)
);
}
};
test "ConnectSetupMessage" {
const auth_name = comptime slice(u16, @as([]const u8, "hello"));
const auth_data = comptime slice(u16, @as([]const u8, "there"));
const len = comptime connect_setup.getLen(auth_name.len, auth_data.len);
var buf: [len]u8 = undefined;
connect_setup.serialize(&buf, 1, 1, auth_name, auth_data);
}
pub const Opcode = enum(u8) {
create_window = 1,
change_window_attributes = 2,
map_window = 8,
intern_atom = 16,
grab_pointer = 26,
ungrab_pointer = 27,
warp_pointer = 41,
open_font = 45,
close_font = 46,
query_font = 47,
query_text_extents = 48,
list_fonts = 49,
get_font_path = 52,
create_pixmap = 53,
free_pixmap = 54,
create_gc = 55,
change_gc = 56,
clear_area = 61,
copy_area = 62,
poly_line = 65,
poly_rectangle = 67,
poly_fill_rectangle = 70,
put_image = 72,
image_text8 = 76,
create_colormap = 78,
free_colormap = 79,
query_extension = 98,
get_keyboard_mapping = 101,
_,
};
pub const BitGravity = enum(u4) {
forget = 0,
north_west = 1,
north = 2,
north_east = 3,
west = 4,
center = 5,
east = 6,
south_west = 7,
south = 8,
south_east = 9,
static = 10,
};
pub const WinGravity = enum(u4) {
unmap = 0,
north_west = 1,
north = 2,
north_east = 3,
west = 4,
center = 5,
east = 6,
south_west = 7,
south = 8,
south_east = 9,
static = 10,
};
fn isDefaultValue(s: anytype, comptime field: std.builtin.Type.StructField) bool {
const default_value_ptr = @as(?*align(1) const field.type, @ptrCast(field.default_value)) orelse
@compileError("isDefaultValue was called on field '" ++ field.name ++ "' which has no default value");
switch (@typeInfo(field.type)) {
.Optional => {
comptime std.debug.assert(default_value_ptr.* == null); // we're assuming all Optionals default to null
return @field(s, field.name) == null;
},
else => {
return @field(s, field.name) == default_value_ptr.*;
},
}
}
fn optionToU32(value: anytype) u32 {
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.Bool => return @intFromBool(value),
.Enum => return @intFromEnum(value),
else => {},
}
if (T == u32) return value;
if (T == ?u32) return value.?;
if (T == u16) return @intCast(value);
@compileError("TODO: implement optionToU32 for type: " ++ @typeName(T));
}
pub const event = struct {
pub const key_press = (1 << 0);
pub const key_release = (1 << 1);
pub const button_press = (1 << 2);
pub const button_release = (1 << 3);
pub const enter_window = (1 << 4);
pub const leave_window = (1 << 5);
pub const pointer_motion = (1 << 6);
pub const pointer_motion_hint= (1 << 7);
pub const button1_motion = (1 << 8);
pub const button2_motion = (1 << 9);
pub const button3_motion = (1 << 10);
pub const button4_motion = (1 << 11);
pub const button5_motion = (1 << 12);
pub const button_motion = (1 << 13);
pub const keymap_state = (1 << 14);
pub const exposure = (1 << 15);
pub const visibility_change = (1 << 16);
pub const structure_notify = (1 << 17);
pub const resize_redirect = (1 << 18);
pub const substructure_notify= (1 << 19);
pub const substructure_redirect= (1 << 20);
pub const focus_change = (1 << 21);
pub const property_change = (1 << 22);
pub const colormap_change = (1 << 23);
pub const owner_grab_button = (1 << 24);
pub const unused_mask: u32 = (0x7f << 25);
};
pub const pointer_event = struct {
pub const button_press = event.button_press;
pub const button_release = event.button_release;
pub const enter_window = event.enter_window;
pub const leave_window = event.leave_window;
pub const pointer_motion = event.pointer_motion;
pub const pointer_motion_hint= event.pointer_motion_hint;
pub const button1_motion = event.button1_motion;
pub const button2_motion = event.button2_motion;
pub const button3_motion = event.button3_motion;
pub const button4_motion = event.button4_motion;
pub const button5_motion = event.button5_motion;
pub const button_motion = event.button_motion;
pub const keymap_state = event.keymap_state;
pub const unused_mask: u32 = 0xFFFF8003;
};
pub const window = struct {
pub const option_flags = struct {
pub const bg_pixmap : u32 = (1 << 0);
pub const bg_pixel : u32 = (1 << 1);
pub const border_pixmap : u32 = (1 << 2);
pub const border_pixel : u32 = (1 << 3);
pub const bit_gravity : u32 = (1 << 4);
pub const win_gravity : u32 = (1 << 5);
pub const backing_store : u32 = (1 << 6);
pub const backing_planes : u32 = (1 << 7);
pub const backing_pixel : u32 = (1 << 8);
pub const override_redirect : u32 = (1 << 9);
pub const save_under : u32 = (1 << 10);
pub const event_mask : u32 = (1 << 11);
pub const dont_propagate : u32 = (1 << 12);
pub const colormap : u32 = (1 << 13);
pub const cursor : u32 = (1 << 14);
};
pub const BgPixmap = enum(u32) { none = 0, copy_from_parent = 1 };
pub const BorderPixmap = enum(u32) { copy_from_parent = 0 };
pub const BackingStore = enum(u32) { not_useful = 0, when_mapped = 1, always = 2 };
pub const Colormap = enum(u32) { copy_from_parent = 0 };
pub const Cursor = enum(u32) { none = 0 };
pub const Options = struct {
bg_pixmap: BgPixmap = .none,
bg_pixel: ?u32 = null,
border_pixmap: BorderPixmap = .copy_from_parent,
border_pixel: ?u32 = null,
bit_gravity: BitGravity = .forget,
win_gravity: WinGravity = .north_west,
backing_store: BackingStore = .not_useful,
backing_planes: u32 = 0xffffffff,
backing_pixel: u32 = 0,
override_redirect: bool = false,
save_under: bool = false,
event_mask: u32 = 0,
dont_propagate: u32 = 0,
colormap: NonExhaustive(Colormap) = .copy_from_parent,
cursor: Cursor = .none,
};
};
pub const create_window = struct {
pub const non_option_len =
2 // opcode and depth
+ 2 // request length
+ 4 // window id
+ 4 // parent window id
+ 10 // 2 bytes each for x, y, width, height and border-width
+ 2 // window class
+ 4 // visual id
+ 4 // window options value-mask
;
pub const max_len = non_option_len + (15 * 4); // 15 possible 4-byte options
pub const Class = enum(u8) {
copy_from_parent = 0,
input_output = 1,
input_only = 2,
};
pub const Args = struct {
window_id: u32,
parent_window_id: u32,
depth: u8,
x: u16,
y: u16,
width: u16,
height: u16,
border_width: u16,
class: Class,
visual_id: u32,
};
pub fn serialize(buf: [*]u8, args: Args, options: window.Options) u16 {
buf[0] = @intFromEnum(Opcode.create_window);
buf[1] = args.depth;
// buf[2-3] is the len, set at the end of the function
writeIntNative(u32, buf + 4, args.window_id);
writeIntNative(u32, buf + 8, args.parent_window_id);
writeIntNative(u16, buf + 12, args.x);
writeIntNative(u16, buf + 14, args.y);
writeIntNative(u16, buf + 16, args.width);
writeIntNative(u16, buf + 18, args.height);
writeIntNative(u16, buf + 20, args.border_width);
writeIntNative(u16, buf + 22, @intFromEnum(args.class));
writeIntNative(u32, buf + 24, args.visual_id);
var request_len: u16 = non_option_len;
var option_mask: u32 = 0;
inline for (std.meta.fields(window.Options)) |field| {
if (!isDefaultValue(options, field)) {
writeIntNative(u32, buf + request_len, optionToU32(@field(options, field.name)));
option_mask |= @field(window.option_flags, field.name);
request_len += 4;