second-brain-sync 0.13.2

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
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
use std::cell::{Cell, RefCell};
use std::ffi::{CStr, CString, c_char, c_int, c_short, c_void};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::ptr::{null, null_mut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};

use super::system::{Registrations, Registry, resolved};
use super::{Advert, Adverts, Found, POLL, Responder, txt_record};

/// How often the responder reads its adverts; a pairing listener opened
/// now shows within this.
const REFRESH: Duration = Duration::from_secs(1);
/// The most one instance's resolve and address lookup may take; answers
/// the system service already holds come back at once.
const RESOLVE_WINDOW: Duration = Duration::from_secs(1);
/// mDNSResponder refuses `_second-brain-pair`, longer than RFC 6335's 15
/// characters, in any domain but `local.`, and the Linux responder serves
/// only `local.` anyway.
const DOMAIN: &CStr = c"local.";

type ServiceRef = *mut c_void;
type Flags = u32;
type ErrorType = i32;

const NO_ERROR: ErrorType = 0;
const FLAGS_MORE_COMING: Flags = 0x1;
const FLAGS_ADD: Flags = 0x2;
const PROTOCOL_IPV4: u32 = 0x1;
const AF_INET: u8 = 2;
const POLLIN: c_short = 0x1;

#[repr(C)]
struct PollFd {
    fd: c_int,
    events: c_short,
    revents: c_short,
}

type RegisterReply = unsafe extern "C" fn(
    ServiceRef,
    Flags,
    ErrorType,
    *const c_char,
    *const c_char,
    *const c_char,
    *mut c_void,
);
type BrowseReply = unsafe extern "C" fn(
    ServiceRef,
    Flags,
    u32,
    ErrorType,
    *const c_char,
    *const c_char,
    *const c_char,
    *mut c_void,
);
type ResolveReply = unsafe extern "C" fn(
    ServiceRef,
    Flags,
    u32,
    ErrorType,
    *const c_char,
    *const c_char,
    u16,
    u16,
    *const u8,
    *mut c_void,
);
type AddrInfoReply = unsafe extern "C" fn(
    ServiceRef,
    Flags,
    u32,
    ErrorType,
    *const c_char,
    *const c_void,
    u32,
    *mut c_void,
);

// dns_sd.h; libSystem exports these on every macOS, so nothing extra links.
unsafe extern "C" {
    fn DNSServiceRegister(
        sd_ref: *mut ServiceRef,
        flags: Flags,
        interface_index: u32,
        name: *const c_char,
        regtype: *const c_char,
        domain: *const c_char,
        host: *const c_char,
        port: u16,
        txt_len: u16,
        txt_record: *const c_void,
        callback: Option<RegisterReply>,
        context: *mut c_void,
    ) -> ErrorType;
    fn DNSServiceBrowse(
        sd_ref: *mut ServiceRef,
        flags: Flags,
        interface_index: u32,
        regtype: *const c_char,
        domain: *const c_char,
        callback: Option<BrowseReply>,
        context: *mut c_void,
    ) -> ErrorType;
    fn DNSServiceResolve(
        sd_ref: *mut ServiceRef,
        flags: Flags,
        interface_index: u32,
        name: *const c_char,
        regtype: *const c_char,
        domain: *const c_char,
        callback: Option<ResolveReply>,
        context: *mut c_void,
    ) -> ErrorType;
    fn DNSServiceGetAddrInfo(
        sd_ref: *mut ServiceRef,
        flags: Flags,
        interface_index: u32,
        protocol: u32,
        hostname: *const c_char,
        callback: Option<AddrInfoReply>,
        context: *mut c_void,
    ) -> ErrorType;
    fn DNSServiceRefSockFD(sd_ref: ServiceRef) -> c_int;
    fn DNSServiceProcessResult(sd_ref: ServiceRef) -> ErrorType;
    fn DNSServiceRefDeallocate(sd_ref: ServiceRef);
    fn poll(fds: *mut PollFd, nfds: u32, timeout: c_int) -> c_int;
}

/// One operation with the system's DNS-SD service; dropping it ends the
/// operation, which withdraws a registration.
struct Connection(ServiceRef);

impl Connection {
    fn open(what: &str, start: impl FnOnce(*mut ServiceRef) -> ErrorType) -> Result<Self> {
        let mut sd_ref: ServiceRef = null_mut();
        let error = start(&mut sd_ref);
        if error != NO_ERROR || sd_ref.is_null() {
            bail!("{what}: the system's DNS-SD service answered error {error}");
        }
        Ok(Self(sd_ref))
    }

    fn readable(&self) -> PollFd {
        PollFd {
            fd: unsafe { DNSServiceRefSockFD(self.0) },
            events: POLLIN,
            revents: 0,
        }
    }

    fn process(&self) -> Result<()> {
        let error = unsafe { DNSServiceProcessResult(self.0) };
        if error != NO_ERROR {
            bail!("the system's DNS-SD service answered error {error}");
        }
        Ok(())
    }

