blib/lib/Protocol/HAP/Server.pm untested

filter: Statementstmt 0.0% 0 / 401 Branchbran 0.0% 0 / 132 Conditioncond 0.0% 0 / 106 MC/DCmcdc 0.0% 0 / 62 Subroutinesub 0.0% 0 / 57 Podpod 0.0% 0 / 40 totaltotal 0.0% 0 / 798 CC 67 SCAR 37.1
CC
67
Cov
0%
_handle_characteristics_get
156.0
_dispatch
110.0
_handle_characteristics_put
110.0
CRAP 40.7
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 Protocol::HAP::Server;
21 our $VERSION = '0.1.0';
22  
23 use JSON::PP;
24 use MIME::Base64 qw(encode_base64);
25 use Digest::SHA qw(sha512);
26  
27 use Protocol::HAP;
28 use Protocol::HAP::HTTP;
29 use Protocol::HAP::TLV;
30 use Protocol::HAP::Session;
31 use Protocol::HAP::Pairing;
32 use Protocol::HAP::Crypto;
33 use Protocol::HAP::Bridge;
34 use Protocol::HAP::Characteristic;
35 use Protocol::HAP::SetupCode qw(normalize_setup_code);
36  
37 # Protocol::HAP::Server - the sans-IO HAP accessory-server engine.
38 #
39 # The engine consumes bytes and emits bytes. The host owns sockets,
40 # timers, logging, and persistence, injected through the contracts
41 # that Protocol/HAP.pod documents. The engine owns everything that is
42 # protocol: the read buffer and its bound, decryption, HTTP parsing,
43 # endpoint dispatch, the pairing state machines, the accessory
44 # database, and event delivery.
45  
46 # The largest request the engine accepts: the header block plus the
47 # body that Content-Length declares. An unpaired client reaches
48 # /pair-setup, so the buffer of an unauthenticated connection needs a
49 # bound of its own. A HAP request is a small TLV or a short JSON
50 # document, so 64 KB is far above anything a controller sends.
51 use constant MAX_REQUEST_SIZE => 65536;
52  
53 # The HAP status code for a request that arrives on an unverified
54 # connection [HAP-HTTP]. It is not an RFC 9110 code, so the codec does
55 # not know its reason phrase.
56 use constant STATUS_INSUFFICIENT_PRIVILEGES => 470;
57  
58 # Characteristic types exempt from coalescing (HAP-HTTP.md §14):
59 # ProgrammableSwitchEvent (0x73), ButtonEvent (0x126),
60 # MotionDetected (0x22), ContactSensorState (0x6A)
61 use constant IMMEDIATE_EVENT_TYPES => {
62 '73' => 1,
63 '126' => 1,
64 '22' => 1,
65 '6A' => 1,
66 };
67  
68 # Event coalescing delay in seconds (HAP-HTTP.md §14)
69 use constant EVENT_COALESCE_DELAY => 0.250;
70  
71 # _response(%args):
72 # Build a response with the HAP defaults: the connection stays
73 # open, because a controller sends every request of a session
74 # over one connection.
75 sub _response (%args)
76 {
77 my %headers = %{ $args{headers} // {} };
78 $headers{Connection} //= 'keep-alive';
79  
80 return Protocol::HAP::HTTP::build_response( %args,
81 headers => \%headers );
82 }
83  
84 # _tlv_response($body):
85 # A 200 response with the pairing TLV content type. Every
86 # pairing and pairings-management reply uses it.
87 sub _tlv_response ($body)
88 {
89 return _response(
90 status => 200,
91 headers => { 'Content-Type' => 'application/pairing+tlv8' },
92 body => $body,
93 );
94 }
95  
96 # _char_status($aid, $iid, $code):
97 # One per-characteristic result entry for the characteristics
98 # endpoints [HAP-HTTP].
99 sub _char_status ( $aid, $iid, $code )
100 {
101 return { aid => $aid + 0, iid => $iid + 0, status => $code };
102 }
103  
104 # $class->new(%args):
105 # name, pin, setup_id, category - the accessory identity.
106 # store, logger, output, after, cancel, on_pairing_changed - the
107 # host contracts of Protocol/HAP.pod. store and output are
108 # required; after and cancel are optional, and without them the
109 # host calls flush_events itself.
110 sub new ( $class, %args )
111 {
112 my $pin = normalize_setup_code( $args{pin} )
113 // die 'valid pin required';
114 my $store = $args{store} // die 'store required';
115 my $output = $args{output} // die 'output required';
116  
117 my $self = bless {
118 pin => $pin,
119 name => $args{name} // 'OpenHAP Bridge',
120 setup_id => $args{setup_id}, # Optional 4-char setup ID
121 category => $args{category} // 2, # Bridge
122  
123 # The host contracts
124 store => $store,
125 logger => $args{logger} // Protocol::HAP->null_logger,
126 output => $output,
127 after => $args{after},
128 cancel => $args{cancel},
129 on_pairing_changed => $args{on_pairing_changed},
130  
131 bridge => undef,
132 pairing => undef,
133  
134 accessory_ltsk => undef,
135 accessory_ltpk => undef,
136  
137 # Session ids come from an instance counter. Two engines
138 # in one process never share one.
139 next_session_id => 1,
140  
141 event_subscriptions => {}, # Track event subscriptions
142 event_queue => {}, # Queued events for coalescing
143 event_flush_timer => undef, # The pending flush, if any
144  
145 # utf8 mode: the codec takes and returns octets, never
146 # wide-character strings. The wire carries octets, the
147 # AEAD layer refuses wide characters, and Content-Length
148 # counts bytes. Without this flag, a non-ASCII value
149 # breaks all three.
150 json => JSON::PP->new->utf8,
151 }, $class;
152  
153 $self->_initialize;
154  
155 return $self;
156 }
157  
158 sub _initialize ($self)
159 {
160 # Load or generate the accessory identity through the store
161 my ( $ltsk, $ltpk ) = $self->{store}->load_accessory_keys;
162 unless ( $ltsk && $ltpk ) {
163 ( $ltsk, $ltpk ) = Protocol::HAP::Crypto->ed25519_keypair;
164 $self->{store}->save_accessory_keys( $ltsk, $ltpk );
165 }
166  
167 $self->{accessory_ltsk} = $ltsk;
168 $self->{accessory_ltpk} = $ltpk;
169  
170 # Initialize the pairing handler
171 $self->{pairing} = Protocol::HAP::Pairing->new(
172 pin => $self->{pin},
173 store => $self->{store},
174 logger => $self->{logger},
175 accessory_ltsk => $self->{accessory_ltsk},
176 accessory_ltpk => $self->{accessory_ltpk},
177 );
178  
179 # Initialize the bridge
180 $self->{bridge} = Protocol::HAP::Bridge->new(
181 name => $self->{name},
182 logger => $self->{logger},
183 );
184  
185 # Deliver device-side changes as EVENT/1.0 notifications.
186 # The bridge forwards the notify_change of each bridged
187 # accessory and keeps the device aid (HAP-HTTP.md §14).
188 # queue_event resolves the current value itself.
189 $self->{bridge}->add_event_callback(
190 sub ( $aid, $iid ) {
191 $self->queue_event( $aid, $iid );
192 } );
193  
194 # The paired state at construction, so the first flip calls
195 # on_pairing_changed
196 $self->{last_paired_state} = $self->is_paired ? 1 : 0;
197  
198 return;
199 }
200  
201 # --- the connection contract --------------------------------------------
202  
203 # $self->session_open:
204 # Return a new session. The host files it beside the connection
205 # it belongs to; the engine never sees the descriptor.
206 sub session_open ($self)
207 {
208 return Protocol::HAP::Session->new(
209 id => $self->{next_session_id}++,
210 logger => $self->{logger},
211 );
212 }
213  
214 # $self->receive($session, $bytes):
215 # Consume what the host read from the connection: decrypt,
216 # buffer, parse, dispatch, and emit every response through the
217 # output contract. The method returns 1, or undef on a fatal
218 # condition - a failed decryption or an over-limit request. On
219 # undef the host closes the connection.
220 sub receive ( $self, $session, $bytes )
221 {
222 # Decrypt the data if the session is encrypted. Keep a
223 # record of the state. Pair-verify M4 enables encryption
224 # during dispatch. But the engine sends the M4 response in
225 # the clear. Encryption applies only to subsequent traffic.
226 my $was_encrypted = $session->is_encrypted;
227 my $data = $bytes;
228 if ($was_encrypted) {
229 $data = $session->decrypt($bytes);
230 unless ( defined $data ) {
231 $self->{logger}
232 ->warning('Decryption failed for client session');
233 return;
234 }
235 }
236  
237 $session->{inbuf} .= $data;
238  
239 # Serve every whole request the buffer holds. A client that
240 # pipelines gets an answer to each one, in order.
241 while ( length $session->{inbuf} ) {
242 my $length =
243 Protocol::HAP::HTTP::message_complete( $session->{inbuf},
244 max_size => MAX_REQUEST_SIZE );
245  
246 # Over the limit. An unpaired client reaches
247 # /pair-setup, so the buffer of an unauthenticated
248 # connection needs a bound of its own.
249 unless ( defined $length ) {
250 $self->{logger}
251 ->warning( 'Request over %d bytes, closing',
252 MAX_REQUEST_SIZE );
253 return;
254 }
255 last if $length == 0; # More bytes are necessary
256  
257 my $message = substr $session->{inbuf}, 0, $length, '';
258 $self->_serve_request( $session, $message, $was_encrypted );
259 }
260  
261 return 1;
262 }
263  
264 # $self->session_close($session):
265 # Release what the session holds: the pairing lock and its event
266 # subscriptions. The host calls this when it closes the
267 # connection.
268 sub session_close ( $self, $session )
269 {
270 $self->{pairing}->clear_pairing_state($session);
271 $self->_purge_event_subscriptions($session);
272  
273 return;
274 }
275  
276 # $self->_serve_request($session, $message, $was_encrypted):
277 # Dispatch one whole request and emit its response.
278 sub _serve_request ( $self, $session, $message, $was_encrypted )
279 {
280 my $request = Protocol::HAP::HTTP::parse_request($message);
281 unless ( defined $request ) {
282 $self->{logger}->warning('Malformed request');
283 $request =
284 { method => '', path => '', headers => {}, body => '' };
285 }
286  
287 $self->{logger}
288 ->info( 'HTTP %s %s', $request->{method}, $request->{path} );
289  
290 # Dispatch the request
291 my $response = $self->_dispatch( $request, $session );
292  
293 # Encrypt the response only if the session was encrypted
294 # when the request arrived. See the note above.
295 if ($was_encrypted) {
296 $response = $session->encrypt($response);
297 }
298  
299 $self->{output}->( $session, $response );
300  
301 # Tell the host if this request changed the pairing state
302 $self->_notify_pairing_changed;
303  
304 return;
305 }
306  
307 # $self->_notify_pairing_changed:
308 # Call on_pairing_changed when the paired state flips. The host
309 # re-advertises its mDNS TXT record [HAP-mDNS §8].
310 sub _notify_pairing_changed ($self)
311 {
312 my $paired = $self->is_paired ? 1 : 0;
313 return if $self->{last_paired_state} == $paired;
314  
315 $self->{last_paired_state} = $paired;
316 $self->{on_pairing_changed}->($paired)
317 if $self->{on_pairing_changed};
318  
319 return;
320 }
321  
322 # --- endpoint dispatch ----------------------------------------------------
323  
324 sub _dispatch ( $self, $request, $session )
325 {
326 my $path = $request->{path};
327 my $method = $request->{method};
328  
329 # Pairing endpoints. These need no verified session.
330 if ( $path eq '/pair-setup' && $method eq 'POST' ) {
331 return $self->_handle_pair_setup( $request, $session );
332 }
333  
334 if ( $path eq '/pair-verify' && $method eq 'POST' ) {
335 return $self->_handle_pair_verify( $request, $session );
336 }
337  
338 # Identify endpoint. It is for unpaired accessories only.
339 if ( $path eq '/identify' && $method eq 'POST' ) {
340 return $self->_handle_identify( $request, $session );
341 }
342  
343 # All other endpoints need a verified session. The 470 code
344 # carries a reason phrase that only HAP defines, so the codec
345 # does not know it.
346 unless ( $session->is_verified ) {
347 return _response(
348 status => STATUS_INSUFFICIENT_PRIVILEGES,
349 status_text => 'Connection Authorization Required',
350 headers => { 'Content-Type' => 'application/hap+json' },
351 );
352 }
353  
354 # Pairings management
355 if ( $path eq '/pairings' && $method eq 'POST' ) {
356 return $self->_handle_pairings( $request, $session );
357 }
358  
359 # Accessory endpoints
360 if ( $path eq '/accessories' && $method eq 'GET' ) {
361 return $self->_handle_accessories( $request, $session );
362 }
363  
364 # Remove the query string for path matching
365 my $base_path = $path;
366 $base_path =~ s/\?.*//;
367  
368 if ( $base_path eq '/characteristics' && $method eq 'GET' ) {
369 return $self->_handle_characteristics_get( $request, $session );
370 }
371  
372 if ( $base_path eq '/characteristics' && $method eq 'PUT' ) {
373 return $self->_handle_characteristics_put( $request, $session );
374 }
375  
376 # Timed write preparation. The spec shows POST in the
377 # table, but the later text uses PUT. Accept both.
378 if ( $path eq '/prepare' && ( $method eq 'PUT' || $method eq 'POST' ) )
379 {
380 return $self->_handle_prepare( $request, $session );
381 }
382  
383 # Not found
384 return _response(
385 status => 404,
386 headers => { 'Content-Type' => 'text/plain' },
387 body => 'Not Found',
388 );
389 }
390  
391 sub _handle_pair_setup ( $self, $request, $session )
392 {
393 $self->{logger}->debug('Handling pair-setup request');
394  
395 return _tlv_response( $self->{pairing}
396 ->handle_pair_setup( $request->{body}, $session ) );
397 }
398  
399 sub _handle_pair_verify ( $self, $request, $session )
400 {
401 $self->{logger}->debug('Handling pair-verify request');
402  
403 return _tlv_response( $self->{pairing}
404 ->handle_pair_verify( $request->{body}, $session ) );
405 }
406  
407 sub _handle_accessories ( $self, $, $ )
408 {
409 my $json = $self->{json}->encode( $self->{bridge}->to_json );
410  
411 return _response(
412 status => 200,
413 headers => { 'Content-Type' => 'application/hap+json' },
414 body => $json,
415 );
416 }
417  
418 # $self->_resolve_char($aid, $iid):
419 # The accessory-then-characteristic lookup that both
420 # characteristics endpoints perform.
421 sub _resolve_char ( $self, $aid, $iid )
422 {
423 my $accessory = $self->{bridge}->get_accessory($aid);
424 return unless $accessory;
425  
426 return $accessory->get_characteristic($iid);
427 }
428  
429 sub _handle_characteristics_get ( $self, $request, $ )
430 {
431 # Parse the query string: ?id=1.11,1.13&meta=1&perms=1&type=1&ev=1
432 my $query = $request->{path};
433 $query =~ s/^.*\?//;
434 $self->{logger}->debug( 'Reading characteristics: %s', $query );
435  
436 my %params;
437 for my $pair ( split /&/, $query ) {
438 my ( $key, $value ) = split /=/, $pair, 2;
439 $params{$key} = $value;
440 }
441  
442 my @ids = split /,/, ( $params{id} // '' );
443 my $include_meta = $params{meta} // 0;
444 my $include_perms = $params{perms} // 0;
445 my $include_type = $params{type} // 0;
446 my $include_ev = $params{ev} // 0;
447  
448 my @characteristics;
449 my $has_errors = 0;
450  
451 for my $id (@ids) {
452 my ( $aid, $iid ) = split /\./, $id;
453  
454 my $char = $self->_resolve_char( $aid, $iid );
455 unless ($char) {
456 push @characteristics,
457 _char_status( $aid, $iid, -70409 );
458 $has_errors = 1;
459 next;
460 }
461  
462 my $result = {
463 aid => $aid + 0,
464 iid => $iid + 0,
465 value => $char->json_value,
466 };
467  
468 # Add the optional metadata if the controller requests it
469 if ($include_meta) {
470 $result->{format} = $char->{format};
471 $result->{unit} = $char->{unit}
472 if defined $char->{unit};
473 $result->{minValue} = $char->{min}
474 if defined $char->{min};
475 $result->{maxValue} = $char->{max}
476 if defined $char->{max};
477 $result->{minStep} = $char->{step}
478 if defined $char->{step};
479 }
480  
481 # Add the permissions if the controller requests them
482 if ($include_perms) {
483 $result->{perms} = $char->{perms};
484 }
485  
486 # Add the type if the controller requests it
487 if ($include_type) {
488 $result->{type} = $char->{type};
489 }
490  
491 # Add the event status if the controller requests it
492 if ($include_ev) {
493 $result->{ev} = $char->events_enabled ? \1 : \0;
494 }
495  
496 push @characteristics, $result;
497 }
498  
499 my $json =
500 $self->{json}->encode( { characteristics => \@characteristics } );
501  
502 return _response(
503 status => $has_errors ? 207 : 200,
504 headers => { 'Content-Type' => 'application/hap+json' },
505 body => $json,
506 );
507 }
508  
509 sub _handle_characteristics_put ( $self, $request, $session )
510 {
511 $self->{logger}->debug('Writing characteristics');
512 my $data = eval { $self->{json}->decode( $request->{body} ) };
513 return _response( status => 400 ) unless $data;
514  
515 my @results;
516 my $has_errors = 0;
517  
518 for my $item ( @{ $data->{characteristics} // [] } ) {
519 my $aid = $item->{aid};
520 my $iid = $item->{iid};
521 my $value = $item->{value};
522  
523 my $char = $self->_resolve_char( $aid, $iid );
524 unless ($char) {
525 push @results, _char_status( $aid, $iid, -70409 );
526 $has_errors = 1;
527 next;
528 }
529  
530 # Check if the characteristic is writable
531 my $is_writable = grep { $_ eq 'pw' } @{ $char->{perms} // [] };
532 if ( defined $value && !$is_writable ) {
533 push @results, _char_status( $aid, $iid, -70404 );
534 $has_errors = 1;
535 next;
536 }
537  
538 # Set the value if the request contains one
539 if ( defined $value ) {
540 eval { $char->set_value($value) };
541 if ($@) {
542 push @results,
543 _char_status( $aid, $iid, -70402 );
544 $has_errors = 1;
545 next;
546 }
547  
548 # Notify the subscribers on other connections.
549 # Exclude the originating session
550 # (HAP-HTTP.md §14).
551 $self->queue_event( $aid, $iid, $char->json_value,
552 $session );
553 }
554  
555 # Enable or disable events
556 if ( exists $item->{ev} ) {
557 my $has_ev =
558 grep { $_ eq 'ev' } @{ $char->{perms} // [] };
559 if ( !$has_ev ) {
560 push @results,
561 _char_status( $aid, $iid, -70406 );
562 $has_errors = 1;
563 next;
564 }
565 $char->enable_events( $item->{ev} );
566  
567 # Record the session for event delivery
568 if ( $item->{ev} ) {
569 $self->_register_event_subscription( $session,
570 $aid, $iid );
571 }
572 else {
573 $self->_unregister_event_subscription( $session,
574 $aid, $iid );
575 }
576 }
577  
578 # Success for this characteristic
579 push @results, _char_status( $aid, $iid, 0 );
580 }
581  
582 # Return 204 No Content when all writes succeed
583 return _response( status => 204 )
584 unless $has_errors;
585  
586 # Return 207 Multi-Status with details if some writes fail
587 my $json = $self->{json}->encode( { characteristics => \@results } );
588 return _response(
589 status => 207,
590 headers => { 'Content-Type' => 'application/hap+json' },
591 body => $json,
592 );
593 }
594  
595 sub _handle_identify ( $self, $, $ )
596 {
597 # Identify is only for unpaired accessories
598 if ( $self->is_paired ) {
599 return _response(
600 status => 400,
601 headers => { 'Content-Type' => 'application/hap+json' },
602 body => $self->{json}->encode( { status => -70401 } ),
603 );
604 }
605  
606 $self->{logger}->info('Identify request received (unpaired)');
607  
608 return _response( status => 204 );
609 }
610  
611 sub _handle_pairings ( $self, $request, $session )
612 {
613 my %tlv = Protocol::HAP::TLV::decode( $request->{body} );
614  
615 my $method_raw = $tlv{ Protocol::HAP::Pairing::kTLVType_Method() };
616 my $method = defined $method_raw ? unpack( 'C', $method_raw ) : -1;
617  
618 $self->{logger}->debug( 'Pairings request method=%d', $method );
619  
620 # Method values: 3=Add, 4=Remove, 5=List
621 if ( $method == 3 ) {
622 return $self->_handle_add_pairing( \%tlv, $session );
623 }
624 elsif ( $method == 4 ) {
625 return $self->_handle_remove_pairing( \%tlv, $session );
626 }
627 elsif ( $method == 5 ) {
628 return $self->_handle_list_pairings( \%tlv, $session );
629 }
630  
631 # Unknown method
632 return $self->_pairings_error(
633 Protocol::HAP::Pairing::kTLVError_Unknown() );
634 }
635  
636 # $self->_pairings_error($code):
637 # One failure response for the pairings endpoints.
638 sub _pairings_error ( $self, $code )
639 {
640 return _tlv_response(
641 Protocol::HAP::TLV::encode(
642 Protocol::HAP::Pairing::kTLVType_State(),
643 pack( 'C', 2 ),
644 Protocol::HAP::Pairing::kTLVType_Error(),
645 pack( 'C', $code ),
646 ) );
647 }
648  
649 # $self->_require_admin($session):
650 # The admin check of the pairings endpoints (HAP-Pairing.md §7).
651 # Return the loaded pairings when the session's controller is an
652 # admin, or undef.
653 sub _require_admin ( $self, $session )
654 {
655 my $pairings = $self->{store}->load_pairings;
656 my $current = $pairings->{ $session->controller_id };
657 return unless $current && $current->{permissions};
658  
659 return $pairings;
660 }
661  
662 sub _handle_add_pairing ( $self, $tlv, $session )
663 {
664 my $identifier =
665 $tlv->{ Protocol::HAP::Pairing::kTLVType_Identifier() };
666 my $ltpk = $tlv->{ Protocol::HAP::Pairing::kTLVType_PublicKey() };
667 my $perms = unpack( 'C',
668 $tlv->{ Protocol::HAP::Pairing::kTLVType_Permissions() }
669 // "\x00" );
670  
671 $self->{logger}
672 ->debug( 'Add pairing request for: %s', $identifier // 'unknown' );
673  
674 # Only admins can add pairings
675 my $pairings = $self->_require_admin($session);
676 unless ($pairings) {
677 return $self->_pairings_error(
678 Protocol::HAP::Pairing::kTLVError_Authentication() );
679 }
680  
681 # An existing identifier with a different LTPK is an error.
682 # With a matching LTPK, the server updates only the
683 # permissions (HAP-Pairing.md §7.4).
684 my $existing = $pairings->{$identifier};
685 if ( $existing && $existing->{ltpk} ne $ltpk ) {
686 return $self->_pairings_error(
687 Protocol::HAP::Pairing::kTLVError_Unknown() );
688 }
689  
690 # Save the pairing
691 $self->{store}->save_pairing( $identifier, $ltpk, $perms );
692 $self->{logger}
693 ->info( 'Added pairing for controller: %s', $identifier );
694  
695 return _tlv_response(
696 Protocol::HAP::TLV::encode(
697 Protocol::HAP::Pairing::kTLVType_State(),
698 pack( 'C', 2 ),
699 ) );
700 }
701  
702 sub _handle_remove_pairing ( $self, $tlv, $session )
703 {
704 my $identifier =
705 $tlv->{ Protocol::HAP::Pairing::kTLVType_Identifier() };
706  
707 $self->{logger}->debug( 'Remove pairing request for: %s',
708 $identifier // 'unknown' );
709  
710 unless ( $self->_require_admin($session) ) {
711 return $self->_pairings_error(
712 Protocol::HAP::Pairing::kTLVError_Authentication() );
713 }
714  
715 # Remove the pairing
716 $self->{store}->remove_pairing($identifier);
717 $self->{logger}
718 ->info( 'Removed pairing for controller: %s', $identifier );
719  
720 # Check if any admins remain (HAP-Pairing.md §7.2). If no
721 # admin remains, remove all pairings and regenerate the
722 # identity.
723 my $remaining = $self->{store}->load_pairings;
724 my $has_admin = grep { $_->{permissions} } values %$remaining;
725 unless ( $has_admin || keys %$remaining == 0 ) {
726 $self->{logger}->info(
727 'Last admin removed - clearing all pairings and regenerating identity'
728 );
729 $self->{store}->remove_all_pairings;
730 $self->_regenerate_identity;
731 }
732  
733 return _tlv_response(
734 Protocol::HAP::TLV::encode(
735 Protocol::HAP::Pairing::kTLVType_State(),
736 pack( 'C', 2 ),
737 ) );
738 }
739  
740 sub _handle_list_pairings ( $self, $, $session )
741 {
742 $self->{logger}->debug('List pairings request');
743  
744 my $pairings = $self->_require_admin($session);
745 unless ($pairings) {
746 return $self->_pairings_error(
747 Protocol::HAP::Pairing::kTLVError_Authentication() );
748 }
749  
750 # Build the response with all pairings. Separate them with
751 # 0xFF.
752 my @response_items =
753 ( Protocol::HAP::Pairing::kTLVType_State(), pack( 'C', 2 ), );
754  
755 my $first = 1;
756 for my $id ( sort keys %$pairings ) {
757 my $pairing = $pairings->{$id};
758  
759 # Add a separator between pairings
760 unless ($first) {
761 push @response_items,
762 Protocol::HAP::Pairing::kTLVType_Separator(), '';
763 }
764 $first = 0;
765  
766 push @response_items,
767 Protocol::HAP::Pairing::kTLVType_Identifier(), $id,
768 Protocol::HAP::Pairing::kTLVType_PublicKey(),
769 $pairing->{ltpk},
770 Protocol::HAP::Pairing::kTLVType_Permissions(),
771 pack( 'C', $pairing->{permissions} );
772 }
773  
774 return _tlv_response( Protocol::HAP::TLV::encode(@response_items) );
775 }
776  
777 sub _handle_prepare ( $self, $request, $ )
778 {
779 $self->{logger}->debug('Timed write prepare request');
780 my $data = eval { $self->{json}->decode( $request->{body} ) };
781 return _response( status => 400 ) unless $data;
782  
783 # Validate the request
784 unless ( defined $data->{ttl} && defined $data->{pid} ) {
785 return _response(
786 status => 400,
787 headers => { 'Content-Type' => 'application/hap+json' },
788 body => $self->{json}->encode( { status => -70410 } ),
789 );
790 }
791  
792 return _response(
793 status => 200,
794 headers => { 'Content-Type' => 'application/hap+json' },
795 body => $self->{json}->encode( { status => 0 } ),
796 );
797 }
798  
799 # --- events ---------------------------------------------------------------
800  
801 # Event subscription tracking. A subscription is filed twice: under
802 # the characteristic, for delivery, and on the session, so that a
803 # disconnect is a delete of what that connection holds and not a
804 # sweep of every characteristic the bridge has.
805 sub _register_event_subscription ( $self, $session, $aid, $iid )
806 {
807 my $key = "$aid.$iid";
808 $self->{event_subscriptions}{$key}{ $session->id } = $session;
809 $session->{subscriptions}{$key} = 1;
810 $self->{logger}->debug( 'Registered event subscription for %s', $key );
811  
812 return;
813 }
814  
815 sub _unregister_event_subscription ( $self, $session, $aid, $iid )
816 {
817 my $key = "$aid.$iid";
818 delete $self->{event_subscriptions}{$key}{ $session->id };
819 delete $session->{subscriptions}{$key};
820 $self->{logger}
821 ->debug( 'Unregistered event subscription for %s', $key );
822  
823 return;
824 }
825  
826 # $self->_purge_event_subscriptions($session):
827 # Remove every subscription that a disconnecting session
828 # holds. Subscriptions are per-connection (HAP-HTTP.md §14).
829 sub _purge_event_subscriptions ( $self, $session )
830 {
831 my $id = $session->id;
832  
833 for my $key ( keys %{ $session->{subscriptions} } ) {
834 delete $self->{event_subscriptions}{$key}{$id};
835 }
836 $session->{subscriptions} = {};
837  
838 return;
839 }
840  
841 # Queue an event for delivery. Coalesce all events except the
842 # immediate-delivery characteristic types. Without a $value, the
843 # current value of the characteristic goes out. The optional
844 # $originator is the session whose request caused the change.
845 # That session never receives the event (HAP-HTTP.md §14).
846 sub queue_event ( $self, $aid, $iid, $value = undef, $originator = undef )
847 {
848 my $char = $self->_resolve_char( $aid, $iid );
849 return unless $char;
850  
851 $value //= $char->json_value;
852  
853 # The immediate types bypass coalescing
854 my $char_type = Protocol::HAP::uuid_to_short( $char->{type} // '' );
855 if ( IMMEDIATE_EVENT_TYPES->{$char_type} ) {
856 $self->send_event( $aid, $iid, $value, $originator );
857 return;
858 }
859  
860 # Queue the event for coalescing
861 my $key = "$aid.$iid";
862 $self->{event_queue}{$key} = {
863 aid => $aid,
864 iid => $iid,
865 value => $value,
866 originator => $originator,
867 };
868  
869 # Schedule one flush for the whole window through the host's
870 # timer contract. A second event inside the window joins the
871 # flush that the first one asked for, which is what coalescing
872 # means. Without the contract, the host calls flush_events
873 # itself.
874 if ( $self->{after} ) {
875 $self->{event_flush_timer} //= $self->{after}->(
876 EVENT_COALESCE_DELAY,
877 sub {
878 $self->{event_flush_timer} = undef;
879 $self->flush_events;
880 } );
881 }
882  
883 return;
884 }
885  
886 # $self->flush_events:
887 # Send every queued event now. The coalesce timer calls this at
888 # the end of the window. A host without the timer contract calls
889 # it directly.
890 sub flush_events ($self)
891 {
892 return unless %{ $self->{event_queue} };
893  
894 for my $event ( values %{ $self->{event_queue} } ) {
895 $self->send_event(
896 $event->{aid}, $event->{iid},
897 $event->{value}, $event->{originator} );
898 }
899  
900 $self->{event_queue} = {};
901  
902 # A direct call empties the queue, so the pending timer has
903 # nothing left to do. Test the handle for definedness, not
904 # truth: the timer contract promises a handle, and a host is
905 # free to hand out a false one.
906 $self->{cancel}->( $self->{event_flush_timer} )
907 if $self->{cancel} && defined $self->{event_flush_timer};
908 $self->{event_flush_timer} = undef;
909  
910 return;
911 }
912  
913 # Send an EVENT/1.0 notification to the subscribed sessions, through
914 # the output contract. Do not send it to the originating session when
915 # the caller gives one (HAP-HTTP.md §14).
916 sub send_event ( $self, $aid, $iid, $value, $originator = undef )
917 {
918 my $key = "$aid.$iid";
919 my $subs = $self->{event_subscriptions}{$key} // {};
920  
921 my $event_body = $self->{json}->encode( {
922 characteristics =>
923 [ { aid => $aid, iid => $iid, value => $value } ] }
924 );
925 my $event_msg = Protocol::HAP::HTTP::build_event($event_body);
926  
927 for my $session ( values %$subs ) {
928 next unless $session && $session->is_encrypted;
929 next if defined $originator && $session == $originator;
930  
931 $self->{output}->( $session, $session->encrypt($event_msg) );
932 }
933  
934 return;
935 }
936  
937 # --- identity and discovery -----------------------------------------------
938  
939 sub is_paired ($self)
940 {
941 my $pairings = $self->{store}->load_pairings;
942 return scalar( keys %$pairings ) > 0;
943 }
944  
945 sub add_accessory ( $self, $accessory )
946 {
947 $self->{bridge}->add_bridged_accessory($accessory);
948  
949 return;
950 }
951  
952 sub get_bridged_accessories ($self)
953 {
954 return $self->{bridge}->get_bridged_accessories;
955 }
956  
957 sub get_config_number ($self)
958 {
959 return $self->{store}->get_config_number;
960 }
961  
962 # $self->update_config_number:
963 # Increment c# when the accessory database changed since the
964 # last run (HAP-mDNS.md §3.1). The host calls this after
965 # device loading. It compares a digest of the accessory
966 # structure against the stored one.
967 sub update_config_number ($self)
968 {
969 my @parts;
970 for my $accessory ( $self->{bridge}->get_all_accessories ) {
971 push @parts, "a$accessory->{aid}";
972 for my $service ( $accessory->get_services ) {
973 push @parts,
974 "s$service->{iid}:" . $service->to_json->{type};
975 for my $char ( $service->get_characteristics ) {
976 push @parts,
977 "c$char->{iid}:"
978 . $char->to_json->{type} . ':'
979 . $char->{format};
980 }
981 }
982 }
983 my $digest = unpack( 'H*', sha512( join( ';', @parts ) ) );
984  
985 my $stored = $self->{store}->get_config_digest;
986 if ( !defined $stored ) {
987  
988 # On the first run, record the digest. c# stays at
989 # its initial value of 1.
990 $self->{store}->save_config_digest($digest);
991 }
992 elsif ( $stored ne $digest ) {
993 $self->{store}->increment_config_number;
994 $self->{store}->save_config_digest($digest);
995 $self->{logger}
996 ->info( 'Accessory database changed, c# is now %d',
997 $self->get_config_number );
998 }
999  
1000 return $self->get_config_number;
1001 }
1002  
1003 sub get_device_id ($self)
1004 {
1005 return Protocol::HAP::device_id( $self->{accessory_ltpk} );
1006 }
1007  
1008 # $self->mdns_txt_records:
1009 # The TXT records of the advertisement, as a hash reference
1010 # [HAP-mDNS §3]. The host formats and publishes them; the wire
1011 # format belongs to the host's mDNS responder, not to HAP.
1012 sub mdns_txt_records ($self)
1013 {
1014 # Note: pv=1, not 1.1. mdnsd uses '.' as the TXT record
1015 # delimiter and does not support escaping. HomeKit accepts
1016 # pv=1.
1017 my $records = {
1018 'c#' => $self->get_config_number,
1019 'ff' => 0,
1020 'id' => $self->get_device_id,
1021 'md' => $self->{name},
1022 'pv' => '1',
1023 's#' => 1,
1024 'sf' => $self->is_paired ? 0 : 1,
1025 'ci' => $self->{category},
1026 };
1027  
1028 # Add the setup hash if setup_id is set
1029 if ( defined $self->{setup_id} && length( $self->{setup_id} ) == 4 ) {
1030 $records->{sh} = $self->_get_setup_hash;
1031 }
1032  
1033 return $records;
1034 }
1035  
1036 # _get_setup_hash() - Calculate the setup hash for mDNS
1037 # The hash is the Base64 of the first 4 bytes of
1038 # SHA-512(setupID + deviceID.toUpperCase())
1039 sub _get_setup_hash ($self)
1040 {
1041 my $setup_id = $self->{setup_id};
1042 my $device_id = $self->get_device_id; # Already uppercase
1043  
1044 my $hash = sha512( $setup_id . $device_id );
1045 my $truncated = substr( $hash, 0, 4 );
1046  
1047 # Encode the truncated hash in Base64 without newlines
1048 my $encoded = encode_base64( $truncated, '' );
1049 return $encoded;
1050 }
1051  
1052 # _regenerate_identity() - Generate new accessory keys after a
1053 # factory reset. The engine calls this after removal of the
1054 # last admin pairing (HAP-Pairing.md §7.2).
1055 sub _regenerate_identity ($self)
1056 {
1057 my ( $ltsk, $ltpk ) = Protocol::HAP::Crypto->ed25519_keypair;
1058 $self->{store}->save_accessory_keys( $ltsk, $ltpk );
1059 $self->{accessory_ltsk} = $ltsk;
1060 $self->{accessory_ltpk} = $ltpk;
1061  
1062 # Reinitialize the pairing handler with the new keys
1063 $self->{pairing} = Protocol::HAP::Pairing->new(
1064 pin => $self->{pin},
1065 store => $self->{store},
1066 logger => $self->{logger},
1067 accessory_ltsk => $self->{accessory_ltsk},
1068 accessory_ltpk => $self->{accessory_ltpk},
1069 );
1070  
1071 # Reset the authentication attempt counter
1072 $self->{pairing}->reset_auth_attempts;
1073  
1074 $self->{logger}->info('Accessory identity regenerated');
1075 return;
1076 }
1077  
1078 1;