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
|
use crate::error::{ Error, Result };
use crate::facility::{ CreatableFacility, Facility, FacilityType };
use crate::unix::get_username;
use crate::xdg::xdg_runtime_directory;
use std::any::Any;
use std::collections::HashMap;
use std::mem::size_of;
use std::path::{ Path, PathBuf };
use std::slice::{ from_raw_parts, from_raw_parts_mut };
use std::sync::Arc;
use async_channel::{ unbounded, Sender };
use async_executor::StaticExecutor;
use async_fs::{ metadata, read_dir };
use async_fs::unix::FileTypeExt;
use async_lock::Mutex;
use async_net::unix::UnixStream;
use async_task::Task;
use bitflags::bitflags;
use futures_lite::{ AsyncReadExt, AsyncWriteExt, StreamExt };
use futures_lite::io::{ split, ReadHalf, WriteHalf };
use json_event_parser::{ JsonEvent, SliceJsonParser };
#[allow(unused)]
const MAGIC_NUMBER: &[u8; 6] = b"i3-ipc";
pub struct I3 {
_read_socket: Arc<Mutex<ReadHalf<UnixStream>>>,
write_socket: Arc<Mutex<WriteHalf<UnixStream>>>,
_receive_task: Task<()>,
pending_commands: Arc<Mutex<Vec<(u32, Sender<String>)>>>,
event_subscribers:
Arc<Mutex<HashMap<EventType, Vec<Sender<(EventType, String)>>>>>,
}
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EventType: u32 {
const WORKSPACE = 0x00000001;
const OUTPUT = 0x00000002;
const MODE = 0x00000004;
const WINDOW = 0x00000008;
const BARCONFIG_UPDATE = 0x00000010;
const BINDING = 0x00000020;
const SHUTDOWN = 0x00000040;
const TICK = 0x00000080;
}
}
impl EventType {
fn name(&self) -> Result<&str> {
match *self {
EventType::WORKSPACE => Ok("workspace"),
EventType::OUTPUT => Ok("output"),
EventType::MODE => Ok("mode"),
EventType::WINDOW => Ok("window"),
EventType::BARCONFIG_UPDATE => Ok("barconfig_update"),
EventType::BINDING => Ok("binding"),
EventType::SHUTDOWN => Ok("shutdown"),
EventType::TICK => Ok("tick"),
_ => Err(Error::custom("Only one event type at a time."))
}
}
fn from_type_code(type_code: u32) -> Result<Self> {
match type_code & 0x7fffffff {
0 => Ok(EventType::WORKSPACE),
1 => Ok(EventType::OUTPUT),
2 => Ok(EventType::MODE),
3 => Ok(EventType::WINDOW),
4 => Ok(EventType::BARCONFIG_UPDATE),
5 => Ok(EventType::BINDING),
6 => Ok(EventType::SHUTDOWN),
7 => Ok(EventType::TICK),
code => Err(Error::custom(&format!("Unknown event code {}.", code)))
}
}
fn subscribe_request_body(&self) -> Result<String> {
let mut json = String::new();
json.push_str("[");
let mut is_first = true;
for event_type in self.iter() {
if !is_first {
json.push_str(",");
}
json.push_str(" \"");
json.push_str(event_type.name()?);
json.push_str("\"");
is_first = false;
}
json.push_str(" ]");
Ok(json)
}
}
impl Facility for I3 {
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn update(&mut self) -> Result<()> {
Ok(())
}
}
impl CreatableFacility for I3 {
const FACILITY_TYPE: FacilityType = FacilityType::I3;
async fn new(executor: &'static StaticExecutor) -> Result<Self> {
let socket = Self::find_socket().await?;
let (read_socket, write_socket) = split(socket);
let read_socket = Arc::new(Mutex::new(read_socket));
let write_socket = Arc::new(Mutex::new(write_socket));
let pending_commands = Arc::new(Mutex::new(Vec::new()));
let event_subscribers = Arc::new(Mutex::new(HashMap::new()));
let receive_task = executor.spawn(
receive_loop(Arc::clone(&read_socket),
Arc::clone(&pending_commands),
Arc::clone(&event_subscribers)));
/* Please notice that we don't send any initial commands or anything like
* that, we just assume it works. It's tested well enough that that ought
* to be true.
*/
Ok(I3 {
_read_socket: read_socket,
write_socket,
_receive_task: receive_task,
pending_commands, event_subscribers,
})
}
}
impl I3 {
async fn find_socket() -> Result<UnixStream> {
/* We save most errors for the end, because they aren't really errors if
* a subsequent attempt succeeds.
*/
let mut errors: Vec<Error> = Vec::new();
/* According to the i3 documentation, the first-choice path is the one
* set in the config file. However, we opt not to parse the config - this
* would be the sole benefit we'd get from doing so. So, we skip it. If
* this affects you, sorry about that.
*/
match std::env::var("I3SOCK") {
Ok(path) => {
/* If it's set but invalid, we regard that as a reason to immediately
* declare failure.
*/
let path = PathBuf::from(path);
match try_socket_path(&path).await {
Ok(Some(socket)) => { return Ok(socket); }
Ok(None) => { }
Err(error) => { errors.push(error); }
}
}
/* We don't consider the mere absence of an environment variable to be
* an error; the user is perfectly capable of noticing that on their own.
*/
Err(std::env::VarError::NotPresent) => { }
Err(error) => { errors.push(error.into()); }
}
if let Some(mut path) = xdg_runtime_directory()? {
path.push("i3/");
match try_socket_directory(&path).await {
Ok(Some(socket)) => { return Ok(socket); }
Ok(None) => { }
Err(error) => { errors.push(error); }
}
}
/* As before, an absent environment variable is not an error. */
let username = get_username().await?;
let tmp_path: PathBuf = "/tmp/".into();
match try_tmp_directory(&tmp_path, &username).await {
Ok(Some(socket)) => { return Ok(socket); }
Ok(None) => { }
Err(error) => { errors.push(error); }
}
for error in errors { error.log() }
Err(Error::custom("i3 window manager socket not found"))
}
pub async fn command(&mut self, type_code: u32, body: &str) -> Result<String> {
let (sender, receiver) = unbounded();
{
/* Because we hold this lock while performing the write, we know that
* items in the vector are in the same order as the commands were sent in.
*
* Since i3 guarantees that replies come in the same order as requests,
* that's the only property we need to route them. See receive_loop() for
* the other half of this logic.
*/
let mut pending_commands = self.pending_commands.lock().await;
write(Arc::clone(&self.write_socket), type_code, body.as_bytes()).await?;
pending_commands.push((type_code, sender));
}
let response = receiver.recv().await?;
Ok(response)
}
pub async fn subscribe(&mut self, event_types: EventType,
sender: Sender<(EventType, String)>)
-> Result<bool>
{
{
/* No special ordering constraints with this lock. The rare case is
* just that we already have another subscriber to the same event type,
* and inadvertently deliver an event to the new subscriber before we've
* executed the new subscribe command. That's still correct behavior.
*/
let mut event_subscribers = self.event_subscribers.lock().await;
for event_type in event_types.iter() {
match event_subscribers.get_mut(&event_type) {
Some(senders) => {
senders.push(Sender::clone(&sender));
}
None => {
let mut senders = Vec::new();
senders.push(Sender::clone(&sender));
event_subscribers.insert(event_type, senders);
}
}
}
}
let request = event_types.subscribe_request_body()?;
let response = self.command(2, &request).await?;
parse_success_object(response.as_bytes())
}
}
/* One of the ways to find an i3 socket is to look within the tmp directory
* for subdirectories with names having a specific pattern. Do that.
*/
async fn try_tmp_directory(path: &Path, username: &str)
-> Result<Option<UnixStream>>
{
let mut directory = read_dir(path).await?;
while let Some(entry) = directory.try_next().await? {
/* Do not follow symlinks for the name check.
*
* Note also that if the name isn't valid Unicode, it doesn't match the
* pattern anyway.
*/
if let Some(name) = entry.file_name().to_str() {
let prefix = format!("i3-{}.", username);
if name.starts_with(&prefix) {
let tail = &name[prefix.len() ..];
if tail.len() == 6 {
let full_path = path.join(name);
if let Some(socket) = try_socket_directory(&full_path).await? {
return Ok(Some(socket));
}
}
}
}
}
Ok(None)
}
/* Several of the ways to find an i3 socket start with a known directory
* name, and look immediately within it for a socket with a name having a
* specific pattern. Handle that case.
*
* The directory iteration logic is a lot like that for try_tmp_directory().
* In principle, it could make sense to write a helper.
*/
async fn try_socket_directory(path: &Path) -> Result<Option<UnixStream>> {
let mut directory = read_dir(path).await?;
while let Some(entry) = directory.try_next().await? {
/* Do not follow symlinks for the name check.
*
* Note also that if the name isn't valid Unicode, it doesn't match the
* pattern anyway.
*/
if let Some(name) = entry.file_name().to_str() {
let prefix = "ipc-socket.";
if name.starts_with(prefix) {
let tail = &name[prefix.len() ..];
if tail.len() > 0
&& tail.chars().all(|c| { c.is_ascii_digit() })
{
let full_path = path.join(name);
if let Some(socket) = try_socket_path(&full_path).await? {
return Ok(Some(socket));
}
}
}
}
}
Ok(None)
}
/* If we have a candidate full path to an i3 socket, see if it works. */
async fn try_socket_path(path: &Path) -> Result<Option<UnixStream>> {
/* Do follow symlinks, for the socket check. */
if !metadata(path).await?.file_type().is_socket() {
return Ok(None);
}
/* Unix-domain sockets don't use open(), despite appearing in the
* filesystem. If you think about it, that makes sense: Each process that
* opens it gets its own send/receive pair. It's not like a pipe.
*/
Ok(Some(UnixStream::connect(path).await?))
}
async fn receive_loop(
socket: Arc<Mutex<ReadHalf<UnixStream>>>,
pending_commands: Arc<Mutex<Vec<(u32, Sender<String>)>>>,
event_subscribers:
Arc<Mutex<HashMap<EventType, Vec<Sender<(EventType, String)>>>>>)
{
loop {
/* This function is the only place we read responses or consume pending
* commands, and it's only ever invoked once. So, we know that as long as
* we consume commands in order, we haven't messed up the order.
*
* On the write end, things are more difficult; see I3::command() for
* details of how we use the mutex there.
*/
match read(Arc::clone(&socket)).await {
Ok((type_code, body)) => {
if type_code & 0x80000000 != 0 {
match EventType::from_type_code(type_code) {
Ok(event_code) => {
/* To avoid tempting fate, we copy the sender list and release the
* lock before dispatching.
*/
let senders = {
let event_subscribers = event_subscribers.lock().await;
if let Some(senders) = event_subscribers.get(&event_code) {
Vec::clone(&senders)
} else { Vec::new() }
};
for sender in senders {
if let Err(error) = sender.send((event_code,
String::clone(&body))).await
{
Into::<Error>::into(error).log();
}
}
/* Receiving an event nobody subscribes to is harmless, and not
* necessarily indicative of a mistake on our end. We just ignore it,
* there's no reason to spam the logs.
*/
}
Err(error) => {
error.log();
}
}
} else {
let mut pending_commands = pending_commands.lock().await;
let mut found_index = None;
for (index, (pending_type_code, _))
in pending_commands.iter().enumerate()
{
if *pending_type_code == type_code {
found_index = Some(index);
break;
}
}
if let Some(index) = found_index {
let (_, sender) = pending_commands.remove(index);
if let Err(error) = sender.send(body).await {
Into::<Error>::into(error).log();
}
} else {
Error::custom(&format!(
"Unexpected response from i3 type {} body {}",
type_code, body)).log();
}
}
}
Err(error) => { error.log() }
}
}
}
async fn write(socket: Arc<Mutex<WriteHalf<UnixStream>>>, type_code: u32,
body: &[u8])
-> Result<()>
{
let mut socket = socket.lock().await;
/* After extensive debugging culminating in socat MITM, it turns out that
* i3 is picky about the header being received in a single packet; if it's
* split, i3 doesn't think it's received a message.
*
* We originally used a repr(C) struct for the header, but the magic
* number is six bytes long, which breaks alignment, so it had to be done
* as two parts, which provoked the misbehavior. Of course we have no
* control over what splitting lower layers of the system might do, but in
* practice as long as we put everything in a single syscall we'll be fine.
*
* So, rather than using a struct, we allocate the whole header as a byte
* array. This is tedious to code, but better for performance anyhow, as
* it's less copying.
*
* We use pointer casts because i3 specifies that it uses the
* architecture's preferred endianness, and this is the easiest way to get
* that. It brings up bad memories of patching other people's programs in
* the 90s to swab their bytes, back when people were in the habit of being
* inadvertently architecture-dependent. Communal trauma notwithstanding,
* in Rust it's about as safe as it can reasonably be.
*/
let length = body.len() as u32;
let mut header: [u8; 14] = [0; 14];
header[0 .. 6].copy_from_slice(MAGIC_NUMBER);
header[6 .. 10].copy_from_slice(unsafe {
from_raw_parts(&raw const length as *const u8, size_of::<u32>())
});
header[10 .. 14].copy_from_slice(unsafe {
from_raw_parts(&raw const type_code as *const u8, size_of::<u32>())
});
socket.write_all(&header).await?;
socket.write_all(body).await?;
Ok(())
}
/* The two calls to read_exact() in here need to be done without releasing
* the mutex. Since they are async functions, doing so holds the lock across
* threads. That means we are in Send-future-land, and must use the Send
* mutices from async_lock, not the non-Send mutices from std.
*
* This is the entire reason we use async_lock. That's fine, it's worth it,
* it's just also worth knowing what we're getting for it.
*/
async fn read(socket: Arc<Mutex<ReadHalf<UnixStream>>>)
-> Result<(u32, String)>
{
let mut socket = socket.lock().await;
/* While it might be nice to use uninitialized memory for this, doing so
* is a giant pain.
*/
let mut header: [u8; 14] = [0; 14];
socket.read_exact(&mut header).await?;
if &header[0 .. 6] != MAGIC_NUMBER {
return Err(Error::custom("Received wrong magic number from i3"));
}
let mut length: u32 = 0;
unsafe {
from_raw_parts_mut(&raw mut length as *mut u8, size_of::<u32>())
}.copy_from_slice(&header[6 .. 10]);
let mut type_code: u32 = 0;
unsafe {
from_raw_parts_mut(&raw mut type_code as *mut u8, size_of::<u32>())
}.copy_from_slice(&header[10 .. 14]);
let mut body: Vec<u8> = [0].repeat(length as usize);
socket.read_exact(&mut body).await?;
let body = String::from_utf8(body)?;
Ok((type_code, body))
}
/* We make no attempt to parse fully general JSON; we exploit our knowledge
* of the format i3 uses. Maybe later.
*/
fn parse_success_object(json: &[u8]) -> Result<bool> {
let mut parser = SliceJsonParser::new(json);
if let JsonEvent::StartObject = parser.parse_next()? { } else {
return Err(Error::custom("Reading i3 JSON, expected object start."));
}
if let JsonEvent::ObjectKey(key) = parser.parse_next()? {
if key == "success" {
if let JsonEvent::Boolean(result) = parser.parse_next()? {
/* That's our answer; exit early. */
return Ok(result);
} else {
return Err(Error::custom("Reading i3 JSON, expected boolean."));
}
} else {
return Err(Error::custom("Reading i3 JSON, expected \"success\" key."));
}
} else {
return Err(Error::custom("Reading i3 JSON, expected object key."));
}
}
fn parse_top_level_key_string(json: &[u8], expected_key: &str) -> Result<String> {
let mut parser = SliceJsonParser::new(json);
if let JsonEvent::StartObject = parser.parse_next()? { } else {
return Err(Error::custom("Reading i3 JSON, expected object start."));
}
if let JsonEvent::ObjectKey(key) = parser.parse_next()? {
if key == expected_key {
if let JsonEvent::String(result) = parser.parse_next()? {
/* That's our answer; exit early. */
return Ok(result.into_owned());
} else {
return Err(Error::custom("Reading i3 JSON, expected string."));
}
} else {
return Err(Error::custom(&format!("Reading i3 JSON, expected {:?} key.",
expected_key)));
}
} else {
return Err(Error::custom("Reading i3 JSON, expected object key."));
}
}
pub fn parse_change_string(json: &[u8]) -> Result<String> {
parse_top_level_key_string(json, "change")
}
pub fn parse_name_string(json: &[u8]) -> Result<String> {
parse_top_level_key_string(json, "name")
}
|