    fn run_until(&self, deadline: Instant, done: impl Fn() -> bool) -> Result<()> {
        while !done() {
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                break;
            }
            let mut fds = [self.readable()];
            if wait(&mut fds, left.min(POLL))? > 0 {
                self.process()?;
            }
        }
        Ok(())
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        unsafe { DNSServiceRefDeallocate(self.0) }
    }
}

fn wait(fds: &mut [PollFd], timeout: Duration) -> Result<usize> {
    let ms = c_int::try_from(timeout.as_millis()).unwrap_or(c_int::MAX);
    let count = u32::try_from(fds.len()).context("too many DNS-SD connections")?;
    let ready = unsafe { poll(fds.as_mut_ptr(), count, ms) };
    if ready < 0 {
        let e = std::io::Error::last_os_error();
        if e.kind() == std::io::ErrorKind::Interrupted {
            return Ok(0);
        }
        return Err(e).context("waiting on the system's DNS-SD service");
    }
    Ok(ready as usize)
}

/// The context pointer a callback reads `value` back from; the callback
/// runs only inside `process`, while `value` is borrowed by the caller.
fn context<T>(value: &T) -> *mut c_void {
    (value as *const T).cast_mut().cast()
}

/// Registers this device's adverts with the system's DNS-SD service, so no
/// socket here binds port 5353, which mDNSResponder owns.
pub(super) fn responder(adverts: Adverts) -> Result<Responder> {
    Responder::running(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)), move |stop| {
        serve(stop, adverts.as_ref())
    })
}

fn serve(stop: &AtomicBool, adverts: &(dyn Fn() -> Vec<Advert> + Send + Sync)) {
    let mut registrations = Registrations::new(DnsSd);
    let mut refreshed: Option<Instant> = None;
    while !stop.load(Ordering::SeqCst) {
        if refreshed.is_none_or(|at| at.elapsed() >= REFRESH) {
            registrations.update(&adverts());
            refreshed = Some(Instant::now());
        }
        let mut fds: Vec<PollFd> = registrations.handles().map(Connection::readable).collect();
        if fds.is_empty() {
            std::thread::sleep(POLL);
            continue;
        }
        if let Err(e) = wait(&mut fds, POLL) {
            tracing::warn!("the mDNS responder cannot wait on its registrations: {e:#}");
            std::thread::sleep(POLL);
            continue;
        }
        let mut ready = fds.iter().map(|fd| fd.revents != 0);
        registrations.retain(|connection| {
            if ready.next() != Some(true) {
                return true;
            }
            match connection.process() {
                Ok(()) => true,
                Err(e) => {
                    tracing::warn!("an mDNS registration ended: {e:#}");
                    false
                }
            }
        });
    }
}

struct DnsSd;

impl Registry for DnsSd {
    type Handle = Connection;

    fn register(&mut self, advert: &Advert) -> Result<Connection> {
        let name = CString::new(advert.instance.as_str()).context("an instance name with a NUL")?;
        let regtype = CString::new(advert.service).context("a service name with a NUL")?;
        let txt = txt_record(advert);
        let txt_len = u16::try_from(txt.len()).context("a TXT record over 64 KiB")?;
        Connection::open("registering an mDNS advert", |sd_ref| unsafe {
            DNSServiceRegister(
                sd_ref,
                0,
                0,
                name.as_ptr(),
                regtype.as_ptr(),
                DOMAIN.as_ptr(),
                null(),
                advert.port.to_be(),
                txt_len,
                txt.as_ptr().cast(),
                Some(on_registered),
                null_mut(),
            )
        })
    }
}

unsafe extern "C" fn on_registered(
    _: ServiceRef,
    _: Flags,
    error: ErrorType,
    _: *const c_char,
    _: *const c_char,
    _: *const c_char,
    _: *mut c_void,
) {
    if error != NO_ERROR {
        tracing::warn!("the system's DNS-SD service dropped an mDNS advert: error {error}");
    }
}

#[derive(PartialEq, Eq)]
struct Seen {
    name: CString,
    regtype: CString,
    domain: CString,
    interface: u32,
}

/// Browses through the system's DNS-SD service for `window`, then resolves
/// each instance seen, all of them within one more `window`.
pub(super) fn browse(service: &str, window: Duration) -> Result<Vec<Found>> {
    let regtype = CString::new(service).context("a service name with a NUL")?;
    let seen: RefCell<Vec<Seen>> = RefCell::new(Vec::new());
    let browser = Connection::open("browsing for mDNS adverts", |sd_ref| unsafe {
        DNSServiceBrowse(
            sd_ref,
            0,
            0,
            regtype.as_ptr(),
            DOMAIN.as_ptr(),
            Some(on_browsed),
            context(&seen),
        )
    })?;
    browser.run_until(Instant::now() + window, || false)?;
    drop(browser);
    let deadline = Instant::now() + window;
    let mut found: Vec<Found> = Vec::new();
    for instance in seen.into_inner() {
        let until = deadline.min(Instant::now() + RESOLVE_WINDOW);
        match resolve(&instance, until) {
            Ok(instances) => {
                for one in instances {
                    if !found.contains(&one) {
                        found.push(one);
                    }
                }
            }
            Err(e) => tracing::debug!("cannot resolve an mDNS advert: {e:#}"),
        }
    }
    Ok(found)
}

