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

filter: Statementstmt 0.0% 0 / 249 Branchbran 0.0% 0 / 86 Conditioncond 0.0% 0 / 52 MC/DCmcdc 0.0% 0 / 26 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 455 CC 44 SCAR 37.3
CC
44
Cov
0%
_round_trip
110.0
next_event
90.0
pair_setup
56.0
CRAP 41.8
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::Controller;
21 our $VERSION = '0.1.0';
22  
23 use IO::Socket::INET;
24 use IO::Select;
25 use Protocol::HAP;
26 use Protocol::HAP::Crypto;
27 use Protocol::HAP::HTTP;
28 use Protocol::HAP::TLV;
29 use Protocol::HAP::Pairing;
30 use Protocol::HAP::Session;
31  
32 # The controller role of SRP lives beside the accessory role
33 use Protocol::HAP::SRP;
34  
35 # This module is a minimal HomeKit controller. It completes pair-setup
36 # (SRP M1-M6) and pair-verify (X25519). It uses the encrypted session
37 # framing. It connects to a live accessory over TCP, or runs
38 # in-process through an injected transport code ref.
39 #
40 # The controller is the documented exception to the sans-IO rule of
41 # Protocol::HAP: it is a blocking convenience client that owns its
42 # socket. An embedder with an event loop uses the codec modules
43 # directly instead.
44  
45 use constant MAX_FRAME => 1024;
46  
47 # The bound on one response that the controller accumulates. The
48 # accessory database of a bridge with many accessories is the largest
49 # message HAP sends, so the limit is well above the server's own
50 # request limit.
51 use constant MAX_MESSAGE => 1048576;
52  
53 sub new ( $class, %args )
54 {
55 # The id goes into the pair-setup signature, so the library
56 # must not invent one
57 my $controller_id = $args{controller_id}
58 // die 'controller_id required';
59  
60 my $self = bless {
61 host => $args{host} // '127.0.0.1',
62 port => $args{port} // 51827,
63 pin => $args{pin} // '031-45-154',
64 logger => $args{logger} // Protocol::HAP->null_logger,
65 transport => $args{transport},
66  
67 # Socket read timeout. The default is correct for fast
68 # in-process and native runs. A caller that talks to a
69 # slow accessory raises it.
70 timeout => $args{timeout} // 5,
71  
72 controller_id => $controller_id,
73  
74 # The session frame codec, with the key roles swapped
75 # relative to the accessory. pair_verify turns its
76 # encryption on.
77 session => Protocol::HAP::Session->new( id => 0 ),
78  
79 socket => undef,
80 inbuf => '',
81 rawbuf => '',
82 last_error => undef,
83 }, $class;
84  
85 # Controller long-term identity. new makes it once.
86 # pair_setup later fills in accessory_ltpk and accessory_id.
87 ( $self->{ltsk}, $self->{ltpk} ) =
88 Protocol::HAP::Crypto->ed25519_keypair;
89  
90 return $self;
91 }
92  
93 # $self->last_error():
94 # Return the TLV error code or message string of the last
95 # failed exchange.
96 sub last_error ($self)
97 {
98 return $self->{last_error};
99 }
100  
101 sub is_encrypted ($self)
102 {
103 return $self->{session}->is_encrypted;
104 }
105  
106 # --- transport ---------------------------------------------------------
107  
108 sub _connect ($self)
109 {
110 return 1 if $self->{transport} || $self->{socket};
111  
112 my $socket = IO::Socket::INET->new(
113 PeerAddr => $self->{host},
114 PeerPort => $self->{port},
115 Proto => 'tcp',
116 Timeout => $self->{timeout},
117 );
118 unless ( defined $socket ) {
119 $self->{last_error} = "connect: $!";
120 return;
121 }
122  
123 $self->{socket} = $socket;
124 return 1;
125 }
126  
127 sub close ($self)
128 {
129 if ( $self->{socket} ) {
130 $self->{socket}->close;
131 $self->{socket} = undef;
132 }
133  
134 # A fresh session: no keys, no counters, no encryption
135 $self->{session} = Protocol::HAP::Session->new( id => 0 );
136 $self->{inbuf} = '';
137 $self->{rawbuf} = '';
138 return 1;
139 }
140  
141 # $self->_round_trip($request_bytes):
142 # Send the raw bytes and return the plaintext of one HTTP
143 # response. On an encrypted session, the raw bytes accumulate
144 # in rawbuf and every complete frame decrypts exactly once
145 # through the session, so the nonce counter stays in sync.
146 sub _round_trip ( $self, $request )
147 {
148 if ( $self->{transport} ) {
149 my $raw = $self->{transport}->($request);
150 return $raw unless $self->is_encrypted;
151 return unless defined $raw;
152 $self->{rawbuf} .= $raw;
153 return $self->_drain_frames;
154 }
155  
156 return unless $self->_connect;
157  
158 my $socket = $self->{socket};
159 $socket->syswrite($request);
160  
161 # Read until the buffer holds a full, decodable HTTP response
162 my $select = IO::Select->new($socket);
163 my $plain = '';
164 while (1) {
165 last unless $select->can_read( $self->{timeout} );
166 my $bytes = $socket->sysread( my $chunk, 65535 );
167 unless ($bytes) {
168 $self->{last_error} = 'connection closed';
169 last;
170 }
171  
172 if ( $self->is_encrypted ) {
173 $self->{rawbuf} .= $chunk;
174 my $drained = $self->_drain_frames;
175 unless ( defined $drained ) {
176 $self->{last_error} =
177 'response decryption failed';
178 return;
179 }
180 $plain .= $drained;
181 }
182 else {
183 $plain .= $chunk;
184 }
185  
186 last
187 if Protocol::HAP::HTTP::message_complete( $plain,
188 max_size => MAX_MESSAGE );
189 }
190  
191 return $plain;
192 }
193  
194 # $self->request($method, $path, $body?, $headers?):
195 # Send one HTTP request over the session. After pair-verify
196 # completes, the session uses the encrypted framing. Return a
197 # hash ref with status, headers and body. Return undef on a
198 # transport error.
199 sub request ( $self, $method, $path, $body = undef, $headers = {} )
200 {
201 my $raw = Protocol::HAP::HTTP::build_request(
202 method => $method,
203 path => $path,
204 body => $body,
205 headers => { Host => "$self->{host}:$self->{port}", %$headers },
206 );
207  
208 # The session encrypts after pair-verify and passes the bytes
209 # through before it
210 $raw = $self->{session}->encrypt($raw);
211  
212 my $response = $self->_round_trip($raw);
213 return unless defined $response && length $response;
214  
215 # Keep the bytes after the first complete message for
216 # next_event. For example, an event can arrive back-to-back
217 # with the response.
218 my $length =
219 Protocol::HAP::HTTP::message_complete( $response,
220 max_size => MAX_MESSAGE );
221 if ($length) {
222 $self->{inbuf} .= substr( $response, $length );
223 $response = substr( $response, 0, $length );
224 }
225  
226 my $parsed = Protocol::HAP::HTTP::parse_response($response);
227 unless ( defined $parsed ) {
228 $self->{last_error} = 'malformed response';
229 return;
230 }
231  
232 return $parsed;
233 }
234  
235 # --- pairing ------------------------------------------------------------
236  
237 sub _tlv_request ( $self, $path, %tlv_items )
238 {
239 my $body = Protocol::HAP::TLV::encode(%tlv_items);
240 my $response = $self->request( 'POST', $path, $body,
241 { 'Content-Type' => 'application/pairing+tlv8' } );
242 return unless defined $response;
243  
244 unless ( $response->{status} == 200 ) {
245 $self->{last_error} = "HTTP $response->{status}";
246 return;
247 }
248  
249 my %tlv = Protocol::HAP::TLV::decode( $response->{body} );
250 my $error = $tlv{ Protocol::HAP::Pairing::kTLVType_Error() };
251 if ( defined $error ) {
252 $self->{last_error} = unpack( 'C', $error );
253 return;
254 }
255  
256 return \%tlv;
257 }
258  
259 # $self->pair_setup():
260 # Complete SRP pair-setup M1-M6. On success, store the
261 # accessory LTPK and return true. On a protocol error, return
262 # undef and put the TLV error code in last_error.
263 sub pair_setup ($self)
264 {
265 $self->{last_error} = undef;
266  
267 # M1 -> M2
268 my $m2 = $self->_tlv_request(
269 '/pair-setup',
270 Protocol::HAP::Pairing::kTLVType_State() => pack( 'C', 1 ),
271 Protocol::HAP::Pairing::kTLVType_Method() => pack( 'C', 0 ),
272 ) or return;
273  
274 my $salt = $m2->{ Protocol::HAP::Pairing::kTLVType_Salt() };
275 my $B = $m2->{ Protocol::HAP::Pairing::kTLVType_PublicKey() };
276 unless ( defined $salt && defined $B ) {
277 $self->{last_error} = 'M2 missing salt or public key';
278 return;
279 }
280  
281 # M3 -> M4
282 my $srp = Protocol::HAP::SRP::Client->new( password => $self->{pin} );
283 my $A = $srp->compute_public;
284 my $M1 = $srp->compute_proof( $salt, $B );
285 unless ( defined $M1 ) {
286 $self->{last_error} = 'bogus server public key';
287 return;
288 }
289  
290 my $m4 = $self->_tlv_request(
291 '/pair-setup',
292 Protocol::HAP::Pairing::kTLVType_State() => pack( 'C', 3 ),
293 Protocol::HAP::Pairing::kTLVType_PublicKey() => $A,
294 Protocol::HAP::Pairing::kTLVType_Proof() => $M1,
295 ) or return;
296  
297 my $M2 = $m4->{ Protocol::HAP::Pairing::kTLVType_Proof() };
298 unless ( $srp->verify_server_proof($M2) ) {
299 $self->{last_error} = 'server proof verification failed';
300 return;
301 }
302  
303 # M5 -> M6
304 my $K = $srp->session_key;
305 my $encrypt_key = Protocol::HAP::Crypto->hkdf_sha512( $K,
306 'Pair-Setup-Encrypt-Salt', 'Pair-Setup-Encrypt-Info', 32 );
307  
308 my $ios_x = Protocol::HAP::Crypto->hkdf_sha512(
309 $K,
310 'Pair-Setup-Controller-Sign-Salt',
311 'Pair-Setup-Controller-Sign-Info', 32
312 );
313 my $signature = Protocol::HAP::Crypto->ed25519_sign(
314 $ios_x . $self->{controller_id} . $self->{ltpk},
315 $self->{ltsk}, $self->{ltpk} );
316  
317 my $inner = Protocol::HAP::TLV::encode(
318 Protocol::HAP::Pairing::kTLVType_Identifier() =>
319 $self->{controller_id},
320 Protocol::HAP::Pairing::kTLVType_PublicKey() => $self->{ltpk},
321 Protocol::HAP::Pairing::kTLVType_Signature() => $signature,
322 );
323 my ( $encrypted, $tag ) =
324 Protocol::HAP::Crypto->chacha20poly1305_encrypt( $encrypt_key,
325 pack('x[4]') . 'PS-Msg05', $inner );
326  
327 my $m6 = $self->_tlv_request(
328 '/pair-setup',
329 Protocol::HAP::Pairing::kTLVType_State() => pack( 'C', 5 ),
330 Protocol::HAP::Pairing::kTLVType_EncryptedData() => $encrypted
331 . $tag,
332 ) or return;
333  
334 my $m6_data = $m6->{ Protocol::HAP::Pairing::kTLVType_EncryptedData() };
335 unless ( defined $m6_data && length($m6_data) > 16 ) {
336 $self->{last_error} = 'M6 missing encrypted data';
337 return;
338 }
339 my $m6_tag = substr( $m6_data, -16, 16, '' );
340 my $m6_plain =
341 Protocol::HAP::Crypto->chacha20poly1305_decrypt( $encrypt_key,
342 pack('x[4]') . 'PS-Msg06',
343 $m6_data, $m6_tag );
344 unless ( defined $m6_plain ) {
345 $self->{last_error} = 'M6 decryption failed';
346 return;
347 }
348  
349 my %m6_inner = Protocol::HAP::TLV::decode($m6_plain);
350 my $acc_id = $m6_inner{ Protocol::HAP::Pairing::kTLVType_Identifier() };
351 my $acc_ltpk =
352 $m6_inner{ Protocol::HAP::Pairing::kTLVType_PublicKey() };
353 my $acc_sig = $m6_inner{ Protocol::HAP::Pairing::kTLVType_Signature() };
354  
355 my $acc_x = Protocol::HAP::Crypto->hkdf_sha512(
356 $K,
357 'Pair-Setup-Accessory-Sign-Salt',
358 'Pair-Setup-Accessory-Sign-Info', 32
359 );
360 unless (
361 Protocol::HAP::Crypto->ed25519_verify(
362 $acc_sig, $acc_x . $acc_id . $acc_ltpk, $acc_ltpk
363 ) )
364 {
365 $self->{last_error} = 'accessory signature invalid';
366 return;
367 }
368  
369 $self->{accessory_ltpk} = $acc_ltpk;
370 $self->{accessory_id} = $acc_id;
371  
372 return 1;
373 }
374  
375 # $self->pair_verify():
376 # Complete pair-verify M1-M4 and switch the connection to the
377 # encrypted session framing. This requires a completed
378 # pair_setup, or an accessory_ltpk from the caller.
379 sub pair_verify ($self)
380 {
381 $self->{last_error} = undef;
382  
383 my ( $secret, $public ) = Protocol::HAP::Crypto->x25519_keypair;
384  
385 # M1 -> M2
386 my $m2 = $self->_tlv_request(
387 '/pair-verify',
388 Protocol::HAP::Pairing::kTLVType_State() => pack( 'C', 1 ),
389 Protocol::HAP::Pairing::kTLVType_PublicKey() => $public,
390 ) or return;
391  
392 my $acc_public = $m2->{ Protocol::HAP::Pairing::kTLVType_PublicKey() };
393 my $m2_data = $m2->{ Protocol::HAP::Pairing::kTLVType_EncryptedData() };
394 unless ( defined $acc_public && defined $m2_data ) {
395 $self->{last_error} = 'M2 missing public key or data';
396 return;
397 }
398  
399 my $shared =
400 Protocol::HAP::Crypto->x25519_shared_secret( $secret, $acc_public );
401 my $pv_key = Protocol::HAP::Crypto->hkdf_sha512( $shared,
402 'Pair-Verify-Encrypt-Salt', 'Pair-Verify-Encrypt-Info', 32 );
403  
404 my $m2_tag = substr( $m2_data, -16, 16, '' );
405 my $m2_plain =
406 Protocol::HAP::Crypto->chacha20poly1305_decrypt( $pv_key,
407 pack('x[4]') . 'PV-Msg02',
408 $m2_data, $m2_tag );
409 unless ( defined $m2_plain ) {
410 $self->{last_error} = 'M2 decryption failed';
411 return;
412 }
413  
414 my %m2_inner = Protocol::HAP::TLV::decode($m2_plain);
415 my $acc_id = $m2_inner{ Protocol::HAP::Pairing::kTLVType_Identifier() };
416 my $acc_sig = $m2_inner{ Protocol::HAP::Pairing::kTLVType_Signature() };
417  
418 # Verify the accessory signature when the controller knows
419 # the accessory LTPK
420 if ( defined $self->{accessory_ltpk} ) {
421 unless (
422 Protocol::HAP::Crypto->ed25519_verify(
423 $acc_sig,
424 $acc_public . $acc_id . $public,
425 $self->{accessory_ltpk} ) )
426 {
427 $self->{last_error} = 'accessory signature invalid';
428 return;
429 }
430 }
431  
432 # M3 -> M4
433 my $signature = Protocol::HAP::Crypto->ed25519_sign(
434 $public . $self->{controller_id} . $acc_public,
435 $self->{ltsk}, $self->{ltpk} );
436 my $inner = Protocol::HAP::TLV::encode(
437 Protocol::HAP::Pairing::kTLVType_Identifier() =>
438 $self->{controller_id},
439 Protocol::HAP::Pairing::kTLVType_Signature() => $signature,
440 );
441 my ( $encrypted, $tag ) =
442 Protocol::HAP::Crypto->chacha20poly1305_encrypt( $pv_key,
443 pack('x[4]') . 'PV-Msg03', $inner );
444  
445 $self->_tlv_request(
446 '/pair-verify',
447 Protocol::HAP::Pairing::kTLVType_State() => pack( 'C', 3 ),
448 Protocol::HAP::Pairing::kTLVType_EncryptedData() => $encrypted
449 . $tag,
450 ) or return;
451  
452 # Session keys: the controller writes with the Write key and
453 # reads with the Read key (HAP-Encryption.md §1). The roles
454 # are the accessory's, swapped.
455 $self->{session}->set_encryption(
456 Protocol::HAP::Crypto->hkdf_sha512(
457 $shared, 'Control-Salt',
458 'Control-Write-Encryption-Key', 32
459 ),
460 Protocol::HAP::Crypto->hkdf_sha512(
461 $shared, 'Control-Salt',
462 'Control-Read-Encryption-Key', 32
463 ) );
464  
465 return 1;
466 }
467  
468 # --- pairings management (HAP-Pairing.md §7) ----------------------------
469  
470 sub add_pairing ( $self, $identifier, $ltpk, $permissions = 0 )
471 {
472 $self->{last_error} = undef;
473  
474 $self->_tlv_request(
475 '/pairings',
476 Protocol::HAP::Pairing::kTLVType_State() => pack( 'C', 1 ),
477 Protocol::HAP::Pairing::kTLVType_Method() => pack( 'C', 3 ),
478 Protocol::HAP::Pairing::kTLVType_Identifier() => $identifier,
479 Protocol::HAP::Pairing::kTLVType_PublicKey() => $ltpk,
480 Protocol::HAP::Pairing::kTLVType_Permissions() =>
481 pack( 'C', $permissions ),
482 ) or return;
483  
484 return 1;
485 }
486  
487 sub remove_pairing ( $self, $identifier = undef )
488 {
489 $self->{last_error} = undef;
490 $identifier //= $self->{controller_id};
491  
492 $self->_tlv_request(
493 '/pairings',
494 Protocol::HAP::Pairing::kTLVType_State() => pack( 'C', 1 ),
495 Protocol::HAP::Pairing::kTLVType_Method() => pack( 'C', 4 ),
496 Protocol::HAP::Pairing::kTLVType_Identifier() => $identifier,
497 ) or return;
498  
499 return 1;
500 }
501  
502 sub list_pairings ($self)
503 {
504 $self->{last_error} = undef;
505  
506 my $body = Protocol::HAP::TLV::encode(
507 Protocol::HAP::Pairing::kTLVType_State() => pack( 'C', 1 ),
508 Protocol::HAP::Pairing::kTLVType_Method() => pack( 'C', 5 ),
509 );
510 my $response = $self->request( 'POST', '/pairings', $body,
511 { 'Content-Type' => 'application/pairing+tlv8' } );
512 return unless defined $response;
513  
514 unless ( $response->{status} == 200 ) {
515 $self->{last_error} = "HTTP $response->{status}";
516 return;
517 }
518  
519 # An error TLV means the request failed. Extract it before
520 # the separator split, over the whole body, once.
521 my %whole = Protocol::HAP::TLV::decode( $response->{body} );
522 my $error = $whole{ Protocol::HAP::Pairing::kTLVType_Error() };
523 if ( defined $error ) {
524 $self->{last_error} = unpack( 'C', $error );
525 return;
526 }
527  
528 # Split the entries on the zero-length separator. Without
529 # the split, TLV::decode concatenates the repeated
530 # Identifier/PublicKey types.
531 my @pairings;
532 for my $entry ( split /\xFF\x00/, $response->{body} ) {
533 my %tlv = Protocol::HAP::TLV::decode($entry);
534 my $id = $tlv{ Protocol::HAP::Pairing::kTLVType_Identifier() };
535 next unless defined $id;
536  
537 push @pairings,
538 {
539 identifier => $id,
540 ltpk => $tlv{
541 Protocol::HAP::Pairing::kTLVType_PublicKey()
542 },
543 permissions => unpack(
544 'C',
545 $tlv{
546 Protocol::HAP::Pairing::kTLVType_Permissions(
547 )
548 } // "\x00"
549 ),
550 };
551 }
552  
553 return \@pairings;
554 }
555  
556 # --- events -------------------------------------------------------------
557  
558 # $self->next_event($timeout?):
559 # Wait for an EVENT/1.0 message on the socket, then decrypt
560 # and parse it. Return { status, headers, body }, or undef on
561 # timeout. Without an explicit $timeout, the session timeout
562 # bounds the wait. That timeout honors OPENHAP_TEST_TIMEOUT.
563 # Pass a literal only for short negative probes. This requires
564 # a socket connection, not an injected transport.
565 sub next_event ( $self, $timeout = undef )
566 {
567 return unless $self->{socket};
568  
569 $timeout //= $self->{timeout};
570  
571 my $select = IO::Select->new( $self->{socket} );
572 my $end = time + $timeout;
573  
574 while (1) {
575  
576 # The buffer can already hold a complete event
577 if ( $self->{inbuf} =~ s{\A(EVENT/1\.0.*?\r\n\r\n)}{}s ) {
578 my $head = $1;
579 my ($length) = $head =~ /Content-Length:\s*(\d+)/i;
580 $length //= 0;
581 my $body = substr( $self->{inbuf}, 0, $length, '' );
582  
583 my %headers;
584 for my $line ( split /\r\n/, $head ) {
585 $headers{ lc $1 } = $2
586 if $line =~ /^([^:]+):\s*(.*)$/;
587 }
588 my ($status) = $head =~ m{^EVENT/1\.0\s+(\d+)};
589  
590 return {
591 status => $status,
592 headers => \%headers,
593 body => $body,
594 };
595 }
596  
597 my $remaining = $end - time;
598 return if $remaining <= 0;
599 next unless $select->can_read($remaining);
600  
601 my $bytes = $self->{socket}->sysread( my $chunk, 65535 );
602 return unless $bytes;
603  
604 unless ( $self->is_encrypted ) {
605 $self->{inbuf} .= $chunk;
606 next;
607 }
608  
609 # A frame can arrive split across reads. Accumulate the
610 # raw bytes and decrypt only complete frames. Keep a
611 # partial tail buffered. Then the nonce counter stays in
612 # sync with the accessory.
613 $self->{rawbuf} .= $chunk;
614 my $plain = $self->_drain_frames;
615 return unless defined $plain;
616 $self->{inbuf} .= $plain;
617 }
618 }
619  
620 # $self->_drain_frames():
621 # Decrypt and consume every complete frame at the front of the
622 # raw receive buffer, one frame at a time through the session,
623 # which advances its counter per consumed frame. A trailing
624 # partial frame stays buffered for the next read. Return the
625 # decrypted plaintext, which can be empty. Return undef on an
626 # authentication failure.
627 sub _drain_frames ($self)
628 {
629 my $out = '';
630 while ( length( $self->{rawbuf} ) >= 2 ) {
631 my $length = unpack( 'v', substr( $self->{rawbuf}, 0, 2 ) );
632 return if $length > MAX_FRAME;
633 last if length( $self->{rawbuf} ) < 2 + $length + 16;
634  
635 my $frame = substr( $self->{rawbuf}, 0, 2 + $length + 16, '' );
636 my $plain = $self->{session}->decrypt($frame);
637 return unless defined $plain;
638 $out .= $plain;
639 }
640 return $out;
641 }
642  
643 1;