/
main.zig
343 lines (293 loc) · 11.3 KB
/
main.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
const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const os = std.os;
const fs = std.fs;
const net = std.net;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
usingnamespace @import("xproto.zig");
pub const Display = struct {
name: []u8,
};
pub const Connection = struct {
allocator: *Allocator,
socket: net.Stream,
setup: []u8,
status: Status,
pub const Status = enum {
SetupFailed = 0,
Ok = 1,
Authenticate = 2,
};
pub fn close(self: *Connection) void {
self.allocator.free(self.setup);
self.socket.close();
self.* = undefined;
}
};
pub const Auth = struct {
family: u16,
address: []u8,
number: []u8,
name: []u8,
data: []u8,
fn deinit(self: *Auth, allocator: *Allocator) void {
allocator.free(self.address);
allocator.free(self.number);
allocator.free(self.name);
allocator.free(self.data);
self.* = undefined;
}
};
pub fn openDefaultDisplay(allocator: *Allocator) !Connection {
const default_name = getDefaultDisplayName() orelse return error.UnknownDefaultDisplay;
return openDisplay(allocator, default_name);
}
pub fn getDefaultDisplayName() ?[]const u8 {
return os.getenv("DISPLAY");
}
pub const OpenDisplayError = error{
OutOfMemory,
InvalidDisplayFormat,
UnableToConnectToServer,
SetupFailed,
AuthFileUnavailable,
// TODO get rid of some of these
FileDescriptorAlreadyPresentInSet,
OperationCausesCircularLoop,
FileDescriptorNotRegistered,
SystemResources,
UserResourceLimitReached,
FileDescriptorIncompatibleWithEpoll,
Unexpected,
InputOutput,
AccessDenied,
EndOfStream,
InvalidStatus,
ConnectionTimedOut,
NotOpenForReading,
NotOpenForWriting,
};
pub fn openDisplay(allocator: *Allocator, name: []const u8) OpenDisplayError!Connection {
const parsed = parseDisplay(name) catch |err| switch (err) {
error.Overflow => return error.InvalidDisplayFormat,
error.MissingColon => return error.InvalidDisplayFormat,
error.MissingDisplayIndex => return error.InvalidDisplayFormat,
error.InvalidCharacter => return error.InvalidDisplayFormat,
};
return try connectToDisplay(allocator, parsed, null);
}
pub const ParsedDisplay = struct {
host: []const u8,
protocol: []const u8,
display: u32,
screen: u32,
};
pub fn parseDisplay(name: []const u8) !ParsedDisplay {
var result = ParsedDisplay{
.host = undefined,
.protocol = name[0..0],
.display = undefined,
.screen = undefined,
};
const after_prot = if (mem.lastIndexOfScalar(u8, name, '/')) |slash_pos| blk: {
result.protocol = name[0..slash_pos];
break :blk name[slash_pos..];
} else name;
const colon = mem.lastIndexOfScalar(u8, after_prot, ':') orelse return error.MissingColon;
var it = mem.split(after_prot[colon + 1 ..], ".");
result.display = try std.fmt.parseInt(u32, it.next() orelse return error.MissingDisplayIndex, 10);
result.screen = if (it.next()) |s| try std.fmt.parseInt(u32, s, 10) else 0;
result.host = after_prot[0..colon];
return result;
}
pub fn open(host: []const u8, protocol: []const u8, display: u32) !net.Stream {
if (protocol.len != 0 and !mem.eql(u8, protocol, "unix")) {
return error.UnsupportedProtocol;
}
var path_buf: [fs.MAX_PATH_BYTES]u8 = undefined;
const socket_path = std.fmt.bufPrint(path_buf[0..], "/tmp/.X11-unix/X{d}", .{display}) catch unreachable;
return net.connectUnixSocket(socket_path);
}
pub fn connectToDisplay(allocator: *Allocator, parsed: ParsedDisplay, optional_auth: ?Auth) !Connection {
const sock = open(parsed.host, parsed.protocol, parsed.display) catch return error.UnableToConnectToServer;
errdefer sock.close();
var cleanup_auth = false;
var auth = if (optional_auth) |a| a else blk: {
cleanup_auth = true;
break :blk getAuth(allocator, sock, parsed.display) catch |e| switch (e) {
error.WouldBlock => unreachable,
error.OperationAborted => unreachable,
error.ConnectionResetByPeer => return error.AuthFileUnavailable,
error.IsDir => return error.AuthFileUnavailable,
error.SharingViolation => return error.AuthFileUnavailable,
error.PathAlreadyExists => return error.AuthFileUnavailable,
error.FileNotFound => return error.AuthFileUnavailable,
error.PipeBusy => return error.AuthFileUnavailable,
error.NameTooLong => return error.AuthFileUnavailable,
error.InvalidUtf8 => return error.AuthFileUnavailable,
error.BadPathName => return error.AuthFileUnavailable,
error.FileTooBig => return error.AuthFileUnavailable,
error.SymLinkLoop => return error.AuthFileUnavailable,
error.ProcessFdQuotaExceeded => return error.AuthFileUnavailable,
error.NoDevice => return error.AuthFileUnavailable,
error.NoSpaceLeft => return error.AuthFileUnavailable,
error.EndOfStream => return error.AuthFileUnavailable,
error.InputOutput => return error.AuthFileUnavailable,
error.NotDir => return error.AuthFileUnavailable,
error.AccessDenied => return error.AuthFileUnavailable,
error.HomeDirectoryNotFound => return error.AuthFileUnavailable,
error.BrokenPipe => return error.AuthFileUnavailable,
error.DeviceBusy => return error.AuthFileUnavailable,
error.PermissionDenied => return error.AuthFileUnavailable,
error.FileLocksNotSupported => return error.AuthFileUnavailable,
error.ConnectionTimedOut => return error.AuthFileUnavailable,
error.NotOpenForReading => return error.AuthFileUnavailable,
error.Unexpected => return error.Unexpected,
error.SystemFdQuotaExceeded => return error.SystemResources,
error.SystemResources => return error.AuthFileUnavailable,
error.OutOfMemory => return error.OutOfMemory,
};
};
defer if (cleanup_auth) auth.deinit(allocator);
return connectToStream(allocator, sock, auth) catch |err| switch (err) {
error.WouldBlock => unreachable,
error.DiskQuota => unreachable,
error.OperationAborted => unreachable,
error.FileTooBig => unreachable,
error.NoSpaceLeft => unreachable,
error.IsDir => return error.UnableToConnectToServer,
error.BrokenPipe => return error.UnableToConnectToServer,
error.ConnectionResetByPeer => return error.UnableToConnectToServer,
else => |e| return e,
};
}
fn xpad(n: usize) usize {
return @bitCast(usize, (-%@bitCast(isize, n)) & 3);
}
test "xpad" {
assert(xpad(1) == 3);
assert(xpad(2) == 2);
assert(xpad(3) == 1);
assert(xpad(4) == 0);
assert(xpad(5) == 3);
assert(xpad(6) == 2);
assert(xpad(7) == 1);
assert(xpad(8) == 0);
}
/// sock must be `O_RDWR`.
/// `O_NONBLOCK` may be set if `std.event.Loop.instance != null`.
pub fn connectToStream(allocator: *Allocator, sock: net.Stream, auth: ?Auth) !Connection {
var conn = Connection{
.allocator = allocator,
.socket = sock,
.setup = undefined,
.status = undefined,
};
try writeSetup(sock, auth);
try readSetup(allocator, &conn);
return conn;
}
fn readSetup(allocator: *Allocator, conn: *Connection) !void {
const reader = conn.socket.reader();
const xcb_setup_generic_t = extern struct {
status: u8,
pad0: [5]u8,
length: u16,
};
const header = try reader.readStruct(xcb_setup_generic_t);
conn.setup = try allocator.alloc(u8, header.length * 4);
errdefer allocator.free(conn.setup);
try reader.readNoEof(conn.setup);
conn.status = switch (header.status) {
0 => Connection.Status.SetupFailed,
1 => Connection.Status.Ok,
2 => Connection.Status.Authenticate,
else => return error.InvalidStatus,
};
}
fn writeSetup(sock: net.Stream, auth: ?Auth) !void {
const pad = [3]u8{ 0, 0, 0 };
var parts: [6]os.iovec_const = undefined;
var parts_index: usize = 0;
var setup_req = xcb_setup_request_t{
.byte_order = if (builtin.endian == builtin.Endian.Big) 0x42 else 0x6c,
.pad0 = 0,
.protocol_major_version = X_PROTOCOL,
.protocol_minor_version = X_PROTOCOL_REVISION,
.authorization_protocol_name_len = 0,
.authorization_protocol_data_len = 0,
.pad1 = [2]u8{ 0, 0 },
};
parts[parts_index].iov_len = @sizeOf(xcb_setup_request_t);
parts[parts_index].iov_base = @ptrCast([*]const u8, &setup_req);
parts_index += 1;
comptime assert(xpad(@sizeOf(xcb_setup_request_t)) == 0);
if (auth) |a| {
setup_req.authorization_protocol_name_len = @intCast(u16, a.name.len);
parts[parts_index].iov_len = a.name.len;
parts[parts_index].iov_base = a.name.ptr;
parts_index += 1;
parts[parts_index].iov_len = xpad(a.name.len);
parts[parts_index].iov_base = &pad;
parts_index += 1;
setup_req.authorization_protocol_data_len = @intCast(u16, a.data.len);
parts[parts_index].iov_len = a.data.len;
parts[parts_index].iov_base = a.data.ptr;
parts_index += 1;
parts[parts_index].iov_len = xpad(a.data.len);
parts[parts_index].iov_base = &pad;
parts_index += 1;
}
assert(parts_index <= parts.len);
return sock.writevAll(parts[0..parts_index]);
}
pub fn getAuth(allocator: *Allocator, sock: net.Stream, display: u32) !Auth {
const xau_file = if (os.getenv("XAUTHORITY")) |xau_file_name| blk: {
break :blk try fs.openFileAbsolute(xau_file_name, .{});
} else blk: {
const home = os.getenv("HOME") orelse return error.HomeDirectoryNotFound;
var dir = try fs.cwd().openDir(home, .{});
defer dir.close();
break :blk try dir.openFile(".Xauthority", .{});
};
defer xau_file.close();
const stream = xau_file.reader();
var hostname_buf: [os.HOST_NAME_MAX]u8 = undefined;
const hostname = try os.gethostname(&hostname_buf);
while (true) {
var auth = blk: {
const family = try stream.readIntBig(u16);
const address = try readCountedString(allocator, stream);
errdefer allocator.free(address);
const number = try readCountedString(allocator, stream);
errdefer allocator.free(number);
const name = try readCountedString(allocator, stream);
errdefer allocator.free(name);
const data = try readCountedString(allocator, stream);
errdefer allocator.free(data);
break :blk Auth{
.family = family,
.address = address,
.number = number,
.name = name,
.data = data,
};
};
if (mem.eql(u8, hostname, auth.address)) {
return auth;
} else {
auth.deinit(allocator);
continue;
}
}
return error.AuthNotFound;
}
fn readCountedString(allocator: *Allocator, stream: anytype) ![]u8 {
const len = try stream.readIntBig(u16);
const buf = try allocator.alloc(u8, len);
errdefer allocator.free(buf);
try stream.readNoEof(buf);
return buf;
}