forked from abrasive/shairport
-
-
Notifications
You must be signed in to change notification settings - Fork 662
Expand file tree
/
Copy pathrtsp.c
More file actions
4709 lines (4202 loc) · 184 KB
/
Copy pathrtsp.c
File metadata and controls
4709 lines (4202 loc) · 184 KB
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
/*
* RTSP protocol handler. This file is part of Shairport Sync
* Copyright (c) James Laird 2013
* Modifications, including those associated with audio synchronization, multithreading and
* metadata handling copyright (c) Mike Brady 2014--2026
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <inttypes.h>
#include <limits.h>
#include <memory.h>
#include <net/if.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include "activity_monitor.h"
#include "config.h"
#include "utilities/network_utilities.h"
#include "utilities/rtsp_message_utilities.h"
#ifdef CONFIG_OPENSSL
#include <openssl/evp.h>
#include <openssl/md5.h>
#endif
#ifdef CONFIG_MBEDTLS
#include <mbedtls/md5.h>
#include <mbedtls/version.h>
#endif
#ifdef CONFIG_POLARSSL
#include <polarssl/md5.h>
#endif
#include "bonjour_strings.h"
#include "common.h"
#include "player.h"
#include "rtp.h"
#include "rtsp.h"
#ifdef CONFIG_METADATA
#include "metadata/core.h"
#include "metadata/pc_queue.h"
#endif
#ifdef CONFIG_METADATA_HUB
#include "metadata/hub.h"
#endif
#ifdef AF_INET6
#define INETx_ADDRSTRLEN INET6_ADDRSTRLEN
#else
#define INETx_ADDRSTRLEN INET_ADDRSTRLEN
#endif
#ifdef CONFIG_AIRPLAY_2
#include "ap2_buffered_audio_processor.h"
#include "ap2_event_receiver.h"
#include "pair_ap/pair.h"
#include "plists/get_info_response.h"
#include "ptp-utilities.h"
#include <plist/plist.h>
#ifdef HAVE_LIBPLIST_GE_2_3_0
#define plist_from_memory(plist_data, length, plist) \
plist_from_memory((plist_data), (length), (plist), NULL)
#endif
#endif
#ifdef CONFIG_CONVOLUTION
#include "FFTConvolver/convolver.h"
#endif
#ifdef CONFIG_DBUS_INTERFACE
#include "dbus-service.h"
#endif
#include "mdns.h"
#include "utilities/network_utilities.h"
enum rtsp_read_request_response {
rtsp_read_request_response_ok,
rtsp_read_request_response_pending,
rtsp_read_request_response_immediate_shutdown_requested,
rtsp_read_request_response_bad_packet,
rtsp_read_request_response_channel_closed,
rtsp_read_request_response_read_error,
rtsp_read_request_response_error
};
rtsp_conn_info *principal_conn = NULL;
rtsp_conn_info **conns = NULL;
// always lock this when accessing the principal conn value
// use a read lock when consulting and holding it
// use a write lock if you want to change it
pthread_rwlock_t principal_conn_lock = PTHREAD_RWLOCK_INITIALIZER;
// always lock this when accessing the list of connection threads
pthread_mutex_t conns_lock = PTHREAD_MUTEX_INITIALIZER;
// only one thread is allowed to use the player at once.
// it monitors the request variable (at least when interrupted)
// static pthread_mutex_t playing_mutex = PTHREAD_MUTEX_INITIALIZER;
// static int please_shutdown = 0;
// static pthread_t playing_thread = 0;
int RTSP_connection_index = 1;
// keep track of the threads we have spawned so we can join() them
static int nconns = 0;
static void track_thread(rtsp_conn_info *conn) {
pthread_mutex_lock(&conns_lock);
// look for an empty slot first
int i = 0;
int found = 0;
while ((i < nconns) && (found == 0)) {
if (conns[i] == NULL)
found = 1;
else
i++;
}
if (found != 0) {
conns[i] = conn;
} else {
// make space for a new element
conns = realloc(conns, sizeof(rtsp_conn_info *) * (nconns + 1));
if (conns) {
conns[nconns] = conn;
nconns++;
} else {
die("could not reallocate memory for conns");
}
}
pthread_mutex_unlock(&conns_lock);
}
// note: connection numbers start at 1, so an except_this_one value of zero means "all threads"
void cancel_all_RTSP_threads(airplay_stream_c stream_category, int except_this_one) {
// if the stream category is unspecified_stream_category
// all categories are elegible for cancellation
// otherwise just the category itself
pthread_mutex_lock(&conns_lock);
int i;
for (i = 0; i < nconns; i++) {
if ((conns[i] != NULL) && (conns[i]->running != 0) &&
(conns[i]->connection_number != except_this_one) &&
((conns[i]->airplay_stream_category == stream_category) ||
(stream_category == unspecified_stream_category))) {
pthread_cancel(conns[i]->thread);
debug(2, "Connection %d: %s cancelled.", conns[i]->connection_number,
get_category_string(conns[i]->airplay_stream_category));
}
}
for (i = 0; i < nconns; i++) {
if ((conns[i] != NULL) && (conns[i]->connection_number != except_this_one) &&
((conns[i]->airplay_stream_category == stream_category) ||
(stream_category == unspecified_stream_category))) {
debug(2, "Connection %d: %s joining....", conns[i]->connection_number,
get_category_string(conns[i]->airplay_stream_category));
pthread_join(conns[i]->thread, NULL);
debug(2, "Connection %d: %s joined.", conns[i]->connection_number,
get_category_string(conns[i]->airplay_stream_category));
free(conns[i]);
conns[i] = NULL;
}
}
pthread_mutex_unlock(&conns_lock);
}
int old_connection_count = -1;
void cleanup_threads(void) {
void *retval;
int i;
int connection_count = 0;
// debug(2, "culling threads.");
pthread_mutex_lock(&conns_lock);
for (i = 0; i < nconns; i++) {
if ((conns[i] != NULL) && (conns[i]->running == 0)) {
debug(4, "found RTSP connection thread %d in a non-running state.",
conns[i]->connection_number);
pthread_join(conns[i]->thread, &retval);
debug(4, "Connection %d: deleted in cleanup.", conns[i]->connection_number);
free(conns[i]);
conns[i] = NULL;
}
if (conns[i] != NULL) {
debug(4, "Airplay Volume for connection %d is %.6f.", conns[i]->connection_number,
suggested_volume(conns[i]));
connection_count++;
}
}
pthread_mutex_unlock(&conns_lock);
if (old_connection_count != connection_count) {
if (connection_count == 0) {
debug(4, "No active connections.");
} else if (connection_count == 1)
debug(4, "One active connection.");
else
debug(4, "%d active connections.", connection_count);
old_connection_count = connection_count;
}
debug(4, "Airplay Volume for new connections is %.6f.", suggested_volume(NULL));
}
int terminate_conn(int connection_number) {
// this will look for a connection by number, cancel it, join it and delete it.
int found = 0;
pthread_mutex_lock(&conns_lock);
// look for an empty slot first
int i = 0;
while ((i < nconns) && (found == 0)) {
if ((conns[i] != NULL) && (conns[i]->connection_number == connection_number)) {
pthread_cancel(conns[i]->thread);
pthread_join(conns[i]->thread, NULL);
conns[i] = NULL;
found = 1;
} else
i++;
}
pthread_mutex_unlock(&conns_lock);
return found;
}
// The principal_conn variable points to the connection that
// controls the mDNS status and flags and that is potentially
// in control of the playing subsystem to output audio to a backend
// the principal_conn variable may be NULL
// the principal_conn is set by an ANNOUNCE message (Classic AirPlay) or
// by the initial SETUP (of a connection, not of a play session) message (AirPlay 2) and cleared
// when a session is terminated (AirPlay 2)
// In AirPlay 2, only one PTP connection can be live at any time, and it is the principal_conn.
// This is because, in AirPlay 2, the principal_conn connection
// also has control of the mDNS interface, and thus determines the state of the player as seen by
// other devices.
// If a conn has play lock, kill the connection completely.
void stop_play() {
pthread_rwlock_wrlock(&principal_conn_lock);
if (principal_conn != NULL) {
debug(1, "Connection %d: stop and close this connection.", principal_conn->connection_number);
terminate_conn(principal_conn->connection_number);
#ifdef CONFIG_AIRPLAY_2
config.airplay_statusflags &= (0xffffffff - (1 << 11)); // DeviceSupportsRelay
if (principal_conn->airplay_gid) {
free(principal_conn->airplay_gid);
principal_conn->airplay_gid = NULL; // stop using the client's GID as our GID.
}
build_bonjour_strings(principal_conn);
if (config.service_type == APST_airplay2) {
mdns_update(NULL, secondary_txt_records);
}
#endif
principal_conn = NULL; // let it go
debug(1, "Connection successfully closed.");
}
pthread_rwlock_unlock(&principal_conn_lock);
}
void release_play_lock(rtsp_conn_info *conn) {
// no need thread cancellation points in here
pthread_rwlock_wrlock(&principal_conn_lock);
if ((principal_conn == conn) || (conn == NULL)) { // if we have the player
if (principal_conn != NULL) {
#ifdef CONFIG_AIRPLAY_2
config.airplay_statusflags &= (0xffffffff - (1 << 11)); // DeviceSupportsRelay
if (principal_conn->airplay_gid) {
free(principal_conn->airplay_gid);
principal_conn->airplay_gid = NULL; // stop using the client's GID as our GID.
}
build_bonjour_strings(principal_conn);
if (config.service_type == APST_airplay2) {
mdns_update(NULL, secondary_txt_records);
}
#endif
debug(2, "Connection %d: %s released principal_conn.", conn->connection_number,
get_category_string(conn->airplay_stream_category));
}
principal_conn = NULL; // let it go
}
pthread_rwlock_unlock(&principal_conn_lock);
}
// stop the current principal_conn from playing if necessary and make conn the principal_conn.
// result of trying to acquire or release the play lock
typedef enum {
play_lock_released,
play_lock_already_released,
play_lock_already_acquired,
play_lock_acquired_without_breaking_in,
play_lock_acquired_by_breaking_in,
play_lock_aquisition_failed
} play_lock_r;
play_lock_r get_play_lock(rtsp_conn_info *conn, int allow_session_interruption) {
play_lock_r response = play_lock_aquisition_failed;
if (conn != NULL) {
debug(2, "Connection %d: %s get_play_lock with allow_session_interruption of %d.",
conn->connection_number, get_category_string(conn->airplay_stream_category),
allow_session_interruption);
pthread_rwlock_wrlock(&principal_conn_lock);
pthread_cleanup_push(rwlock_unlock, (void *)&principal_conn_lock);
if (principal_conn == conn) {
debug(2, "Connection %d: %s already has principal_conn.", principal_conn->connection_number,
get_category_string(conn->airplay_stream_category));
} else {
if (principal_conn != NULL)
debug(2, "Connection %d: %s is requested to relinquish principal_conn.",
principal_conn->connection_number,
get_category_string(conn->airplay_stream_category));
if (conn != NULL)
debug(2, "Connection %d: %s request to acquire principal_conn.", conn->connection_number,
get_category_string(conn->airplay_stream_category));
}
if (principal_conn == conn) {
if (conn == NULL)
response = play_lock_already_released;
else
response = play_lock_already_acquired;
} else if (principal_conn == NULL) {
// already unlocked, and principal conn not NULL
principal_conn = conn;
#ifdef CONFIG_AIRPLAY_2
config.airplay_statusflags |= (1 << 11); // DeviceSupportsRelay
#endif
response = play_lock_acquired_without_breaking_in;
} else if (allow_session_interruption != 0) { // principal conn not NULL,
// important -- demote the principal conn before cancelling it
/*
if (principal_conn->fd > 0) {
debug(2,
"Connection %d: %s is acquiring play_lock and is forcing termination of Connection "
"%d %s. Closing "
"RTSP connection socket %d: "
"from %s:%u to self at "
"%s:%u.",
conn->connection_number, get_category_string(conn->airplay_stream_category),
principal_conn->connection_number,
get_category_string(principal_conn->airplay_stream_category), principal_conn->fd,
principal_conn->client_ip_string, principal_conn->client_rtsp_port,
principal_conn->self_ip_string, principal_conn->self_rtsp_port);
safe_socket_close(&principal_conn->fd);
usleep(1000000);
}
*/
debug(4, "Connection %d: about to be terminated.", principal_conn->connection_number);
rtsp_conn_info *previous_principal_conn = principal_conn;
principal_conn = conn; // make the conn the new principal_conn
terminate_conn(previous_principal_conn->connection_number);
debug(4, "Connection successfully terminated.");
if (principal_conn == NULL) {
#ifdef CONFIG_AIRPLAY_2
config.airplay_statusflags &= (0xffffffff - (1 << 11)); // DeviceSupportsRelay
if (conn->airplay_gid) {
free(conn->airplay_gid);
conn->airplay_gid = NULL; // stop using the client's GID as our GID.
}
build_bonjour_strings(conn);
if (config.service_type == APST_airplay2) {
mdns_update(NULL, secondary_txt_records);
}
#endif
response = play_lock_released;
} else {
#ifdef CONFIG_AIRPLAY_2
config.airplay_statusflags |= (1 << 11); // DeviceSupportsRelay
#endif
response = play_lock_acquired_by_breaking_in;
}
// usleep(1000000); // don't know why this delay is needed.
}
if ((principal_conn != NULL) && (response != play_lock_already_acquired))
debug(2, "Connection %d: %s has principal_conn.", conn->connection_number,
get_category_string(conn->airplay_stream_category));
pthread_cleanup_pop(1); // release the principal_conn lock
} else {
debug(1, "Connection %d: %s get_play_lock must have a non-NULL conn.", conn->connection_number,
get_category_string(conn->airplay_stream_category));
}
return response;
}
// park a null at the line ending, and return the next line pointer
// accept \r, \n, or \r\n
static char *nextline(char *in, int inbuf) {
char *out = NULL;
while (inbuf) {
if (*in == '\r') {
*in++ = 0;
out = in;
inbuf--;
}
if ((*in == '\n') && (inbuf)) {
*in++ = 0;
out = in;
}
if (out)
break;
in++;
inbuf--;
}
return out;
}
#ifdef CONFIG_AIRPLAY_2
static void buf_add(sized_buffer *buf, uint8_t *in, size_t in_len) {
if (buf->length + in_len > buf->size) {
buf->size = buf->length + in_len + 2048; // Extra headroom to avoid future memcpy's
buf->data = realloc(buf->data, buf->size);
}
memcpy(buf->data + buf->length, in, in_len);
buf->length += in_len;
}
static void buf_drain(sized_buffer *buf, ssize_t len) {
if (len < 0 || (size_t)len >= buf->length) {
free(buf->data);
memset(buf, 0, sizeof(sized_buffer));
return;
}
memmove(buf->data, buf->data + len, buf->length - len);
buf->length -= len;
}
static size_t buf_remove(sized_buffer *buf, uint8_t *out, size_t out_len) {
size_t bytes = (buf->length > out_len) ? out_len : buf->length;
memcpy(out, buf->data, bytes);
buf_drain(buf, bytes);
return bytes;
}
ssize_t read_encrypted(int fd, pair_cipher_bundle *ctx, void *buf, size_t count) {
ssize_t response = 0;
// If there is leftover decoded content from the last pass just return that
if (ctx->plaintext_read_buffer.length > 0) {
response = buf_remove(&ctx->plaintext_read_buffer, buf, count);
} else {
// Otherwise read stuff in...
uint8_t in[4096];
uint8_t *plain = NULL; // may be allocated and reallocated by pair_decrypt
pthread_cleanup_push(malloc_cleanup, &plain);
size_t plain_len = 0;
do {
response = read(fd, in, sizeof(in));
if (response > 0) {
buf_add(&ctx->encrypted_read_buffer, in, response);
ssize_t consumed = pair_decrypt(&plain, &plain_len, ctx->encrypted_read_buffer.data,
ctx->encrypted_read_buffer.length, ctx->cipher_ctx);
if (consumed < 0) {
debug(1, "read_encrypted: abnormal exit from pair_decrypt: %zd.", consumed);
response = -1;
} else {
buf_drain(&ctx->encrypted_read_buffer, consumed);
}
}
} while ((plain_len == 0) && (response > 0));
if (response >= 0) {
buf_add(&ctx->plaintext_read_buffer, plain, plain_len);
response = buf_remove(&ctx->plaintext_read_buffer, buf, count);
}
pthread_cleanup_pop(1);
}
return response;
}
ssize_t write_encrypted(int fd, pair_cipher_bundle *ctx, const void *buf, size_t count) {
uint8_t *encrypted;
size_t encrypted_len;
ssize_t ret = pair_encrypt(&encrypted, &encrypted_len, buf, count, ctx->cipher_ctx);
if (ret < 0) {
debug(1, "%s", pair_cipher_errmsg(ctx->cipher_ctx));
return -1;
}
size_t remain = encrypted_len;
// debug(1, "write to the \"%s\" channel", ctx->description);
// debug_print_buffer(1, (void *)buf, count);
// debug(1, "write encrypted:");
// debug_print_buffer(1, encrypted, encrypted_len);
while (remain > 0) {
ssize_t wrote = write(fd, encrypted + (encrypted_len - remain), remain);
if (wrote <= 0) {
free(encrypted);
return wrote;
}
remain -= wrote;
}
free(encrypted);
return count;
}
#endif
ssize_t read_from_rtsp_connection(rtsp_conn_info *conn, void *buf, size_t count) {
if (count == 0)
debug(1, "asking to read zero bytes!");
ssize_t result = 0; // closed
if (conn->fd > 0) {
#ifdef CONFIG_AIRPLAY_2
if (conn->ap2_pairing_context.control_cipher_bundle.cipher_ctx) {
conn->ap2_pairing_context.control_cipher_bundle.is_encrypted = 1;
result =
read_encrypted(conn->fd, &conn->ap2_pairing_context.control_cipher_bundle, buf, count);
} else {
result = read(conn->fd, buf, count);
}
#else
result = read(conn->fd, buf, count);
// In AP1, the RTSP connection is closed in this way, so it's not unexpected
#endif
if ((result <= 0) && (errno != 0)) {
char errorstring[1024];
strerror_r(errno, (char *)errorstring, sizeof(errorstring));
debug(3, "read_from_rtsp_connection error %d \"%s\" attempting to read up to %zu bytes.",
errno, errorstring, count);
}
} else {
debug(1, "Connection %d: attempt to read from a closed RTSP connection.",
conn->connection_number);
}
return result;
}
#ifdef CONFIG_AIRPLAY_2
void set_client_as_ptp_clock(rtsp_conn_info *conn) {
char timing_list_message[4096] = "";
strncat(timing_list_message, "T ", sizeof(timing_list_message) - 1 - strlen(timing_list_message));
strncat(timing_list_message, (const char *)&conn->client_ip_string,
sizeof(timing_list_message) - 1 - strlen(timing_list_message));
ptp_send_control_message_string(timing_list_message);
}
#endif
enum rtsp_read_request_response rtsp_read_request(rtsp_conn_info *conn, rtsp_message **the_packet) {
enum rtsp_read_request_response reply = rtsp_read_request_response_pending;
*the_packet = NULL; // need this for error handling
ssize_t buflen = 4096;
#ifdef CONFIG_METADATA
if ((config.metadata_enabled != 0) && (config.get_coverart != 0))
buflen = 1024 * 256; // big enough for typical picture data, which will be base64 encoded
#endif
int release_buffer = 0; // on exit, don't deallocate the buffer if everything was okay
char *buf = malloc(buflen + 1); // add a NUL at the end
if (buf == NULL) {
debug(1, "Connection %d: rtsp_read_request: can't get a buffer.", conn->connection_number);
reply = rtsp_read_request_response_error;
} else {
debug(4, "buf is allocated at 0x%" PRIxPTR ".", (uintptr_t)buf);
pthread_cleanup_push(malloc_cleanup, &buf);
ssize_t nread;
ssize_t inbuf = 0;
int msg_size = -1;
while ((msg_size < 0) && (reply == rtsp_read_request_response_pending)) {
if (conn->stop != 0) {
debug(3, "Connection %d: shutdown requested by client.", conn->connection_number);
reply = rtsp_read_request_response_immediate_shutdown_requested;
// goto shutdown;
} else {
nread = read_from_rtsp_connection(conn, buf + inbuf, buflen - inbuf);
if (nread <= 0) {
// ETIMEDOUT seems to be from the keepalive having failed.
// But it does seem as it it's not always sent, e.g. if another read() is outstanding (?)
// EAGAIN seems to be simply from the read() request timing out.
if (errno == ETIMEDOUT) {
debug(1,
"Connection %d has disappeared. As Yeats almost said, \"Too long a "
"silence / can make a stone "
"of the heart\". ETIMEOUT",
conn->connection_number);
reply = rtsp_read_request_response_immediate_shutdown_requested;
} else if (nread == 0) {
if (errno == 0) {
// a blocking read that returns zero means eof -- implies connection closed by client
debug(2, "Connection %d RTSP closed by client.", conn->connection_number);
} else {
char errorstring[1024];
strerror_r(errno, (char *)errorstring, sizeof(errorstring));
debug(2, "Connection %d RTSP port closed by client with error %d: \"%s\".",
conn->connection_number, errno, (char *)errorstring);
}
safe_socket_close(&conn->fd); // close it from our end too...
reply = rtsp_read_request_response_channel_closed;
} else {
char errorstring[1024];
strerror_r(errno, (char *)errorstring, sizeof(errorstring));
debug(1, "Connection %d: rtsp_read_request_response_read_error %d: \"%s\".",
conn->connection_number, errno, (char *)errorstring);
reply = rtsp_read_request_response_read_error;
}
// goto shutdown;
} else {
/* // this outputs the message received
{
void *pt = malloc(nread+1);
memset(pt, 0, nread+1);
memcpy(pt, buf + inbuf, nread);
debug(1, "Incoming string on port: \"%s\"",pt);
free(pt);
}
*/
inbuf += nread;
char *next;
while ((reply == rtsp_read_request_response_pending) && (msg_size < 0) &&
(next = nextline(buf, inbuf))) {
msg_size = msg_handle_line(the_packet, buf);
if (!(*the_packet)) {
debug(1, "Connection %d: rtsp_read_request can't find an RTSP header.",
conn->connection_number);
reply = rtsp_read_request_response_bad_packet;
// goto shutdown;
} else {
inbuf -= next - buf;
if (inbuf)
memmove(buf, next, inbuf);
}
}
}
}
}
if ((reply == rtsp_read_request_response_pending) && (msg_size > 0)) {
// more input is needed...
uint64_t threshold_time =
get_absolute_time_in_ns() + ((uint64_t)15000000000); // i.e. fifteen seconds from now
int warning_message_sent = 0;
if (msg_size > buflen) {
buf = realloc(buf, msg_size + 1);
if (buf == NULL) {
warn("Connection %d: too much content.", conn->connection_number);
reply = rtsp_read_request_response_error;
// goto shutdown;
} else {
debug(4, "buf is reallocated at 0x%" PRIxPTR ".", (uintptr_t)buf);
buflen = msg_size;
}
}
// const size_t max_read_chunk = 1024 * 1024 / 16;
while ((inbuf < msg_size) && (reply == rtsp_read_request_response_pending)) {
// we are going to read the stream in chunks and time how long it takes to
// do so.
// If it's taking too long, (and we find out about it), we will send an
// error message as
// metadata
if (warning_message_sent == 0) {
uint64_t time_now = get_absolute_time_in_ns();
if (time_now > threshold_time) { // it's taking too long
debug(1, "Error receiving metadata from source -- transmission seems "
"to be stalled.");
#ifdef CONFIG_METADATA
send_ssnc_metadata('stal', NULL, 0, 1);
#endif
warning_message_sent = 1;
}
}
if (conn->stop != 0) {
debug(1, "RTSP shutdown requested.");
reply = rtsp_read_request_response_immediate_shutdown_requested;
// goto shutdown;
} else {
size_t read_chunk = msg_size - inbuf;
// if (read_chunk > max_read_chunk)
// read_chunk = max_read_chunk;
// usleep(80000); // wait about 80 milliseconds between reads of up to max_read_chunk
nread = read_from_rtsp_connection(conn, buf + inbuf, read_chunk);
if (nread <= 0) {
// ETIMEDOUT seems to be from the keepalive having failed.
// But it does seem as it it's not always sent, e.g. if another read() is outstanding
// (?) EAGAIN seems to be simply from the read() request timing out.
if (errno == ETIMEDOUT) {
debug(1,
"Connection %d has disappeared. As Yeats almost said, \"Too long a "
"silence / can make a stone "
"of the heart\". ETIMEOUT",
conn->connection_number);
reply = rtsp_read_request_response_immediate_shutdown_requested;
// Note: the socket will be closed when the thread exits
} else if (nread == 0) {
if (errno == 0) {
// a blocking read that returns zero means eof -- implies connection closed by
// client
debug(1, "Connection %d closed by client.", conn->connection_number);
} else {
char errorstring[1024];
strerror_r(errno, (char *)errorstring, sizeof(errorstring));
debug(1, "Connection %d closed by client with error %d: \"%s\".",
conn->connection_number, errno, (char *)errorstring);
}
reply = rtsp_read_request_response_channel_closed;
// Note: the socket will be closed when the thread exits
} else {
char errorstring[1024];
strerror_r(errno, (char *)errorstring, sizeof(errorstring));
debug(1, "Connection %d: rtsp_read_request_response_read_error %d: \"%s\".",
conn->connection_number, errno, (char *)errorstring);
reply = rtsp_read_request_response_read_error;
}
// goto shutdown;
} else {
inbuf += nread;
}
}
}
}
if (reply == rtsp_read_request_response_pending) {
reply = rtsp_read_request_response_ok;
rtsp_message *msg = *the_packet;
msg->contentlength = inbuf;
msg->content = buf;
char *jp = inbuf + buf;
*jp = '\0';
*the_packet = msg;
}
// shutdown:
if (reply != rtsp_read_request_response_ok) {
if (*the_packet != NULL) {
debug(3, "Freeing the_packet");
msg_free(the_packet);
}
release_buffer = 1; // allow the buffer to be released
}
pthread_cleanup_pop(release_buffer);
}
return reply;
}
int msg_write_response(rtsp_conn_info *conn, rtsp_message *resp) {
char pkt[4096];
int pktfree = sizeof(pkt);
char *p = pkt;
int n;
unsigned int i;
struct response_t {
int code;
char *string;
};
struct response_t responses[] = {{200, "OK"},
{400, "Bad Request"},
{403, "Unauthorized"},
{404, "Not Found"},
{451, "Unavailable"},
{456, "Header Field Not Valid for Resource"},
{470, "Connection Authorization Required"},
{500, "Internal Server Error"},
{501, "Not Implemented"}};
// 451 is really "Unavailable For Legal Reasons"!
int found = 0;
char *respcode_text = "Unauthorized";
for (i = 0; i < sizeof(responses) / sizeof(struct response_t); i++) {
if (resp->respcode == responses[i].code) {
found = 1;
respcode_text = responses[i].string;
}
}
if (found == 0)
debug(1, "can't find text for response code %d. Using \"%s\" instead.", resp->respcode,
respcode_text);
n = snprintf(p, pktfree, "RTSP/1.0 %d %s\r\n", resp->respcode, respcode_text);
pktfree -= n;
p += n;
for (i = 0; i < resp->nheaders; i++) {
// debug(3, " %s: %s.", resp->name[i], resp->value[i]);
n = snprintf(p, pktfree, "%s: %s\r\n", resp->name[i], resp->value[i]);
pktfree -= n;
p += n;
if (pktfree <= 1024) {
debug(1, "Attempted to write overlong RTSP packet 1");
return -1;
}
}
// Here, if there's content, write the Content-Length header ...
// if (resp->contentlength) {
{
// debug(2, "Responding with content of length %d", resp->contentlength);
n = snprintf(p, pktfree, "Content-Length: %d\r\n", resp->contentlength);
pktfree -= n;
p += n;
if (pktfree <= 1024) {
debug(1, "Attempted to write overlong RTSP packet 2");
return -2;
}
}
n = snprintf(p, pktfree, "\r\n");
pktfree -= n;
p += n;
if (resp->contentlength) {
memcpy(p, resp->content, resp->contentlength);
pktfree -= resp->contentlength;
p += resp->contentlength;
}
if (pktfree <= 1024) {
debug(1, "Attempted to write overlong RTSP packet 3");
return -3;
}
// here, if the link is encrypted, better do it
#ifdef CONFIG_AIRPLAY_2
ssize_t reply;
if (conn->ap2_pairing_context.control_cipher_bundle.is_encrypted) {
reply =
write_encrypted(conn->fd, &conn->ap2_pairing_context.control_cipher_bundle, pkt, p - pkt);
} else {
reply = write(conn->fd, pkt, p - pkt);
}
#else
ssize_t reply = write(conn->fd, pkt, p - pkt);
#endif
if (reply == -1) {
char errorstring[1024];
strerror_r(errno, (char *)errorstring, sizeof(errorstring));
debug(1, "msg_write_response error %d: \"%s\".", errno, (char *)errorstring);
return -4;
}
if (reply != p - pkt) {
debug(1, "msg_write_response error -- requested bytes: %zd not fully written: %zd.", p - pkt,
reply);
return -5;
}
return 0;
}
#ifdef CONFIG_AIRPLAY_2
void handle_record_2(rtsp_conn_info *conn, __attribute((unused)) rtsp_message *req,
rtsp_message *resp) {
debug(2, "Connection %d: RECORD (AP2) on %s", conn->connection_number,
get_category_string(conn->airplay_stream_category));
debug_log_rtsp_message_conn(conn, 2, "RECORD (AP2) incoming message", req);
msg_add_header(resp, "Audio-Latency", "0");
resp->respcode = 200;
}
#endif
void handle_record(rtsp_conn_info *conn, rtsp_message *req, rtsp_message *resp) {
debug(1, "Connection %d: RECORD", conn->connection_number);
if ((conn != NULL) && (principal_conn == conn)) {
if (conn->player_thread)
warn("Connection %d: RECORD: Duplicate RECORD message -- ignored", conn->connection_number);
else {
activity_monitor_signify_activity(1);
player_play(conn); // the thread better be 0
}
resp->respcode = 200;
// I think this is for telling the client what the absolute minimum latency
// actually is,
// and when the client specifies a latency, it should be added to this figure.
// Thus, [the old version of] AirPlay's latency figure of 77175, when added to 11025 gives you
// exactly 88200
// and iTunes' latency figure of 88553, when added to 11025 gives you 99578,
// pretty close to the 99400 we guessed.
msg_add_header(resp, "Audio-Latency", "11025");
char *p;
uint32_t rtptime = 0;
char *hdr = msg_get_header(req, "RTP-Info");
if (hdr) {
// debug(1,"FLUSH message received: \"%s\".",hdr);
// get the rtp timestamp
p = strstr(hdr, "rtptime=");
if (p) {
p = strchr(p, '=');
if (p) {
rtptime = uatoi(p + 1); // unsigned integer -- up to 2^32-1
// rtptime--;
// debug(1,"RTSP Flush Requested by handle_record: %u.",rtptime);
player_flush(rtptime, conn);
}
}
}
} else {
warn("Connection %d RECORD received without having the player (no ANNOUNCE?)",
conn->connection_number);
resp->respcode = 451;
}
}
#ifdef CONFIG_AIRPLAY_2
int add_pstring_to_malloc(const char *s, void **allocation, size_t *size) {
int response = 0;
void *p = *allocation;
if (p == NULL) {
p = malloc(strlen(s) + 1);
if (p == NULL) {
debug(1, "error allocating memory");
} else {
*allocation = p;
*size = *size + strlen(s) + 1;
uint8_t *b = (uint8_t *)p;
*b = strlen(s);
p = p + 1;
memcpy(p, s, strlen(s));
response = 1;
}
} else {
p = realloc(p, *size + strlen(s) + 1);
if (p == NULL) { // assuming we never allocate a zero byte space
debug(1, "error reallocating memory");
} else {
*allocation = p;
uint8_t *b = (uint8_t *)p + *size;
*b = strlen(s);
p = p + *size + 1;
memcpy(p, s, strlen(s));
*size = *size + strlen(s) + 1;
response = 1;
}
}
return response;
}
void generateTxtDataValueInfo(rtsp_conn_info *conn, void **response, size_t *responseLength) {
void *qualifier_response_data = NULL;
size_t qualifier_response_data_length = 0;
char localString[256];
if (add_pstring_to_malloc("acl=0", &qualifier_response_data, &qualifier_response_data_length) ==
0)