-
Notifications
You must be signed in to change notification settings - Fork 134
/
ap2-receiver.py
1484 lines (1321 loc) · 57.9 KB
/
ap2-receiver.py
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import socket
import argparse
import multiprocessing
import random
import tempfile # noqa
from threading import current_thread
import pprint
import http.server
import socketserver
import asyncio
import netifaces as ni
from hexdump import hexdump
from zeroconf import IPVersion, ServiceInfo, Zeroconf, NonUniqueNameException
from biplist import readPlistFromString, writePlistToString
from biplist import InvalidPlistException
from ap2.playfair import PlayFair, FairPlayAES
from ap2.airplay1 import AP1Security
from ap2.utils import get_volume, set_volume, set_volume_pid, get_screen_logger
from ap2.pairing.hap import Hap, HAPSocket, LTPK, DeviceProperties
from ap2.connections.event import EventGeneric
from ap2.connections.stream import Stream
from ap2.connections.session_properties import Session
from ap2.dxxp import parse_dxxp
from ap2.bitflags import FeatureFlags, StatusFlags
from ap2.sdphandler import SDPHandler
FEATURES = FeatureFlags.GetDefaultAirplayTwoFlags(FeatureFlags)
STATUS_FLAGS = StatusFlags.GetDefaultStatusFlags(StatusFlags)
# PI = Public ID (can be GUID, MAC, some string).
# Note: BINARY. HAP classes expect binary format. Must be in text in device_info.
PI = b'aa5cb8df-7f14-4249-901a-5e748ce57a93'
STREAM_ID = 0
DEBUG = False
# The device MAC - string form.
DEVICE_ID = None
# HAP object to hold device properties like name, ACL, password etc.
DEV_PROPS = None
# The chosen interface's IPv4/6
IPV4 = None
IPV6 = None
IPADDR = None
# Globally assign the device name provided from the command line
DEV_NAME = None
# Object to hold our mDNS broadcaster
MDNS_OBJ = None
# HomeKit AccessControl level to persist settings we get from HomeKit
# 0=Everyone, 1=(HomeKit Users), 2=Admin
HK_ACL_LEVEL = 0
# HomeKit assigned password (numeric PIN) to access
HK_PW = None
"""
# SERVER_VERSION; presence/absence, and value dictates client behaviours
Set above 360 to trigger remote control
Set to <= 355 to trigger REALTIME and NTP (as opposed to buffered streams)
Set to >= 355 to trigger PTP and buffered.
Set to <= 350 to prevent shk in streams.
Set to 300 to trigger ??
Set to 200 to trigger ANNOUNCE (APv1)
"""
SERVER_VERSION = "366.0"
HTTP_CT_BPLIST = "application/x-apple-binary-plist"
HTTP_CT_OCTET = "application/octet-stream"
HTTP_CT_PARAM = "text/parameters"
HTTP_CT_IMAGE_JPEG = "image/jpeg"
HTTP_CT_IMAGE = "image/"
HTTP_CT_DMAP = "application/x-dmap-tagged"
HTTP_CT_PAIR = "application/pairing+tlv8"
"""
X-Apple-HKP:
Values 0,2,3,4,6 seen.
0 = Unauth. When Ft48TransientPairing and Ft43SystemPairing are absent
2 = (pair-setup complete, pair-verify starts)
3 = SystemPairing (with Ft43SystemPairing)
4 = Transient
6 = HomeKit
7 = HomeKit (administration)
"""
HTTP_X_A_HKP = "X-Apple-HKP"
HTTP_X_A_CN = "X-Apple-Client-Name"
HTTP_X_A_PD = "X-Apple-PD"
# HTTP_X_A_AT: Unix timestamp for current system date/time.
HTTP_X_A_AT = "X-Apple-AbsoluteTime"
# Encryption Type
HTTP_X_A_ET = "X-Apple-ET"
#
AIRPLAY_BUFFER = 8388608 # 0x800000 i.e. 1024 * 8192 - how many CODEC frame size 1024 we can hold
def increase_stream_id():
global STREAM_ID
STREAM_ID += 1
# ID shall not exceed 32 bits.
STREAM_ID &= 0xFFFFFFFF
return STREAM_ID
def get_hex_bitmask(in_features):
"""
prepares the feature bits into text form
"""
if in_features.bit_length() <= 32:
# print(f"{hex(in_features)}")
return f"{hex(in_features)}"
else:
# print(f'feature bit length: {in_features.bit_length()} ')
# print(f"{hex(in_features & 0xffffffff)},{hex(in_features >> 32 & 0xffffffff)}")
return f"{hex(in_features & 0xffffffff)},{hex(in_features >> 32 & 0xffffffff)}"
def update_status_flags(flag=None, on=False, push=True):
global MDNS_OBJ
""" Use this to check for and send out updated status flags
if flag is None, skip changing the flags (e.g. updates already queued)
if on is true, add the flag in, otherwise remove it.
if push is False, skip the update (e.g. you want to queue multiple changes)
"""
if flag:
global STATUS_FLAGS
# If the flag is not present in STATUS_FLAGS, add it in, if on is True
if not STATUS_FLAGS & flag and on:
STATUS_FLAGS ^= flag
elif STATUS_FLAGS & flag and not on:
STATUS_FLAGS ^= flag
# update the global info structures
setup_global_structs(args, isDebug=DEBUG)
# If push is false, we skip pushing out the update.
if push:
if IPV6 is not None:
MDNS_OBJ = register_mdns(DEVICE_ID, DEV_NAME, [IP4ADDR_BIN, IP6ADDR_BIN])
else:
MDNS_OBJ = register_mdns(DEVICE_ID, DEV_NAME, [IP4ADDR_BIN])
def setup_global_structs(args, isDebug=False):
global device_info
global device_setup
global stream_setup_data
global second_stage_info
global mdns_props
global LTPK_OBJ
global DEV_NAME
LTPK_OBJ = LTPK(PI, isDebug)
device_info = {
# 'OSInfo': 'Linux 3.10.53',
# 'PTPInfo': 'OpenAVNU ArtAndLogic-aPTP-changes a5d7f94-0.0.1',
'audioLatencies': [
{
# audioType can be: e.g. NULL/nothing (iTunes), default, media, telephony, speechRecognition, alert
# (AP1?) GeneralAudio(96), MainAudio(100), AltAudio(101), Screen(110).
# Absence triggers default.
# 'audioType': 'default',
'inputLatencyMicros': 0,
'outputLatencyMicros': 400000,
# Type can be any RTP type, 96, 100, 103, 110 etc.
# 'type': 96
},
],
# 'build': '16.0',
'deviceID': DEVICE_ID,
# features: can send in hex() also
'features': int(FEATURES),
# 'features': 496155769145856, # Sonos One
# 'firmwareBuildDate': 'Nov 5 2019',
# 'firmwareRevision': '53.3-71050',
# 'hardwareRevision': '1.21.1.8-2',
# 'initialVolume': -144.0,
'keepAliveLowPower': True,
'keepAliveSendStatsAsBody': True,
'manufacturer': 'OpenAirplay',
'model': 'Receiver',
'name': DEV_NAME,
'nameIsFactoryDefault': False,
'pi': PI.decode(), # UUID generated casually..
# 'psi': PI.decode(), # ?
'protocolVersion': '1.1',
'sdk': 'AirPlay;2.0.2',
'sourceVersion': SERVER_VERSION,
'statusFlags': get_hex_bitmask(STATUS_FLAGS),
# 'supportedFormats': {
# 'lowLatencyAudioStream': 0,
# # 'screenStream': 21235712,
# 'audioStream': 21235712,
# 'bufferStream': 14680064,
# },
# 'statusFlags': 0x404 # Sonos One
# 'volumeControlType': 4, # 1-4 all seem to behave the same.
# 'vv': 2,
}
if DISABLE_VM:
volume = 0
else:
volume = get_volume()
second_stage_info = {
"initialVolume": volume,
}
device_setup = {
'eventPort': 0 # AP2 receiver event server
}
if not DISABLE_PTP_MASTER:
if IPV6 and not IPV4:
addr = [
IPV6
]
else:
# Prefer (only) IPV4
addr = [
IPV4
]
device_setup['timingPort'] = 0 # Seems like legacy, non PTP setting
device_setup['timingPeerInfo'] = {
'Addresses': addr,
'ID': DEVICE_ID
}
stream_setup_data = {
'streams': [
]
}
mdns_props = {
# Airplay flags
# Access ControL. 0,1,2 == anon,users,admin(?)
"acl": HK_ACL_LEVEL,
"deviceid": DEVICE_ID, # device MAC addr
# Features, aka ft - see Feat class.
"features": get_hex_bitmask(FEATURES),
# flags (bitmask)
"flags": get_hex_bitmask(STATUS_FLAGS),
# Group Contains Group Leader.
"gcgl": "0",
# Group UUID (generated casually)
"gid": "5dccfd20-b166-49cc-a593-6abd5f724ddb",
# isGroupLeader: See gcgl
# "isGroupLeader": "0",
"manufacturer": "OpenAirplay",
"model": "Airplay2-Receiver",
"name": DEV_NAME,
"protovers": "1.1",
# Required Sender Features (bitmask)
"rsf": "0x0",
"serialNumber": DEVICE_ID,
# Source Version (airplay SDK?): absence triggers AP1 ANNOUNCE behaviour.
"srcvers": SERVER_VERSION,
# RAOP Flags - ("xx") - mostly used with RAOP
# These are found under the <deviceid>@<name> mDNS record.
# Apple Model (name)
# "am": "One",
# (amount of audio) CHannels
"ch": "2",
# CompressioN. 0,1,2,3 == (None aka) PCM, ALAC, AAC, AAC_ELD
"cn": "0,1,2",
# Digest Auth RFC-2617 support
# "da": "true",
# Encryption Key
# "ek": "1",
# Encryption Types. 0,1,3,4,5 == None, RSA, FairPlay, Mfi, FairPlay SAPv2.5
# "et": "0,1,3",
# "et": "0,1,3,4,5",
# Firmware version. p20 == AirPlay Src revision?
# "fv": "p20.78000.12",
# MetaData(?) 0,1,2 == Text, Gfx, Progress (only needed for pre iOS7 senders)
# "md": "0,1,2",
# Pairing UUID (generated casually)
"pi": PI.decode(),
# Ed25519 PubKey
"pk": LTPK_OBJ.get_pub_string(),
# "protovers": "1.1",
# PassWord enabled: 0/false off, 1/true on.
# -This requires Method POST Path /pair-pin-start endpoint
# "pw": "false",
# Status Flags (bitmask): see StatusFlags class.
"sf": get_hex_bitmask(STATUS_FLAGS),
# Software Mute (whether needed)
# "sm": "false",
# Sample Rate
# "sr": "44100",
# Sample Size
# "ss": "16",
# Software Volume (whether needed)
# "sv": "false",
# TransPort for media. CSV of capables transports for audio
# "tp": "TCP,UDP",
# (Airplay) version number (supported) 16bit.16bit, 65537 == 1.1
# "vn": "65537",
# Source version
# "vs": "366",
}
class AP2Handler(http.server.BaseHTTPRequestHandler):
aeskeyobj = None
pp = pprint.PrettyPrinter()
timing_port, ptp_port = 0, 0
timing_proc, ptp_proc = None, None
fairplay_keymsg = None
ecdh_shared_key = None
session = None
hap = None
# Maps paths to methods a la HAP-python
HANDLERS = {
"POST": {
"/command": "handle_command",
"/feedback": "handle_feedback",
"/audioMode": "handle_audiomode",
"/auth-setup": "handle_auth_setup",
"/fp-setup": "handle_fp_setup",
"/fp-setup2": "handle_auth_setup",
"/pair-pin-start": "handle_pair_pin_start",
"/pair-setup": "handle_pair_setup",
"/pair-verify": "handle_pair_verify",
"/pair-add": "handle_pair_add",
"/pair-remove": "handle_pair_remove",
"/pair-list": "handle_pair_list",
"/configure": "handle_configure",
},
"GET": {
"/info": "handle_info",
},
"PUT": {"/xyz": "handle_xyz"},
}
""" This is needed now to prep logging in case we get a sneak attack from
AP1 senders that don't go via dispatch """
def __init__(self, socket, client_address, server):
""" thread local logging """
server_address = socket.getsockname()
pair_string = f'{self.__class__.__name__}: {server_address[0]}:{server_address[1]}<=>{client_address[0]}:{client_address[1]}'
pair_string += f'; {current_thread().name}'
level = 'DEBUG' if DEBUG else 'INFO'
self.logger = get_screen_logger(pair_string, level=level)
http.server.BaseHTTPRequestHandler.__init__(self, socket, client_address, server)
return
def dispatch(self):
"""Dispatch the request to the appropriate handler method."""
path = self.path
paramStr = ''
if '?' in self.path:
path = self.path.split('?')[0]
paramStr = self.path.split('?')[1]
self.logger.debug(f'{self.command}: {path}')
self.logger.debug(f'!Dropped parameters: {paramStr}') if paramStr else self.logger.debug('')
self.logger.debug(self.headers)
try:
# pass additional paramArray:
# getattr(self, self.HANDLERS[self.command][path])(paramArray)
# Note: handle_* signatures need e.g. (self, *args, **kwargs)
getattr(self, self.HANDLERS[self.command][path])()
except KeyError:
self.send_error(
404,
f": Method {self.command} Path {path} endpoint not implemented"
)
self.hap = None
def parse_request(self):
self.raw_requestline = self.raw_requestline.replace(b"RTSP/1.0", b"HTTP/1.1")
r = http.server.BaseHTTPRequestHandler.parse_request(self)
self.protocol_version = "RTSP/1.0"
self.close_connection = 0
return r
def process_info(self, device_name):
self.logger.info('Process info called')
device_info["name"] = "TODO"
def send_response(self, code, message=None):
if message is None:
if code in self.responses:
message = self.responses[code][0]
else:
message = b''
response = f"{self.protocol_version} {code} {message}\r\n"
self.wfile.write(response.encode())
def version_string(self):
return f"AirTunes/{SERVER_VERSION}"
def do_GET(self):
self.dispatch()
def do_OPTIONS(self):
self.logger.debug(self.headers)
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
if "Apple-Challenge" in self.headers:
# Build Apple-Reponse
apple_response = AP1Security.compute_apple_response(self.headers["Apple-Challenge"], IPADDR_BIN, DEVICE_ID_BIN)
self.send_header("Apple-Jack-Status", "connected; type=analog")
self.send_header("Apple-Response", apple_response)
self.send_header("Public",
"ANNOUNCE, SETUP, RECORD, PAUSE, FLUSH"
"FLUSHBUFFERED, TEARDOWN, OPTIONS, POST, GET, PUT"
"SETPEERSX"
"SETMAGICCOOKIE"
)
self.end_headers()
def do_ANNOUNCE(self):
# Enable Feature bit 12: Ft12FPSAPv2p5_AES_GCM: this uses only RSA
# Enabling Feat bit 25 and iTunes4win attempts AES - cannot yet decrypt.
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
if self.headers["Content-Type"] == 'application/sdp':
content_len = int(self.headers["Content-Length"])
if content_len > 0:
sdp_body = self.rfile.read(content_len).decode('utf-8')
self.logger.debug(sdp_body)
sdp = SDPHandler(sdp_body)
self.aud_params = sdp.params
if sdp.has_mfi:
self.logger.warning("MFi not possible on this hardware.")
self.send_response(404)
self.hap = None
else:
if(sdp.audio_format is SDPHandler.SDPAudioFormat.ALAC
and int((FEATURES & FeatureFlags.getFeature19ALAC(FeatureFlags))) == 0):
self.logger.warning("This receiver not configured for ALAC (set flag 19).")
self.send_response(404)
self.hap = None
elif (sdp.audio_format is SDPHandler.SDPAudioFormat.AAC
and int((FEATURES & FeatureFlags.getFeature20AAC(FeatureFlags))) == 0):
self.logger.warning("This receiver not configured for AAC (set flag 20).")
self.send_response(404)
self.hap = None
elif (sdp.audio_format is SDPHandler.SDPAudioFormat.AAC_ELD
and int((FEATURES & FeatureFlags.getFeature20AAC(FeatureFlags))) == 0):
self.logger.warning("This receiver not configured for AAC (set flag 20/21).")
self.send_response(404)
self.hap = None
else:
if sdp.has_fp and self.fairplay_keymsg:
self.logger.debug('Got FP AES Key from SDP')
self.aeskeyobj = FairPlayAES(fpaeskeyb64=sdp.aeskey, aesivb64=sdp.aesiv, keymsg=self.fairplay_keymsg)
elif sdp.has_rsa:
self.aeskeyobj = FairPlayAES(rsaaeskeyb64=sdp.aeskey, aesivb64=sdp.aesiv)
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
self.sdp = sdp
def do_FLUSHBUFFERED(self):
self.logger.info(f'{self.command}: {self.path}')
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
if self.headers["Content-Type"] == HTTP_CT_BPLIST:
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
fr = 0
if "flushFromSeq" in plist:
fr = plist["flushFromSeq"]
if "flushUntilSeq" in plist:
to = plist["flushUntilSeq"]
try:
for s in self.server.streams:
if s.isAudio() and s.isInitialized():
s.getAudioConnection().send(f"flush_from_until_seq-{fr}-{to}")
except OSError as e:
self.logger.error(f'FLUSHBUFFERED error: {repr(e)}')
self.logger.debug(self.pp.pformat(plist))
def do_POST(self):
self.dispatch()
def do_SETUP(self):
dacp_id = self.headers.get("DACP-ID")
active_remote = self.headers.get("Active-Remote")
ua = self.headers.get("User-Agent")
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
# Found in SETUP after ANNOUNCE:
if self.headers["Transport"]:
# self.logger.debug(self.headers["Transport"])
""" Run receiver with bit 13/14 and no bit 25, it's RSA in ANNOUNCE. Sender assumes you are an
airport with only 250msec buffer, so min/max are absent from SDP. FP2 is a solution. """
""" ct: 0x1 = PCM, 0x2 = ALAC, 0x4 = AAC_LC, 0x8 = AAC_ELD. largely implied by audioFormat """
# Set up a stream to receive.
stream = {
'audioFormat': self.sdp.AirplayAudFmt,
'latencyMin': int(self.sdp.audio_format_sr) // 4 if not self.sdp.minlatency else int(self.sdp.minlatency),
'latencyMax': int(self.sdp.audio_format_sr) * 2 if not self.sdp.maxlatency else int(self.sdp.maxlatency),
'ct': 0, # Compression Type(?)
'shk': self.aeskeyobj.aeskey,
'shiv': self.aeskeyobj.aesiv,
'spf': int(self.sdp.spf), # sample frames per pkt
'type': int(self.sdp.payload_type),
'controlPort': 0,
}
streamobj = Stream(
stream,
IPADDR,
buff_size=AIRPLAY_BUFFER,
stream_id=increase_stream_id(),
shared_key=self.ecdh_shared_key,
isDebug=DEBUG,
aud_params=self.aud_params
)
self.server.streams.append(streamobj)
if not self.server.event_proc:
self.server.event_port, self.server.event_proc = EventGeneric.spawn(
self.server.server_address, name='events', shared_key=self.ecdh_shared_key, isDebug=DEBUG)
if not self.server.timing_proc:
self.server.timing_port, self.server.timing_proc = EventGeneric.spawn(
self.server.server_address, name='ntp', shared_key=self.ecdh_shared_key, isDebug=DEBUG)
transport = self.headers["Transport"].split(';')
res = []
res.append("RTP/AVP/UDP")
res.append("unicast")
res.append("mode=record")
ctl_msg = f"control_port={streamobj.getControlPort()}"
res.append(ctl_msg)
self.logger.debug(ctl_msg)
data_msg = f"server_port={streamobj.getDataPort()}"
res.append(data_msg)
self.logger.debug(data_msg)
ntp_msg = f"timing_port={self.server.timing_port}"
res.append(ntp_msg)
self.logger.debug(ntp_msg)
string = ';'
self.send_response(200)
self.send_header("Transport", string.join(res))
self.send_header("Session", "1")
self.send_header("Audio-Jack-Status", 'connected; type=analog')
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
self.logger.info('')
# Send flag that we're active
update_status_flags(StatusFlags.getRecvSessActive(StatusFlags), on=True)
return
if self.headers["Content-Type"] == HTTP_CT_BPLIST:
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
self.logger.debug(self.pp.pformat(plist))
if not self.session:
""" Only set up session first time at connection """
self.session = Session(plist, self.fairplay_keymsg)
if "streams" not in plist:
self.logger.debug("Sending EVENT:")
self.server.event_port, self.server.event_proc = EventGeneric.spawn(
self.server.server_address, name='events', shared_key=self.ecdh_shared_key, isDebug=DEBUG)
device_setup["eventPort"] = self.server.event_port
self.logger.debug(f"[+] eventPort={self.server.event_port}")
self.logger.debug(self.pp.pformat(device_setup))
res = writePlistToString(device_setup)
self.send_response(200)
self.send_header("Content-Length", len(res))
self.send_header("Content-Type", HTTP_CT_BPLIST)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
self.wfile.write(res)
self.logger.info('')
else:
for stream in plist["streams"]:
s = Stream(
stream,
IPADDR,
buff_size=AIRPLAY_BUFFER,
stream_id=increase_stream_id(),
shared_key=self.ecdh_shared_key,
isDebug=DEBUG,
)
self.logger.debug("Building stream channels:")
self.server.streams.append(s)
stream_setup_data["streams"].append(
s.descriptor
)
self.logger.debug(s.getSummaryMessage())
if s.getStreamType() == Stream.BUFFERED:
set_volume_pid(s.getControlProc().pid)
if s.getStreamType() == Stream.REALTIME:
set_volume_pid(s.getControlProc().pid)
self.logger.debug(self.pp.pformat(stream_setup_data))
res = writePlistToString(stream_setup_data)
self.send_response(200)
self.send_header("Content-Length", len(res))
self.send_header("Content-Type", HTTP_CT_BPLIST)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
self.wfile.write(res)
self.logger.info('')
# Send flag that we're active
update_status_flags(StatusFlags.getRecvSessActive(StatusFlags), on=True)
return
self.send_error(404)
self.logger.info('')
def do_GET_PARAMETER(self):
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
params_res = {}
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
params = body.splitlines()
for p in params:
if p == b"volume":
self.logger.info(f"GET_PARAMETER: {p}")
if not DISABLE_VM:
params_res[p] = str(get_volume()).encode()
else:
self.logger.warning("Volume Management is disabled")
else:
self.logger.info(f"Ops GET_PARAMETER: {p}")
if DISABLE_VM:
res = b"volume: 0" + b"\r\n"
else:
res = b"\r\n".join(b"%s: %s" % (k, v) for k, v in params_res.items()) + b"\r\n"
self.send_response(200)
self.send_header("Content-Length", len(res))
self.send_header("Content-Type", HTTP_CT_PARAM)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
self.wfile.write(res)
hexdump(res) if DEBUG else ''
def do_SET_PARAMETER(self):
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
params_res = {}
content_type = self.headers["Content-Type"]
content_len = int(self.headers["Content-Length"])
if content_type == HTTP_CT_PARAM:
if content_len > 0:
body = self.rfile.read(content_len)
params = body.splitlines()
for p in params:
pp = p.split(b":")
if pp[0] == b"volume":
self.logger.info(f"SET_PARAMETER: {pp[0]} => {pp[1]}")
if not DISABLE_VM:
set_volume(float(pp[1]))
else:
self.logger.warning("Volume Management is disabled")
elif pp[0] == b"progress":
# startTimeStamp, currentTimeStamp, stopTimeStamp
try:
for s in self.server.streams:
s.getAudioConnection().send(f"progress-{pp[1].decode('utf8').lstrip(' ')}")
except OSError as e:
self.logger.error(f'SET_PARAMETER error: {repr(e)}')
self.logger.info(f"SET_PARAMETER: {pp[0]} => {pp[1]}")
# else:
# self.logger.info(f"Ops SET_PARAMETER: {p}")
elif content_type.startswith(HTTP_CT_IMAGE):
if content_len > 0:
body = self.rfile.read(content_len)
"""
fname = None
with tempfile.NamedTemporaryFile(prefix="artwork", dir=".", delete=False, suffix=".jpg") as f:
f.write(self.rfile.read(content_len))
fname = f.name
self.logger.info(f"Artwork saved to {fname}")
"""
elif content_type == HTTP_CT_DMAP:
if content_len > 0:
self.logger.info(parse_dxxp(self.rfile.read(content_len)))
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
def do_RECORD(self):
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
if self.headers["Content-Type"] == HTTP_CT_BPLIST:
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
self.logger.info(self.pp.pformat(plist))
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
# TODO: get actual playout latency
self.send_header("Audio-Latency", "0")
self.end_headers()
def do_SETRATEANCHORTIME(self):
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
if self.headers["Content-Type"] == HTTP_CT_BPLIST:
content_len = int(self.headers["Content-Length"])
try:
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
try: # Sending thru a pipe, check for pipe related errors
if plist["rate"] == 1:
for s in self.server.streams:
if s.isAudio() and s.isInitialized():
s.getAudioConnection().send(f"play-{plist['rtpTime']}")
if plist["rate"] == 0:
for s in self.server.streams:
if s.isAudio() and s.isInitialized():
s.getAudioConnection().send("pause")
except OSError:
self.logger.error(f'SETRATEANCHORTIME error: {repr(e)}')
self.logger.info(self.pp.pformat(plist))
except IndexError:
# Fixes some disconnects
self.logger.error('Cannot process request; streams torn down already.')
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
def do_TEARDOWN(self):
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
if self.headers["Content-Type"] == HTTP_CT_BPLIST:
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
if "streams" in plist:
for s in plist["streams"]:
stream_id = s["streamID"]
stream_type = s["type"]
if len(self.server.streams) > 0:
for st in self.server.streams:
if stream_type == st.getStreamType() and stream_id == st.getStreamID():
st.teardown()
# Stream cull: build new list of non culled streams
self.server.streams[:] = [s for s in self.server.streams if not s.isCulled()]
self.logger.info(self.pp.pformat(plist))
if plist == {} and len(self.server.streams) == 0:
self.server.event_proc.terminate()
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
# Send flag that we're no longer active
update_status_flags(StatusFlags.getRecvSessActive(StatusFlags))
def do_SETPEERS(self):
"""
A shorter format to set timing (PTP clock) peers.
Content-Type: /peer-list-changed
Contains [] array of IP{4|6}addrs:
['...::...',
'...::...',
'...']
"""
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
self.logger.info(self.pp.pformat(plist))
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
def do_SETPEERSX(self):
# Extended format for setting timing (PTP clock) peers
# Requires Ft52PeersExtMsg (bit 52)
# Note: this method does not require defining in do_OPTIONS
# Content-Type: /peer-list-changed-x
# Contains [] array of:
# {'Addresses': ['fe80::...',
# '...'],
# 'ClockID': 000000000000000000,
# 'ClockPorts': {GUID1: port,
# GUID2: port,
# GUIDN: port},
# 'DeviceType': 0,
# 'ID': GUID,
# 'SupportsClockPortMatchingOverride': T/F}
# SETPEERSX may require more logic when PTP is finished.
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
self.logger.info(self.pp.pformat(plist))
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
def do_FLUSH(self):
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
if "RTP-Info" in self.headers:
rtp_info = self.headers["RTP-Info"]
seq, rtptime = rtp_info.split(';')
seq = seq.split('=')[1]
rtptime = rtptime.split('=')[1]
try:
for s in self.server.streams:
s.getAudioConnection().send(f"flush_seq_rtptime-{seq}-{rtptime}")
except OSError as e:
self.logger.error(f'FLUSH error: {repr(e)}')
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
def do_SETMAGICCOOKIE(self):
# First appeared in iOS 17 betas ( User-Agent: AirPlay/710.66.3 )
self.logger.info(f'{self.command}: {self.path}')
self.logger.debug(self.headers)
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
self.logger.info(self.pp.pformat(plist))
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
def handle_command(self):
if self.headers["Content-Type"] == HTTP_CT_BPLIST:
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
newin = []
if "mrSupportedCommandsFromSender" in plist["params"]:
for p in plist["params"]["mrSupportedCommandsFromSender"]:
iplist = readPlistFromString(p)
newin.append(iplist)
plist["params"]["mrSupportedCommandsFromSender"] = newin
if "params" in plist["params"] and "kMRMediaRemoteNowPlayingInfoArtworkData" in plist["params"]["params"]:
plist["params"]["params"]["kMRMediaRemoteNowPlayingInfoArtworkData"] = "<redacted ..too long>"
# don't print this massive blob - one day we may use it though.
# self.logger.debug(plist) # self.logger.info(self.pp.pformat(plist))
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
def handle_feedback(self):
self.handle_generic(feedback=True)
def handle_audiomode(self):
self.handle_generic()
def handle_generic(self, feedback=False):
if self.headers["Content-Type"] == HTTP_CT_BPLIST:
content_len = int(self.headers["Content-Length"])
if content_len > 0:
body = self.rfile.read(content_len)
plist = readPlistFromString(body)
self.logger.info(self.pp.pformat(plist))
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
if feedback:
if len(self.server.streams) > 0:
stream_data = {'streams': []}
for s in self.server.streams:
stream_data['streams'].append(s.getDescriptor())
else:
stream_data = {}
# self.logger.debug(stream_data)
res = writePlistToString(stream_data)
self.send_header("Content-Length", len(res))
self.send_header("Content-Type", HTTP_CT_BPLIST)
self.end_headers()
if feedback:
self.wfile.write(res)
def handle_auth_setup(self):
self.handle_X_setup('auth')
def handle_fp_setup(self):
self.handle_X_setup('fp')
def handle_X_setup(self, op: str = ''):
response = b''
content_len = int(self.headers["Content-Length"])
if content_len > 0:
# This is the session fairplay_keymsg (168 bytes long)
self.fairplay_keymsg = body = self.rfile.read(content_len)
if op == 'fp':
pf = PlayFair()
pf_info = PlayFair.fairplay_s()
response = pf.fairplay_setup(pf_info, body)
if op == 'auth':
try:
plist = readPlistFromString(body)
self.logger.info(self.pp.pformat(plist))
except InvalidPlistException as e:
# Use flags: 00088200405f4200 or -ftxor 51
self.logger.error('Unhandled edge-case encrypted setup')
self.send_response(404)
return
if 'X-Apple-AT' in self.headers and self.headers["X-Apple-AT"] == '16':
"""
Use flags: 144037111597568 / 0x830040DF0A00 or -ftxor 23 (RSA)
triggers: {'ascm': 1, 'tkrd': ['pair', 'auth', 'uuid']}
"""
self.logger.error('Unhandled edge-case for unencrypted auth setup')
if response:
self.send_response(200)
self.send_header("Content-Length", len(response))
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
if op == 'fp':
self.wfile.write(response)
else:
self.logger.error('Unhandled edge-case: FairPlay 2 encryption not supported.')
self.send_error(101)
return
def handle_pair_pin_start(self):
""" Should probably set the PIN status flag to 'on' here. """
if not self.hap:
self.hap = Hap(PI, DEBUG)
self.send_response(200)
self.send_header("Server", self.version_string())
self.send_header("CSeq", self.headers["CSeq"])
self.end_headers()
def handle_pair_setup(self):
self.handle_pair_SV('setup')
def handle_pair_verify(self):
self.handle_pair_SV('verify')