unsafe extern "C" fn on_browsed(
    _: ServiceRef,
    flags: Flags,
    interface: u32,
    error: ErrorType,
    name: *const c_char,
    regtype: *const c_char,
    domain: *const c_char,
    context: *mut c_void,
) {
    if error != NO_ERROR || name.is_null() || regtype.is_null() || domain.is_null() {
        return;
    }
    let seen = unsafe { &*context.cast::<RefCell<Vec<Seen>>>() };
    let instance = unsafe {
        Seen {
            name: CStr::from_ptr(name).to_owned(),
            regtype: CStr::from_ptr(regtype).to_owned(),
            domain: CStr::from_ptr(domain).to_owned(),
            interface,
        }
    };
    let mut seen = seen.borrow_mut();
    if flags & FLAGS_ADD == 0 {
        seen.retain(|held| *held != instance);
    } else if !seen.contains(&instance) {
        seen.push(instance);
    }
}

struct Target {
    host: CString,
    port: u16,
    txt: Vec<u8>,
}

#[derive(Default)]
struct Addresses {
    found: RefCell<Vec<IpAddr>>,
    settled: Cell<bool>,
}

fn resolve(instance: &Seen, deadline: Instant) -> Result<Vec<Found>> {
    let target: RefCell<Option<Target>> = RefCell::new(None);
    let resolver = Connection::open("resolving an mDNS advert", |sd_ref| unsafe {
        DNSServiceResolve(
            sd_ref,
            0,
            instance.interface,
            instance.name.as_ptr(),
            instance.regtype.as_ptr(),
            instance.domain.as_ptr(),
            Some(on_resolved),
            context(&target),
        )
    })?;
    resolver.run_until(deadline, || target.borrow().is_some())?;
    drop(resolver);
    let Some(target) = target.into_inner() else {
        return Ok(Vec::new());
    };
    let addresses = Addresses::default();
    let lookup = Connection::open("looking up an mDNS host", |sd_ref| unsafe {
        DNSServiceGetAddrInfo(
            sd_ref,
            0,
            instance.interface,
            PROTOCOL_IPV4,
            target.host.as_ptr(),
            Some(on_address),
            context(&addresses),
        )
    })?;
    lookup.run_until(deadline, || addresses.settled.get())?;
    drop(lookup);
    Ok(resolved(
        &instance.name.to_string_lossy(),
        target.port,
        &target.txt,
        &addresses.found.into_inner(),
    ))
}

unsafe extern "C" fn on_resolved(
    _: ServiceRef,
    _: Flags,
    _: u32,
    error: ErrorType,
    _: *const c_char,
    host: *const c_char,
    port: u16,
    txt_len: u16,
    txt: *const u8,
    context: *mut c_void,
) {
    if error != NO_ERROR || host.is_null() {
        return;
    }
    let target = unsafe { &*context.cast::<RefCell<Option<Target>>>() };
    let txt = if txt.is_null() {
        Vec::new()
    } else {
        unsafe { std::slice::from_raw_parts(txt, usize::from(txt_len)) }.to_vec()
    };
    let host = unsafe { CStr::from_ptr(host) }.to_owned();
    target.borrow_mut().get_or_insert(Target {
        host,
        port: u16::from_be(port),
        txt,
    });
}

unsafe extern "C" fn on_address(
    _: ServiceRef,
    flags: Flags,
    _: u32,
    error: ErrorType,
    _: *const c_char,
    address: *const c_void,
    _: u32,
    context: *mut c_void,
) {
    let addresses = unsafe { &*context.cast::<Addresses>() };
    if error == NO_ERROR
        && flags & FLAGS_ADD != 0
        && let Some(ip) = unsafe { ipv4_of(address) }
    {
        addresses.found.borrow_mut().push(ip);
    }
    if flags & FLAGS_MORE_COMING == 0 && !addresses.found.borrow().is_empty() {
        addresses.settled.set(true);
    }
}

/// Reads a BSD `sockaddr`: length, family, then for `AF_INET` the port and
/// the four address bytes.
unsafe fn ipv4_of(address: *const c_void) -> Option<IpAddr> {
    if address.is_null() {
        return None;
    }
    let bytes = unsafe { std::slice::from_raw_parts(address.cast::<u8>(), 8) };
    (bytes[1] == AF_INET).then(|| IpAddr::V4(Ipv4Addr::new(bytes[4], bytes[5], bytes[6], bytes[7])))
}