| 1 | # ex:ts=8 sw=4: | ||
| 2 | # $OpenBSD$ | ||
| 3 | # | ||
| 4 | # Copyright (c) 2026 Dick Olsson <hi@senzilla.io> | ||
| 5 | # | ||
| 6 | # Permission to use, copy, modify, and distribute this software for any | ||
| 7 | # purpose with or without fee is hereby granted, provided that the above | ||
| 8 | # copyright notice and this permission notice appear in all copies. | ||
| 9 | # | ||
| 10 | # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES | ||
| 11 | # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF | ||
| 12 | # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR | ||
| 13 | # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES | ||
| 14 | # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN | ||
| 15 | # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF | ||
| 16 | # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | ||
| 17 | |||
| 18 | use v5.36; | ||
| 19 | |||
| 20 | package App::OpenHAP::Host; | ||
| 21 | our $VERSION = '0.1.0'; | ||
| 22 | |||
| 23 | use IO::Socket::INET; | ||
| 24 | use Time::HiRes qw(time); | ||
| 25 | |||
| 26 | use Fugu::EventLoop; | ||
| 27 | use Fugu::File; | ||
| 28 | use Fugu::Log; | ||
| 29 | use Fugu::Mdnsd; | ||
| 30 | use Protocol::HAP::Server; | ||
| 31 | use Protocol::HAP::Store::File; | ||
| 32 | |||
| 33 | # App::OpenHAP::Host - the host of the Protocol::HAP engine. | ||
| 34 | # | ||
| 35 | # The engine owns the protocol; this module owns everything the | ||
| 36 | # operating system hands out: the listening socket, per-connection | ||
| 37 | # reads and writes, the event loop, its timers, the MQTT client, and | ||
| 38 | # the mDNS advertisement. The engine reaches the outside world only | ||
| 39 | # through the contracts it was constructed with. | ||
| 40 | |||
| 41 | # How much the server reads from a client at a time. | ||
| 42 | use constant READ_SIZE => 65536; | ||
| 43 | |||
| 44 | # The interval between MQTT reconnection attempts, in seconds. A | ||
| 45 | # broker that is down stays down for a while, and a daemon that | ||
| 46 | # hammers it helps nobody. | ||
| 47 | use constant MQTT_RECONNECT_INTERVAL => 30; | ||
| 48 | |||
| 49 | sub new ( $class, %args ) | ||
| 50 | { | ||
| 51 | # The other fields - the storage, the engine, the MQTT client, | ||
| 52 | # the mDNS handle, the loop and the listening socket - appear | ||
| 53 | # when their setters and accessors run. | ||
| 54 | my $self = bless { | ||
| 55 | port => $args{port} // 51827, | ||
| 56 | storage_path => $args{storage_path}, | ||
| 57 | |||
| 58 | # Each connection is filed under its session id: the | ||
| 59 | # session and its socket together. A fileno index | ||
| 60 | # resolves reads to the session id. The kernel reuses | ||
| 61 | # descriptors; session ids never repeat. | ||
| 62 | connections => {}, | ||
| 63 | by_fileno => {}, | ||
| 64 | |||
| 65 | mqtt_tick_interval => 0.1, # MQTT poll interval in seconds | ||
| 66 | |||
| 67 | # For the uptime in a control status. Time::HiRes::time | ||
| 68 | # is imported here, and it gives a float; a whole second | ||
| 69 | # is all an uptime needs. | ||
| 70 | started => int time, | ||
| 71 | }, $class; | ||
| 72 | |||
| 73 | $self->{storage} = Protocol::HAP::Store::File->new( | ||
| 74 | path => $self->{storage_path}, | ||
| 75 | logger => Fugu::Log->default, | ||
| 76 | ); | ||
| 77 | |||
| 78 | # Build the engine over the host contracts: the storage, the | ||
| 79 | # process logger, writes through the connection map, and the | ||
| 80 | # one-shot timers of the loop. | ||
| 81 | $self->{engine} = Protocol::HAP::Server->new( | ||
| 82 | name => $args{name}, | ||
| 83 | pin => $args{pin}, | ||
| 84 | setup_id => $args{setup_id}, | ||
| 85 | store => $self->{storage}, | ||
| 86 | logger => Fugu::Log->default, | ||
| 87 | output => sub ( $session, $bytes ) { | ||
| 88 | $self->_write( $session, $bytes ); | ||
| 89 | }, | ||
| 90 | after => sub ( $seconds, $code ) { | ||
| 91 | return $self->loop->after( $seconds, $code ); | ||
| 92 | }, | ||
| 93 | cancel => sub ($handle) { | ||
| 94 | $self->loop->cancel($handle); | ||
| 95 | }, | ||
| 96 | on_pairing_changed => sub ($paired) { | ||
| 97 | $self->_refresh_mdns($paired); | ||
| 98 | }, | ||
| 99 | ); | ||
| 100 | |||
| 101 | return $self; | ||
| 102 | } | ||
| 103 | |||
| 104 | # $self->engine: | ||
| 105 | # The Protocol::HAP engine of this host. | ||
| 106 | sub engine ($self) | ||
| 107 | { | ||
| 108 | return $self->{engine}; | ||
| 109 | } | ||
| 110 | |||
| 111 | # --- delegation to the engine --------------------------------------------- | ||
| 112 | |||
| 113 | sub add_accessory ( $self, $accessory ) | ||
| 114 | { | ||
| 115 | $self->{engine}->add_accessory($accessory); | ||
| 116 | |||
| 117 | return; | ||
| 118 | } | ||
| 119 | |||
| 120 | sub is_paired ($self) | ||
| 121 | { | ||
| 122 | return $self->{engine}->is_paired; | ||
| 123 | } | ||
| 124 | |||
| 125 | sub update_config_number ($self) | ||
| 126 | { | ||
| 127 | return $self->{engine}->update_config_number; | ||
| 128 | } | ||
| 129 | |||
| 130 | # $self->mdns_txt_string: | ||
| 131 | # The TXT records of the engine, in the format that mdnsd | ||
| 132 | # publishes. | ||
| 133 | sub mdns_txt_string ($self) | ||
| 134 | { | ||
| 135 | return Fugu::Mdnsd::format_txt( | ||
| 136 | %{ $self->{engine}->mdns_txt_records } ); | ||
| 137 | } | ||
| 138 | |||
| 139 | # --- the connection plumbing ---------------------------------------------- | ||
| 140 | |||
| 141 | # $self->loop: | ||
| 142 | # The event loop of this server. The server makes one on demand, | ||
| 143 | # so a caller that only wants to drive timers by hand does not | ||
| 144 | # have to build one. | ||
| 145 | sub loop ($self) | ||
| 146 | { | ||
| 147 | $self->{loop} //= Fugu::EventLoop->new; | ||
| 148 | |||
| 149 | return $self->{loop}; | ||
| 150 | } | ||
| 151 | |||
| 152 | # $self->listen: | ||
| 153 | # Open the HAP listener and register it with the loop. The method | ||
| 154 | # returns the socket. It dies when the port is not available: | ||
| 155 | # a HAP server that cannot listen has no reason to run. | ||
| 156 | sub listen ($self) | ||
| 157 | { | ||
| 158 | return $self->{server} if $self->{server}; | ||
| 159 | |||
| 160 | my $server = IO::Socket::INET->new( | ||
| 161 | LocalPort => $self->{port}, | ||
| 162 | Type => SOCK_STREAM, | ||
| 163 | Reuse => 1, | ||
| 164 | Listen => 10, | ||
| 165 | ) | ||
| 166 | or do { | ||
| 167 | Fugu::Log->default->error( | ||
| 168 | 'Cannot create server socket on port %d: %s', | ||
| 169 | $self->{port}, $! ); | ||
| 170 | die "Cannot create server: $!"; | ||
| 171 | }; | ||
| 172 | |||
| 173 | $self->{server} = $server; | ||
| 174 | $self->loop->add_fd( $server, read => sub ($) { $self->_accept } ); | ||
| 175 | |||
| 176 | Fugu::Log->default->info( 'OpenHAP server listening on port %d', | ||
| 177 | $self->{port} ); | ||
| 178 | |||
| 179 | return $server; | ||
| 180 | } | ||
| 181 | |||
| 182 | # $self->run: | ||
| 183 | # Serve until the loop stops. The method returns when a signal | ||
| 184 | # interrupted the loop or a callback stopped it. Thus the caller | ||
| 185 | # runs its own shutdown, and nothing has to exit from inside a | ||
| 186 | # signal handler. | ||
| 187 | sub run ($self) | ||
| 188 | { | ||
| 189 | $self->listen; | ||
| 190 | $self->_register_mqtt; | ||
| 191 | $self->loop->run; | ||
| 192 | |||
| 193 | Fugu::Log->default->info('OpenHAP server stopped'); | ||
| 194 | |||
| 195 | return $self; | ||
| 196 | } | ||
| 197 | |||
| 198 | # $self->shutdown: | ||
| 199 | # Close the listener and every client connection. The caller | ||
| 200 | # calls this after run returns. | ||
| 201 | sub shutdown ($self) | ||
| 202 | { | ||
| 203 | for my $conn ( values %{ $self->{connections} } ) { | ||
| 204 | my $socket = $conn->{socket}; | ||
| 205 | |||
| 206 | $self->loop->remove_fd($socket); | ||
| 207 | $socket->close; | ||
| 208 | } | ||
| 209 | $self->{connections} = {}; | ||
| 210 | $self->{by_fileno} = {}; | ||
| 211 | |||
| 212 | if ( $self->{server} ) { | ||
| 213 | $self->loop->remove_fd( $self->{server} ); | ||
| 214 | $self->{server}->close; | ||
| 215 | $self->{server} = undef; | ||
| 216 | } | ||
| 217 | |||
| 218 | return $self; | ||
| 219 | } | ||
| 220 | |||
| 221 | # $self->_accept: | ||
| 222 | # Take one connection, open its session, and put it on the loop. | ||
| 223 | sub _accept ($self) | ||
| 224 | { | ||
| 225 | my $client = $self->{server}->accept or return; | ||
| 226 | |||
| 227 | Fugu::Log->default->info( 'Client connected from %s', | ||
| 228 | $client->peerhost ); | ||
| 229 | |||
| 230 | my $session = $self->{engine}->session_open; | ||
| 231 | $self->{connections}{ $session->id } = { | ||
| 232 | session => $session, | ||
| 233 | socket => $client, | ||
| 234 | }; | ||
| 235 | $self->{by_fileno}{ fileno $client } = $session->id; | ||
| 236 | |||
| 237 | $self->loop->add_fd( | ||
| 238 | $client, | ||
| 239 | read => sub ($fh) { | ||
| 240 | $self->_handle_client($fh); | ||
| 241 | } ); | ||
| 242 | |||
| 243 | return; | ||
| 244 | } | ||
| 245 | |||
| 246 | # $self->_handle_client($sock): | ||
| 247 | # Read what arrived and hand it to the engine. The engine | ||
| 248 | # returns undef on a fatal condition, and the host closes the | ||
| 249 | # connection. | ||
| 250 | sub _handle_client ( $self, $sock ) | ||
| 251 | { | ||
| 252 | # _accept installs the fileno row and the connection together, | ||
| 253 | # so a fileno the loop reports always resolves | ||
| 254 | my $sid = $self->{by_fileno}{ fileno $sock } // return; | ||
| 255 | my $session = $self->{connections}{$sid}{session}; | ||
| 256 | |||
| 257 | my $data = ''; | ||
| 258 | my $bytes = $sock->sysread( $data, READ_SIZE ); | ||
| 259 | |||
| 260 | if ( !$bytes ) { | ||
| 261 | |||
| 262 | # The connection is closed. The engine releases the | ||
| 263 | # pairing lock if this session holds it. Thus an | ||
| 264 | # aborted pair-setup cannot block pairing until a | ||
| 265 | # restart. | ||
| 266 | my $peer = $sock->peerhost // 'unknown'; | ||
| 267 | $self->_close_client($sock); | ||
| 268 | Fugu::Log->default->info( 'Client disconnected from %s', | ||
| 269 | $peer ); | ||
| 270 | return; | ||
| 271 | } | ||
| 272 | |||
| 273 | unless ( $self->{engine}->receive( $session, $data ) ) { | ||
| 274 | $self->_close_client($sock); | ||
| 275 | } | ||
| 276 | |||
| 277 | return; | ||
| 278 | } | ||
| 279 | |||
| 280 | # $self->_write($session, $bytes): | ||
| 281 | # The output contract of the engine: write the bytes to the | ||
| 282 | # connection that the session is filed under, whole. A | ||
| 283 | # controller that closes mid-write raises SIGPIPE, which would | ||
| 284 | # kill the daemon; the local guard turns it into an EPIPE that | ||
| 285 | # the checked loop reports. A connection the host cannot write | ||
| 286 | # is a connection it drops. | ||
| 287 | sub _write ( $self, $session, $bytes ) | ||
| 288 | { | ||
| 289 | my $conn = $self->{connections}{ $session->id } or return; | ||
| 290 | |||
| 291 | local $SIG{PIPE} = 'IGNORE'; | ||
| 292 | unless ( Fugu::File->_write_all( $conn->{socket}, $bytes, 'session' ) ) | ||
| 293 | { | ||
| 294 | Fugu::Log->default->warning( | ||
| 295 | 'Dropping session %d: write failed', | ||
| 296 | $session->id ); | ||
| 297 | $self->_close_client( $conn->{socket} ); | ||
| 298 | } | ||
| 299 | |||
| 300 | return; | ||
| 301 | } | ||
| 302 | |||
| 303 | # $self->_close_client($sock): | ||
| 304 | # Drop a client and everything the server kept for it. | ||
| 305 | sub _close_client ( $self, $sock ) | ||
| 306 | { | ||
| 307 | # A write failure inside receive drops the connection before | ||
| 308 | # the read path does, so a second close must be a no-op. A | ||
| 309 | # closed handle has no fileno, and a handled one has no row. | ||
| 310 | my $fileno = fileno $sock // return; | ||
| 311 | my $sid = delete $self->{by_fileno}{$fileno} // return; | ||
| 312 | my $conn = delete $self->{connections}{$sid}; | ||
| 313 | |||
| 314 | $self->{engine}->session_close( $conn->{session} ); | ||
| 315 | |||
| 316 | $self->loop->remove_fd($sock); | ||
| 317 | $sock->close; | ||
| 318 | |||
| 319 | return; | ||
| 320 | } | ||
| 321 | |||
| 322 | # --- MQTT ------------------------------------------------------------------- | ||
| 323 | |||
| 324 | # $self->set_mqtt_client($mqtt): | ||
| 325 | # Set the MQTT client for event loop integration | ||
| 326 | sub set_mqtt_client ( $self, $mqtt ) | ||
| 327 | { | ||
| 328 | $self->{mqtt_client} = $mqtt; | ||
| 329 | |||
| 330 | return; | ||
| 331 | } | ||
| 332 | |||
| 333 | # $self->_register_mqtt: | ||
| 334 | # Put the MQTT client on the loop: a tick on every interval, and | ||
| 335 | # a reconnection attempt on its own slower schedule. | ||
| 336 | # | ||
| 337 | # The two are separate timers because they answer to different | ||
| 338 | # clocks. Before this, one poll interval drove both, and the | ||
| 339 | # backoff was an epoch comparison inside the pass. | ||
| 340 | sub _register_mqtt ($self) | ||
| 341 | { | ||
| 342 | return unless $self->{mqtt_client}; | ||
| 343 | return if $self->{mqtt_timers}; | ||
| 344 | |||
| 345 | $self->{mqtt_timers} = [ | ||
| 346 | $self->loop->every( | ||
| 347 | $self->{mqtt_tick_interval}, | ||
| 348 | sub { | ||
| 349 | my $mqtt = $self->{mqtt_client} or return; | ||
| 350 | $mqtt->tick(0) if $mqtt->is_connected; | ||
| 351 | } | ||
| 352 | ), | ||
| 353 | $self->loop->every( | ||
| 354 | MQTT_RECONNECT_INTERVAL, | ||
| 355 | sub { $self->_mqtt_retry } | ||
| 356 | ), | ||
| 357 | ]; | ||
| 358 | |||
| 359 | return; | ||
| 360 | } | ||
| 361 | |||
| 362 | # $self->_mqtt_retry: | ||
| 363 | # One reconnection attempt, if the client is down. | ||
| 364 | sub _mqtt_retry ($self) | ||
| 365 | { | ||
| 366 | my $mqtt = $self->{mqtt_client} or return; | ||
| 367 | return if $mqtt->is_connected; | ||
| 368 | |||
| 369 | unless ( $mqtt->reconnect ) { | ||
| 370 | Fugu::Log->default->debug( | ||
| 371 | 'MQTT reconnection attempt failed, will retry'); | ||
| 372 | return; | ||
| 373 | } | ||
| 374 | |||
| 375 | Fugu::Log->default->info('Reconnected to MQTT broker'); | ||
| 376 | $self->_mqtt_resubscribe_accessories; | ||
| 377 | |||
| 378 | return; | ||
| 379 | } | ||
| 380 | |||
| 381 | # $self->_mqtt_resubscribe_accessories: | ||
| 382 | # Resubscribe all accessories to their MQTT topics | ||
| 383 | sub _mqtt_resubscribe_accessories ($self) | ||
| 384 | { | ||
| 385 | for my $acc ( $self->{engine}->get_bridged_accessories ) { | ||
| 386 | eval { $acc->subscribe_mqtt; }; | ||
| 387 | Fugu::Log->default->error( | ||
| 388 | 'Failed to resubscribe accessory: %s', $@ ) | ||
| 389 | if $@; | ||
| 390 | } | ||
| 391 | |||
| 392 | return; | ||
| 393 | } | ||
| 394 | |||
| 395 | # --- mDNS --------------------------------------------------------------------- | ||
| 396 | |||
| 397 | # $self->set_mdns($mdns): | ||
| 398 | # Set the mDNS registration handle. The engine reports pairing | ||
| 399 | # changes through on_pairing_changed, and this host re-advertises | ||
| 400 | # the TXT record (HAP-mDNS.md ยง8). | ||
| 401 | sub set_mdns ( $self, $mdns ) | ||
| 402 | { | ||
| 403 | $self->{mdns} = $mdns; | ||
| 404 | |||
| 405 | return; | ||
| 406 | } | ||
| 407 | |||
| 408 | # $self->_refresh_mdns($paired): | ||
| 409 | # Re-advertise the TXT record. The engine already filtered for a | ||
| 410 | # real state change. | ||
| 411 | sub _refresh_mdns ( $self, $paired ) | ||
| 412 | { | ||
| 413 | # Never send an update to an unpublished handle. The daemon | ||
| 414 | # can start while mdnsd is down. This code runs on the | ||
| 415 | # pairing path. A write to a dead socket must not be | ||
| 416 | # reachable there. | ||
| 417 | return unless $self->{mdns} && $self->{mdns}->is_published; | ||
| 418 | |||
| 419 | if ( $self->{mdns}->update_txt( txt => $self->mdns_txt_string ) ) { | ||
| 420 | Fugu::Log->default->info( | ||
| 421 | 'Pairing state changed, re-advertised mDNS TXT (sf=%d)', | ||
| 422 | $paired ? 0 : 1 | ||
| 423 | ); | ||
| 424 | } | ||
| 425 | else { | ||
| 426 | Fugu::Log->default->warning( | ||
| 427 | 'mDNS TXT update failed: %s', | ||
| 428 | $self->{mdns}->error // 'unknown' | ||
| 429 | ); | ||
| 430 | } | ||
| 431 | |||
| 432 | return; | ||
| 433 | } | ||
| 434 | |||
| 435 | # --- control ------------------------------------------------------------------ | ||
| 436 | |||
| 437 | # $self->control_status: | ||
| 438 | # What the server can say about itself, for a control client. | ||
| 439 | # | ||
| 440 | # Nothing here is a secret. The setup code, the broker password, | ||
| 441 | # the accessory keys and the controller keys all stay in the | ||
| 442 | # daemon. A reply that carried one would put it in the output of | ||
| 443 | # a command an operator runs in front of other people. | ||
| 444 | sub control_status ($self) | ||
| 445 | { | ||
| 446 | my $engine = $self->{engine}; | ||
| 447 | my $pairings = $self->{storage}->load_pairings; | ||
| 448 | |||
| 449 | # get_bridged_accessories returns a list, and scalar on a list | ||
| 450 | # return gives the last element, not a count | ||
| 451 | my @devices = $engine->get_bridged_accessories; | ||
| 452 | |||
| 453 | return { | ||
| 454 | name => $engine->{name}, | ||
| 455 | port => $self->{port}, | ||
| 456 | paired => $engine->is_paired ? 1 : 0, | ||
| 457 | pairings => scalar keys %$pairings, | ||
| 458 | config_number => $engine->get_config_number, | ||
| 459 | devices => scalar @devices, | ||
| 460 | connections => scalar keys %{ $self->{connections} }, | ||
| 461 | mdns => $self->{mdns} | ||
| 462 | && $self->{mdns}->is_published ? 'published' : 'absent', | ||
| 463 | mqtt => !$self->{mqtt_client} ? 'none' | ||
| 464 | : $self->{mqtt_client}->is_connected ? 'connected' | ||
| 465 | : 'disconnected', | ||
| 466 | started => $self->{started}, | ||
| 467 | }; | ||
| 468 | } | ||
| 469 | |||
| 470 | # $self->control_devices: | ||
| 471 | # The accessories on the bridge, for a control client. The | ||
| 472 | # bridge itself is not one of them: it carries no device. | ||
| 473 | sub control_devices ($self) | ||
| 474 | { | ||
| 475 | my @devices; | ||
| 476 | for my $accessory ( $self->{engine}->get_bridged_accessories ) { | ||
| 477 | push @devices, | ||
| 478 | { | ||
| 479 | aid => $accessory->{aid}, | ||
| 480 | name => $accessory->{name}, | ||
| 481 | model => $accessory->{model}, | ||
| 482 | serial => $accessory->{serial}, | ||
| 483 | class => ref $accessory, | ||
| 484 | topic => $accessory->{mqtt_topic}, | ||
| 485 | }; | ||
| 486 | } | ||
| 487 | |||
| 488 | return [ sort { $a->{aid} <=> $b->{aid} } @devices ]; | ||
| 489 | } | ||
| 490 | |||
| 491 | 1; |