• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***
2   This file is part of PulseAudio.
3 
4   Copyright 2008 Colin Guthrie
5   Copyright 2013 Hajime Fujita
6   Copyright 2013 Martin Blanchard
7 
8   PulseAudio is free software; you can redistribute it and/or modify
9   it under the terms of the GNU Lesser General Public License as published
10   by the Free Software Foundation; either version 2.1 of the License,
11   or (at your option) any later version.
12 
13   PulseAudio is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17 
18   You should have received a copy of the GNU Lesser General Public License
19   along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
20 ***/
21 
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25 
26 #include <stdlib.h>
27 #include <stdint.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <sys/ioctl.h>
32 #include <math.h>
33 
34 #ifdef HAVE_SYS_FILIO_H
35 #include <sys/filio.h>
36 #endif
37 
38 #include <pulse/xmalloc.h>
39 #include <pulse/timeval.h>
40 #include <pulse/sample.h>
41 
42 #include <pulsecore/core.h>
43 #include <pulsecore/core-error.h>
44 #include <pulsecore/core-rtclock.h>
45 #include <pulsecore/core-util.h>
46 #include <pulsecore/iochannel.h>
47 #include <pulsecore/arpa-inet.h>
48 #include <pulsecore/socket-client.h>
49 #include <pulsecore/socket-util.h>
50 #include <pulsecore/log.h>
51 #include <pulsecore/parseaddr.h>
52 #include <pulsecore/macro.h>
53 #include <pulsecore/memchunk.h>
54 #include <pulsecore/random.h>
55 #include <pulsecore/poll.h>
56 
57 #include <modules/rtp/rtsp_client.h>
58 
59 #include "raop-client.h"
60 #include "raop-packet-buffer.h"
61 #include "raop-crypto.h"
62 #include "raop-util.h"
63 
64 #define DEFAULT_RAOP_PORT 5000
65 
66 #define FRAMES_PER_TCP_PACKET 4096
67 #define FRAMES_PER_UDP_PACKET 352
68 
69 #define RTX_BUFFERING_SECONDS 4
70 
71 #define DEFAULT_TCP_AUDIO_PORT   6000
72 #define DEFAULT_UDP_AUDIO_PORT   6000
73 #define DEFAULT_UDP_CONTROL_PORT 6001
74 #define DEFAULT_UDP_TIMING_PORT  6002
75 
76 #define DEFAULT_USER_AGENT "iTunes/11.0.4 (Windows; N)"
77 #define DEFAULT_USER_NAME  "iTunes"
78 
79 #define JACK_STATUS_DISCONNECTED 0
80 #define JACK_STATUS_CONNECTED    1
81 #define JACK_TYPE_ANALOG         0
82 #define JACK_TYPE_DIGITAL        1
83 
84 #define VOLUME_MAX  0.0
85 #define VOLUME_DEF -30.0
86 #define VOLUME_MIN -144.0
87 
88 #define UDP_DEFAULT_PKT_BUF_SIZE 1000
89 #define APPLE_CHALLENGE_LENGTH 16
90 
91 struct pa_raop_client {
92     pa_core *core;
93     char *host;
94     uint16_t port;
95     pa_rtsp_client *rtsp;
96     char *sci, *sid;
97     char *password;
98     bool autoreconnect;
99 
100     pa_raop_protocol_t protocol;
101     pa_raop_encryption_t encryption;
102     pa_raop_codec_t codec;
103 
104     pa_raop_secret *secret;
105 
106     int tcp_sfd;
107 
108     int udp_sfd;
109     int udp_cfd;
110     int udp_tfd;
111 
112     pa_raop_packet_buffer *pbuf;
113 
114     uint16_t seq;
115     uint32_t rtptime;
116     bool is_recording;
117     uint32_t ssrc;
118 
119     bool is_first_packet;
120     uint32_t sync_interval;
121     uint32_t sync_count;
122 
123     uint8_t jack_type;
124     uint8_t jack_status;
125 
126     pa_raop_client_state_cb_t state_callback;
127     void *state_userdata;
128 };
129 
130 /* Audio TCP packet header [16x8] (cf. rfc4571):
131  *  [0,1]   Frame marker; seems always 0x2400
132  *  [2,3]   RTP packet size (following): 0x0000 (to be set)
133  *   [4,5]   RTP v2: 0x80
134  *   [5]     Payload type: 0x60 | Marker bit: 0x80 (always set)
135  *   [6,7]   Sequence number: 0x0000 (to be set)
136  *   [8,11]  Timestamp: 0x00000000 (to be set)
137  *   [12,15] SSRC: 0x00000000 (to be set) */
138 #define PAYLOAD_TCP_AUDIO_DATA 0x60
139 static const uint8_t tcp_audio_header[16] = {
140     0x24, 0x00, 0x00, 0x00,
141     0x80, 0xe0, 0x00, 0x00,
142     0x00, 0x00, 0x00, 0x00,
143     0x00, 0x00, 0x00, 0x00
144 };
145 
146 /* Audio UDP packet header [12x8] (cf. rfc3550):
147  *  [0]    RTP v2: 0x80
148  *  [1]    Payload type: 0x60
149  *  [2,3]  Sequence number: 0x0000 (to be set)
150  *  [4,7]  Timestamp: 0x00000000 (to be set)
151  *  [8,12] SSRC: 0x00000000 (to be set) */
152 #define PAYLOAD_UDP_AUDIO_DATA 0x60
153 static const uint8_t udp_audio_header[12] = {
154     0x80, 0x60, 0x00, 0x00,
155     0x00, 0x00, 0x00, 0x00,
156     0x00, 0x00, 0x00, 0x00
157 };
158 
159 /* Audio retransmission UDP packet header [4x8]:
160  *  [0] RTP v2: 0x80
161  *  [1] Payload type: 0x56 | Marker bit: 0x80 (always set)
162  *  [2] Unknown; seems always 0x01
163  *  [3] Unknown; seems some random number around 0x20~0x40 */
164 #define PAYLOAD_RETRANSMIT_REQUEST 0x55
165 #define PAYLOAD_RETRANSMIT_REPLY   0x56
166 static const uint8_t udp_audio_retrans_header[4] = {
167     0x80, 0xd6, 0x00, 0x00
168 };
169 
170 /* Sync packet header [8x8] (cf. rfc3550):
171  *  [0]   RTP v2: 0x80
172  *  [1]   Payload type: 0x54 | Marker bit: 0x80 (always set)
173  *  [2,3] Sequence number: 0x0007
174  *  [4,7] Timestamp: 0x00000000 (to be set) */
175 static const uint8_t udp_sync_header[8] = {
176     0x80, 0xd4, 0x00, 0x07,
177     0x00, 0x00, 0x00, 0x00
178 };
179 
180 /* Timing packet header [8x8] (cf. rfc3550):
181  *  [0]   RTP v2: 0x80
182  *  [1]   Payload type: 0x53 | Marker bit: 0x80 (always set)
183  *  [2,3] Sequence number: 0x0007
184  *  [4,7] Timestamp: 0x00000000 (unused) */
185 #define PAYLOAD_TIMING_REQUEST  0x52
186 #define PAYLOAD_TIMING_REPLY    0x53
187 static const uint8_t udp_timing_header[8] = {
188     0x80, 0xd3, 0x00, 0x07,
189     0x00, 0x00, 0x00, 0x00
190 };
191 
192 /**
193  * Function to trim a given character at the end of a string (no realloc).
194  * @param str Pointer to string
195  * @param rc Character to trim
196  */
rtrim_char(char * str,char rc)197 static inline void rtrim_char(char *str, char rc) {
198     char *sp = str + strlen(str) - 1;
199     while (sp >= str && *sp == rc) {
200         *sp = '\0';
201         sp -= 1;
202     }
203 }
204 
205 /**
206  * Function to convert a timeval to ntp timestamp.
207  * @param tv Pointer to the timeval structure
208  * @return The NTP timestamp
209  */
timeval_to_ntp(struct timeval * tv)210 static inline uint64_t timeval_to_ntp(struct timeval *tv) {
211     uint64_t ntp = 0;
212 
213     /* Converting micro seconds to a fraction. */
214     ntp = (uint64_t) tv->tv_usec * UINT32_MAX / PA_USEC_PER_SEC;
215     /* Moving reference from  1 Jan 1970 to 1 Jan 1900 (seconds). */
216     ntp |= (uint64_t) (tv->tv_sec + 0x83aa7e80) << 32;
217 
218     return ntp;
219 }
220 
221 /**
222  * Function to write bits into a buffer.
223  * @param buffer Handle to the buffer. It will be incremented if new data requires it.
224  * @param bit_pos A pointer to a position buffer to keep track the current write location (0 for MSB, 7 for LSB)
225  * @param size A pointer to the byte size currently written. This allows the calling function to do simple buffer overflow checks
226  * @param data The data to write
227  * @param data_bit_len The number of bits from data to write
228  */
bit_writer(uint8_t ** buffer,uint8_t * bit_pos,size_t * size,uint8_t data,uint8_t data_bit_len)229 static inline void bit_writer(uint8_t **buffer, uint8_t *bit_pos, size_t *size, uint8_t data, uint8_t data_bit_len) {
230     int bits_left, bit_overflow;
231     uint8_t bit_data;
232 
233     if (!data_bit_len)
234         return;
235 
236     /* If bit pos is zero, we will definitely use at least one bit from the current byte so size increments. */
237     if (!*bit_pos)
238         *size += 1;
239 
240     /* Calc the number of bits left in the current byte of buffer. */
241     bits_left = 7 - *bit_pos  + 1;
242     /* Calc the overflow of bits in relation to how much space we have left... */
243     bit_overflow = bits_left - data_bit_len;
244     if (bit_overflow >= 0) {
245         /* We can fit the new data in our current byte.
246          * As we write from MSB->LSB we need to left shift by the overflow amount. */
247         bit_data = data << bit_overflow;
248         if (*bit_pos)
249             **buffer |= bit_data;
250         else
251             **buffer = bit_data;
252         /* If our data fits exactly into the current byte, we need to increment our pointer. */
253         if (0 == bit_overflow) {
254             /* Do not increment size as it will be incremented on next call as bit_pos is zero. */
255             *buffer += 1;
256             *bit_pos = 0;
257         } else {
258             *bit_pos += data_bit_len;
259         }
260     } else {
261         /* bit_overflow is negative, there for we will need a new byte from our buffer
262          * Firstly fill up what's left in the current byte. */
263         bit_data = data >> -bit_overflow;
264         **buffer |= bit_data;
265         /* Increment our buffer pointer and size counter. */
266         *buffer += 1;
267         *size += 1;
268         **buffer = data << (8 + bit_overflow);
269         *bit_pos = -bit_overflow;
270     }
271 }
272 
write_ALAC_data(uint8_t * packet,const size_t max,uint8_t * raw,size_t * length,bool compress)273 static size_t write_ALAC_data(uint8_t *packet, const size_t max, uint8_t *raw, size_t *length, bool compress) {
274     uint32_t nbs = (*length / 2) / 2;
275     uint8_t *ibp, *maxibp;
276     uint8_t *bp, bpos;
277     size_t size = 0;
278 
279     bp = packet;
280     pa_memzero(packet, max);
281     size = bpos = 0;
282 
283     bit_writer(&bp, &bpos, &size, 1, 3); /* channel=1, stereo */
284     bit_writer(&bp, &bpos, &size, 0, 4); /* Unknown */
285     bit_writer(&bp, &bpos, &size, 0, 8); /* Unknown */
286     bit_writer(&bp, &bpos, &size, 0, 4); /* Unknown */
287     bit_writer(&bp, &bpos, &size, 1, 1); /* Hassize */
288     bit_writer(&bp, &bpos, &size, 0, 2); /* Unused */
289     bit_writer(&bp, &bpos, &size, 1, 1); /* Is-not-compressed */
290     /* Size of data, integer, big endian. */
291     bit_writer(&bp, &bpos, &size, (nbs >> 24) & 0xff, 8);
292     bit_writer(&bp, &bpos, &size, (nbs >> 16) & 0xff, 8);
293     bit_writer(&bp, &bpos, &size, (nbs >> 8)  & 0xff, 8);
294     bit_writer(&bp, &bpos, &size, (nbs)       & 0xff, 8);
295 
296     ibp = raw;
297     maxibp = raw + (4 * nbs) - 4;
298     while (ibp <= maxibp) {
299         /* Byte swap stereo data. */
300         bit_writer(&bp, &bpos, &size, *(ibp + 1), 8);
301         bit_writer(&bp, &bpos, &size, *(ibp + 0), 8);
302         bit_writer(&bp, &bpos, &size, *(ibp + 3), 8);
303         bit_writer(&bp, &bpos, &size, *(ibp + 2), 8);
304         ibp += 4;
305     }
306 
307     *length = (ibp - raw);
308     return size;
309 }
310 
build_tcp_audio_packet(pa_raop_client * c,pa_memchunk * block,pa_memchunk * packet)311 static size_t build_tcp_audio_packet(pa_raop_client *c, pa_memchunk *block, pa_memchunk *packet) {
312     const size_t head = sizeof(tcp_audio_header);
313     uint32_t *buffer = NULL;
314     uint8_t *raw = NULL;
315     size_t length, size;
316 
317     raw = pa_memblock_acquire(block->memblock);
318     buffer = pa_memblock_acquire(packet->memblock);
319     buffer += packet->index / sizeof(uint32_t);
320     raw += block->index;
321 
322     /* Wrap sequence number to 0 then UINT16_MAX is reached */
323     if (c->seq == UINT16_MAX)
324         c->seq = 0;
325     else
326         c->seq++;
327 
328     memcpy(buffer, tcp_audio_header, sizeof(tcp_audio_header));
329     buffer[1] |= htonl((uint32_t) c->seq);
330     buffer[2] = htonl(c->rtptime);
331     buffer[3] = htonl(c->ssrc);
332 
333     length = block->length;
334     size = sizeof(tcp_audio_header);
335     if (c->codec == PA_RAOP_CODEC_ALAC)
336         size += write_ALAC_data(((uint8_t *) buffer + head), packet->length - head, raw, &length, false);
337     else {
338         pa_log_debug("Only ALAC encoding is supported, sending zeros...");
339         pa_memzero(((uint8_t *) buffer + head), packet->length - head);
340         size += length;
341     }
342 
343     c->rtptime += length / 4;
344 
345     pa_memblock_release(block->memblock);
346 
347     buffer[0] |= htonl((uint32_t) size - 4);
348     if (c->encryption == PA_RAOP_ENCRYPTION_RSA)
349         pa_raop_aes_encrypt(c->secret, (uint8_t *) buffer + head, size - head);
350 
351     pa_memblock_release(packet->memblock);
352     packet->length = size;
353 
354     return size;
355 }
356 
send_tcp_audio_packet(pa_raop_client * c,pa_memchunk * block,size_t offset)357 static ssize_t send_tcp_audio_packet(pa_raop_client *c, pa_memchunk *block, size_t offset) {
358     static int write_type = 0;
359     const size_t max = sizeof(tcp_audio_header) + 8 + 16384;
360     pa_memchunk *packet = NULL;
361     uint8_t *buffer = NULL;
362     double progress = 0.0;
363     ssize_t written = -1;
364     size_t done = 0;
365 
366     packet = pa_raop_packet_buffer_retrieve(c->pbuf, c->seq);
367 
368     if (!packet || (packet && packet->length <= 0)) {
369         pa_assert(block->index == offset);
370 
371         if (!(packet = pa_raop_packet_buffer_prepare(c->pbuf, c->seq, max)))
372             return -1;
373 
374         packet->index = 0;
375         packet->length = max;
376         if (!build_tcp_audio_packet(c, block, packet))
377             return -1;
378     }
379 
380     buffer = pa_memblock_acquire(packet->memblock);
381 
382     pa_assert(buffer);
383 
384     buffer += packet->index;
385     if (buffer && packet->length > 0)
386         written = pa_write(c->tcp_sfd, buffer, packet->length, &write_type);
387     if (written > 0) {
388         progress = (double) written / (double) packet->length;
389         packet->length -= written;
390         packet->index += written;
391 
392         done = block->length * progress;
393         block->length -= done;
394         block->index += done;
395     }
396 
397     pa_memblock_release(packet->memblock);
398 
399     return written;
400 }
401 
build_udp_audio_packet(pa_raop_client * c,pa_memchunk * block,pa_memchunk * packet)402 static size_t build_udp_audio_packet(pa_raop_client *c, pa_memchunk *block, pa_memchunk *packet) {
403     const size_t head = sizeof(udp_audio_header);
404     uint32_t *buffer = NULL;
405     uint8_t *raw = NULL;
406     size_t length, size;
407 
408     raw = pa_memblock_acquire(block->memblock);
409     buffer = pa_memblock_acquire(packet->memblock);
410     buffer += packet->index / sizeof(uint32_t);
411     raw += block->index;
412 
413     memcpy(buffer, udp_audio_header, sizeof(udp_audio_header));
414     if (c->is_first_packet)
415         buffer[0] |= htonl((uint32_t) 0x80 << 16);
416     buffer[0] |= htonl((uint32_t) c->seq);
417     buffer[1] = htonl(c->rtptime);
418     buffer[2] = htonl(c->ssrc);
419 
420     length = block->length;
421     size = sizeof(udp_audio_header);
422     if (c->codec == PA_RAOP_CODEC_ALAC)
423         size += write_ALAC_data(((uint8_t *) buffer + head), packet->length - head, raw, &length, false);
424     else {
425         pa_log_debug("Only ALAC encoding is supported, sending zeros...");
426         pa_memzero(((uint8_t *) buffer + head), packet->length - head);
427         size += length;
428     }
429 
430     c->rtptime += length / 4;
431 
432     /* Wrap sequence number to 0 then UINT16_MAX is reached */
433     if (c->seq == UINT16_MAX)
434         c->seq = 0;
435     else
436         c->seq++;
437 
438     pa_memblock_release(block->memblock);
439 
440     if (c->encryption == PA_RAOP_ENCRYPTION_RSA)
441         pa_raop_aes_encrypt(c->secret, (uint8_t *) buffer + head, size - head);
442 
443     pa_memblock_release(packet->memblock);
444     packet->length = size;
445 
446     return size;
447 }
448 
send_udp_audio_packet(pa_raop_client * c,pa_memchunk * block,size_t offset)449 static ssize_t send_udp_audio_packet(pa_raop_client *c, pa_memchunk *block, size_t offset) {
450     const size_t max = sizeof(udp_audio_retrans_header) + sizeof(udp_audio_header) + 8 + 1408;
451     pa_memchunk *packet = NULL;
452     uint8_t *buffer = NULL;
453     ssize_t written = -1;
454 
455     /* UDP packet has to be sent at once ! */
456     pa_assert(block->index == offset);
457 
458     if (!(packet = pa_raop_packet_buffer_prepare(c->pbuf, c->seq, max)))
459         return -1;
460 
461     packet->index = sizeof(udp_audio_retrans_header);
462     packet->length = max - sizeof(udp_audio_retrans_header);
463     if (!build_udp_audio_packet(c, block, packet))
464         return -1;
465 
466     buffer = pa_memblock_acquire(packet->memblock);
467 
468     pa_assert(buffer);
469 
470     buffer += packet->index;
471     if (buffer && packet->length > 0)
472         written = pa_write(c->udp_sfd, buffer, packet->length, NULL);
473     if (written < 0 && errno == EAGAIN) {
474         pa_log_debug("Discarding UDP (audio, seq=%d) packet due to EAGAIN (%s)", c->seq, pa_cstrerror(errno));
475         written = packet->length;
476     }
477 
478     pa_memblock_release(packet->memblock);
479     /* It is meaningless to preseve the partial data */
480     block->index += block->length;
481     block->length = 0;
482 
483     return written;
484 }
485 
rebuild_udp_audio_packet(pa_raop_client * c,uint16_t seq,pa_memchunk * packet)486 static size_t rebuild_udp_audio_packet(pa_raop_client *c, uint16_t seq, pa_memchunk *packet) {
487     size_t size = sizeof(udp_audio_retrans_header);
488     uint32_t *buffer = NULL;
489 
490     buffer = pa_memblock_acquire(packet->memblock);
491 
492     memcpy(buffer, udp_audio_retrans_header, sizeof(udp_audio_retrans_header));
493     buffer[0] |= htonl((uint32_t) seq);
494     size += packet->length;
495 
496     pa_memblock_release(packet->memblock);
497     packet->length += sizeof(udp_audio_retrans_header);
498     packet->index -= sizeof(udp_audio_retrans_header);
499 
500     return size;
501 }
502 
resend_udp_audio_packets(pa_raop_client * c,uint16_t seq,uint16_t nbp)503 static ssize_t resend_udp_audio_packets(pa_raop_client *c, uint16_t seq, uint16_t nbp) {
504     ssize_t total = 0;
505     int i = 0;
506 
507     for (i = 0; i < nbp; i++) {
508         pa_memchunk *packet = NULL;
509         uint8_t *buffer = NULL;
510         ssize_t written = -1;
511 
512         if (!(packet = pa_raop_packet_buffer_retrieve(c->pbuf, seq + i)))
513             continue;
514 
515         if (packet->index > 0) {
516             if (!rebuild_udp_audio_packet(c, seq + i, packet))
517                 continue;
518         }
519 
520         pa_assert(packet->index == 0);
521 
522         buffer = pa_memblock_acquire(packet->memblock);
523 
524         pa_assert(buffer);
525 
526         if (buffer && packet->length > 0)
527             written = pa_write(c->udp_cfd, buffer, packet->length, NULL);
528         if (written < 0 && errno == EAGAIN) {
529             pa_log_debug("Discarding UDP (audio-retransmitted, seq=%d) packet due to EAGAIN", seq + i);
530             pa_memblock_release(packet->memblock);
531             continue;
532         }
533 
534         pa_memblock_release(packet->memblock);
535         total +=  written;
536     }
537 
538     return total;
539 }
540 
541 /* Caller has to free the allocated memory region for packet */
build_udp_sync_packet(pa_raop_client * c,uint32_t stamp,uint32_t ** packet)542 static size_t build_udp_sync_packet(pa_raop_client *c, uint32_t stamp, uint32_t **packet) {
543     const size_t size = sizeof(udp_sync_header) + 12;
544     const uint32_t delay = 88200;
545     uint32_t *buffer = NULL;
546     uint64_t transmitted = 0;
547     struct timeval tv;
548 
549     *packet = NULL;
550     if (!(buffer = pa_xmalloc0(size)))
551         return 0;
552 
553     memcpy(buffer, udp_sync_header, sizeof(udp_sync_header));
554     if (c->is_first_packet)
555         buffer[0] |= 0x10;
556     stamp -= delay;
557     buffer[1] = htonl(stamp);
558     /* Set the transmitted timestamp to current time. */
559     transmitted = timeval_to_ntp(pa_rtclock_get(&tv));
560     buffer[2] = htonl(transmitted >> 32);
561     buffer[3] = htonl(transmitted & 0xffffffff);
562     stamp += delay;
563     buffer[4] = htonl(stamp);
564 
565     *packet = buffer;
566     return size;
567 }
568 
send_udp_sync_packet(pa_raop_client * c,uint32_t stamp)569 static ssize_t send_udp_sync_packet(pa_raop_client *c, uint32_t stamp) {
570     uint32_t * packet = NULL;
571     ssize_t written = 0;
572     size_t size = 0;
573 
574     size = build_udp_sync_packet(c, stamp, &packet);
575     if (packet != NULL && size > 0) {
576         written = pa_loop_write(c->udp_cfd, packet, size, NULL);
577         pa_xfree(packet);
578     }
579 
580     return written;
581 }
582 
handle_udp_control_packet(pa_raop_client * c,const uint8_t packet[],ssize_t size)583 static size_t handle_udp_control_packet(pa_raop_client *c, const uint8_t packet[], ssize_t size) {
584     uint8_t payload = 0;
585     uint16_t seq, nbp = 0;
586     ssize_t written = 0;
587 
588     /* Control packets are 8 bytes long:  */
589     if (size != 8 || packet[0] != 0x80)
590         return 1;
591 
592     seq = ntohs((uint16_t) (packet[4] | packet[5] << 8));
593     nbp = ntohs((uint16_t) (packet[6] | packet[7] << 8));
594     if (nbp <= 0)
595         return 1;
596 
597     /* The marker bit is always set (see rfc3550 for packet structure) ! */
598     payload = packet[1] ^ 0x80;
599     switch (payload) {
600         case PAYLOAD_RETRANSMIT_REQUEST:
601             pa_log_debug("Resending %u packets starting at %u", nbp, seq);
602             written = resend_udp_audio_packets(c, seq, nbp);
603             break;
604         case PAYLOAD_RETRANSMIT_REPLY:
605         default:
606             pa_log_debug("Got an unexpected payload type on control channel (%u) !", payload);
607             break;
608     }
609 
610     return written;
611 }
612 
613 /* Caller has to free the allocated memory region for packet */
build_udp_timing_packet(pa_raop_client * c,const uint32_t data[6],uint64_t received,uint32_t ** packet)614 static size_t build_udp_timing_packet(pa_raop_client *c, const uint32_t data[6], uint64_t received, uint32_t **packet) {
615     const size_t size = sizeof(udp_timing_header) + 24;
616     uint32_t *buffer = NULL;
617     uint64_t transmitted = 0;
618     struct timeval tv;
619 
620     *packet = NULL;
621     if (!(buffer = pa_xmalloc0(size)))
622         return 0;
623 
624     memcpy(buffer, udp_timing_header, sizeof(udp_timing_header));
625     /* Copying originate timestamp from the incoming request packet. */
626     buffer[2] = data[4];
627     buffer[3] = data[5];
628     /* Set the receive timestamp to reception time. */
629     buffer[4] = htonl(received >> 32);
630     buffer[5] = htonl(received & 0xffffffff);
631     /* Set the transmit timestamp to current time. */
632     transmitted = timeval_to_ntp(pa_rtclock_get(&tv));
633     buffer[6] = htonl(transmitted >> 32);
634     buffer[7] = htonl(transmitted & 0xffffffff);
635 
636     *packet = buffer;
637     return size;
638 }
639 
send_udp_timing_packet(pa_raop_client * c,const uint32_t data[6],uint64_t received)640 static ssize_t send_udp_timing_packet(pa_raop_client *c, const uint32_t data[6], uint64_t received) {
641     uint32_t * packet = NULL;
642     ssize_t written = 0;
643     size_t size = 0;
644 
645     size = build_udp_timing_packet(c, data, received, &packet);
646     if (packet != NULL && size > 0) {
647         written = pa_loop_write(c->udp_tfd, packet, size, NULL);
648         pa_xfree(packet);
649     }
650 
651     return written;
652 }
653 
handle_udp_timing_packet(pa_raop_client * c,const uint8_t packet[],ssize_t size)654 static size_t handle_udp_timing_packet(pa_raop_client *c, const uint8_t packet[], ssize_t size) {
655     const uint32_t * data = NULL;
656     uint8_t payload = 0;
657     struct timeval tv;
658     size_t written = 0;
659     uint64_t rci = 0;
660 
661     /* Timing packets are 32 bytes long: 1 x 8 RTP header (no ssrc) + 3 x 8 NTP timestamps */
662     if (size != 32 || packet[0] != 0x80)
663         return 0;
664 
665     rci = timeval_to_ntp(pa_rtclock_get(&tv));
666     data = (uint32_t *) (packet + sizeof(udp_timing_header));
667 
668     /* The marker bit is always set (see rfc3550 for packet structure) ! */
669     payload = packet[1] ^ 0x80;
670     switch (payload) {
671         case PAYLOAD_TIMING_REQUEST:
672             pa_log_debug("Sending timing packet at %" PRIu64 , rci);
673             written = send_udp_timing_packet(c, data, rci);
674             break;
675         case PAYLOAD_TIMING_REPLY:
676         default:
677             pa_log_debug("Got an unexpected payload type on timing channel (%u) !", payload);
678             break;
679     }
680 
681     return written;
682 }
683 
send_initial_udp_timing_packet(pa_raop_client * c)684 static void send_initial_udp_timing_packet(pa_raop_client *c) {
685     uint32_t data[6] = { 0 };
686     struct timeval tv;
687     uint64_t initial_time = 0;
688 
689     initial_time = timeval_to_ntp(pa_rtclock_get(&tv));
690     data[4] = htonl(initial_time >> 32);
691     data[5] = htonl(initial_time & 0xffffffff);
692 
693     send_udp_timing_packet(c, data, initial_time);
694 }
695 
connect_udp_socket(pa_raop_client * c,int fd,uint16_t port)696 static int connect_udp_socket(pa_raop_client *c, int fd, uint16_t port) {
697     struct sockaddr_in sa4;
698 #ifdef HAVE_IPV6
699     struct sockaddr_in6 sa6;
700 #endif
701     struct sockaddr *sa;
702     socklen_t salen;
703     sa_family_t af;
704 
705     pa_zero(sa4);
706 #ifdef HAVE_IPV6
707     pa_zero(sa6);
708 #endif
709     if (inet_pton(AF_INET, c->host, &sa4.sin_addr) > 0) {
710         sa4.sin_family = af = AF_INET;
711         sa4.sin_port = htons(port);
712         sa = (struct sockaddr *) &sa4;
713         salen = sizeof(sa4);
714 #ifdef HAVE_IPV6
715     } else if (inet_pton(AF_INET6, c->host, &sa6.sin6_addr) > 0) {
716         sa6.sin6_family = af = AF_INET6;
717         sa6.sin6_port = htons(port);
718         sa = (struct sockaddr *) &sa6;
719         salen = sizeof(sa6);
720 #endif
721     } else {
722         pa_log("Invalid destination '%s'", c->host);
723         goto fail;
724     }
725 
726     if (fd < 0 && (fd = pa_socket_cloexec(af, SOCK_DGRAM, 0)) < 0) {
727         pa_log("socket() failed: %s", pa_cstrerror(errno));
728         goto fail;
729     }
730 
731     /* If the socket queue is full, let's drop packets */
732     pa_make_udp_socket_low_delay(fd);
733     pa_make_fd_nonblock(fd);
734 
735     if (connect(fd, sa, salen) < 0) {
736         pa_log("connect() failed: %s", pa_cstrerror(errno));
737         goto fail;
738     }
739 
740     pa_log_debug("Connected to %s on port %d (SOCK_DGRAM)", c->host, port);
741     return fd;
742 
743 fail:
744     if (fd >= 0)
745         pa_close(fd);
746 
747     return -1;
748 }
749 
open_bind_udp_socket(pa_raop_client * c,uint16_t * actual_port)750 static int open_bind_udp_socket(pa_raop_client *c, uint16_t *actual_port) {
751     int fd = -1;
752     uint16_t port;
753     struct sockaddr_in sa4;
754 #ifdef HAVE_IPV6
755     struct sockaddr_in6 sa6;
756 #endif
757     struct sockaddr *sa;
758     uint16_t *sa_port;
759     socklen_t salen;
760     sa_family_t af;
761     int one = 1;
762 
763     pa_assert(actual_port);
764 
765     port = *actual_port;
766 
767     pa_zero(sa4);
768 #ifdef HAVE_IPV6
769     pa_zero(sa6);
770 #endif
771     if (inet_pton(AF_INET, pa_rtsp_localip(c->rtsp), &sa4.sin_addr) > 0) {
772         sa4.sin_family = af = AF_INET;
773         sa4.sin_port = htons(port);
774         sa4.sin_addr.s_addr = INADDR_ANY;
775         sa = (struct sockaddr *) &sa4;
776         salen = sizeof(sa4);
777         sa_port = &sa4.sin_port;
778 #ifdef HAVE_IPV6
779     } else if (inet_pton(AF_INET6, pa_rtsp_localip(c->rtsp), &sa6.sin6_addr) > 0) {
780         sa6.sin6_family = af = AF_INET6;
781         sa6.sin6_port = htons(port);
782         sa6.sin6_addr = in6addr_any;
783         sa = (struct sockaddr *) &sa6;
784         salen = sizeof(sa6);
785         sa_port = &sa6.sin6_port;
786 #endif
787     } else {
788         pa_log("Could not determine which address family to use");
789         goto fail;
790     }
791 
792     if ((fd = pa_socket_cloexec(af, SOCK_DGRAM, 0)) < 0) {
793         pa_log("socket() failed: %s", pa_cstrerror(errno));
794         goto fail;
795     }
796 
797 #ifdef SO_TIMESTAMP
798     if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0) {
799         pa_log("setsockopt(SO_TIMESTAMP) failed: %s", pa_cstrerror(errno));
800         goto fail;
801     }
802 #else
803     pa_log("SO_TIMESTAMP unsupported on this platform");
804     goto fail;
805 #endif
806 
807     one = 1;
808     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) {
809         pa_log("setsockopt(SO_REUSEADDR) failed: %s", pa_cstrerror(errno));
810         goto fail;
811     }
812 
813     do {
814         int ret;
815 
816         *sa_port = htons(port);
817         ret = bind(fd, sa, salen);
818         if (!ret)
819             break;
820         if (ret < 0 && errno != EADDRINUSE) {
821             pa_log("bind() failed: %s", pa_cstrerror(errno));
822             goto fail;
823         }
824     } while (++port > 0);
825 
826     if (!port) {
827         pa_log("Could not bind port");
828         goto fail;
829     }
830 
831     pa_log_debug("Socket bound to port %d (SOCK_DGRAM)", port);
832     *actual_port = port;
833 
834     return fd;
835 
836 fail:
837     if (fd >= 0)
838         pa_close(fd);
839 
840     return -1;
841 }
842 
tcp_connection_cb(pa_socket_client * sc,pa_iochannel * io,void * userdata)843 static void tcp_connection_cb(pa_socket_client *sc, pa_iochannel *io, void *userdata) {
844     pa_raop_client *c = userdata;
845 
846     pa_assert(sc);
847     pa_assert(c);
848 
849     pa_socket_client_unref(sc);
850 
851     if (!io) {
852         pa_log("Connection failed: %s", pa_cstrerror(errno));
853         return;
854     }
855 
856     c->tcp_sfd = pa_iochannel_get_send_fd(io);
857     pa_iochannel_set_noclose(io, true);
858     pa_make_tcp_socket_low_delay(c->tcp_sfd);
859 
860     pa_iochannel_free(io);
861 
862     pa_log_debug("Connection established (TCP)");
863 
864     if (c->state_callback)
865         c->state_callback(PA_RAOP_CONNECTED, c->state_userdata);
866 }
867 
rtsp_stream_cb(pa_rtsp_client * rtsp,pa_rtsp_state_t state,pa_rtsp_status_t status,pa_headerlist * headers,void * userdata)868 static void rtsp_stream_cb(pa_rtsp_client *rtsp, pa_rtsp_state_t state, pa_rtsp_status_t status, pa_headerlist *headers, void *userdata) {
869     pa_raop_client *c = userdata;
870 
871     pa_assert(c);
872     pa_assert(rtsp);
873     pa_assert(rtsp == c->rtsp);
874 
875     switch (state) {
876         case STATE_CONNECT: {
877             char *key, *iv, *sdp = NULL;
878             int frames = 0;
879             const char *ip;
880             char *url;
881             int ipv;
882 
883             pa_log_debug("RAOP: CONNECTED");
884 
885             ip = pa_rtsp_localip(c->rtsp);
886             if (pa_is_ip6_address(ip)) {
887                 ipv = 6;
888                 url = pa_sprintf_malloc("rtsp://[%s]/%s", ip, c->sid);
889             } else {
890                 ipv = 4;
891                 url = pa_sprintf_malloc("rtsp://%s/%s", ip, c->sid);
892             }
893             pa_rtsp_set_url(c->rtsp, url);
894 
895             if (c->protocol == PA_RAOP_PROTOCOL_TCP)
896                 frames = FRAMES_PER_TCP_PACKET;
897             else if (c->protocol == PA_RAOP_PROTOCOL_UDP)
898                 frames = FRAMES_PER_UDP_PACKET;
899 
900             switch(c->encryption) {
901                 case PA_RAOP_ENCRYPTION_NONE: {
902                     sdp = pa_sprintf_malloc(
903                         "v=0\r\n"
904                         "o=iTunes %s 0 IN IP%d %s\r\n"
905                         "s=iTunes\r\n"
906                         "c=IN IP%d %s\r\n"
907                         "t=0 0\r\n"
908                         "m=audio 0 RTP/AVP 96\r\n"
909                         "a=rtpmap:96 AppleLossless\r\n"
910                         "a=fmtp:96 %d 0 16 40 10 14 2 255 0 0 44100\r\n",
911                         c->sid, ipv, ip, ipv, c->host, frames);
912 
913                     break;
914                 }
915 
916                 case PA_RAOP_ENCRYPTION_RSA:
917                 case PA_RAOP_ENCRYPTION_FAIRPLAY:
918                 case PA_RAOP_ENCRYPTION_MFISAP:
919                 case PA_RAOP_ENCRYPTION_FAIRPLAY_SAP25: {
920                     key = pa_raop_secret_get_key(c->secret);
921                     if (!key) {
922                         pa_log("pa_raop_secret_get_key() failed.");
923                         pa_rtsp_disconnect(rtsp);
924                         /* FIXME: This is an unrecoverable failure. We should notify
925                          * the pa_raop_client owner so that it could shut itself
926                          * down. */
927                         goto connect_finish;
928                     }
929 
930                     iv = pa_raop_secret_get_iv(c->secret);
931 
932                     sdp = pa_sprintf_malloc(
933                         "v=0\r\n"
934                         "o=iTunes %s 0 IN IP%d %s\r\n"
935                         "s=iTunes\r\n"
936                         "c=IN IP%d %s\r\n"
937                         "t=0 0\r\n"
938                         "m=audio 0 RTP/AVP 96\r\n"
939                         "a=rtpmap:96 AppleLossless\r\n"
940                         "a=fmtp:96 %d 0 16 40 10 14 2 255 0 0 44100\r\n"
941                         "a=rsaaeskey:%s\r\n"
942                         "a=aesiv:%s\r\n",
943                         c->sid, ipv, ip, ipv, c->host, frames, key, iv);
944 
945                     pa_xfree(key);
946                     pa_xfree(iv);
947                     break;
948                 }
949             }
950 
951             pa_rtsp_announce(c->rtsp, sdp);
952 
953 connect_finish:
954             pa_xfree(sdp);
955             pa_xfree(url);
956             break;
957         }
958 
959         case STATE_OPTIONS: {
960             pa_log_debug("RAOP: OPTIONS (stream cb)");
961 
962             break;
963         }
964 
965         case STATE_ANNOUNCE: {
966             uint16_t cport = DEFAULT_UDP_CONTROL_PORT;
967             uint16_t tport = DEFAULT_UDP_TIMING_PORT;
968             char *trs = NULL;
969 
970             pa_log_debug("RAOP: ANNOUNCE");
971 
972             if (c->protocol == PA_RAOP_PROTOCOL_TCP) {
973                 trs = pa_sprintf_malloc(
974                     "RTP/AVP/TCP;unicast;interleaved=0-1;mode=record");
975             } else if (c->protocol == PA_RAOP_PROTOCOL_UDP) {
976                 c->udp_cfd = open_bind_udp_socket(c, &cport);
977                 c->udp_tfd  = open_bind_udp_socket(c, &tport);
978                 if (c->udp_cfd < 0 || c->udp_tfd < 0)
979                     goto annonce_error;
980 
981                 trs = pa_sprintf_malloc(
982                     "RTP/AVP/UDP;unicast;interleaved=0-1;mode=record;"
983                     "control_port=%d;timing_port=%d",
984                     cport, tport);
985             }
986 
987             pa_rtsp_setup(c->rtsp, trs);
988 
989             pa_xfree(trs);
990             break;
991 
992         annonce_error:
993             if (c->udp_cfd >= 0)
994                 pa_close(c->udp_cfd);
995             c->udp_cfd = -1;
996             if (c->udp_tfd >= 0)
997                 pa_close(c->udp_tfd);
998             c->udp_tfd = -1;
999 
1000             pa_rtsp_client_free(c->rtsp);
1001 
1002             pa_log_error("Aborting RTSP announce, failed creating required sockets");
1003 
1004             c->rtsp = NULL;
1005             pa_xfree(trs);
1006             break;
1007         }
1008 
1009         case STATE_SETUP: {
1010             pa_socket_client *sc = NULL;
1011             uint32_t sport = DEFAULT_UDP_AUDIO_PORT;
1012             uint32_t cport =0, tport = 0;
1013             char *ajs, *token, *pc, *trs;
1014             const char *token_state = NULL;
1015             char delimiters[] = ";";
1016 
1017             pa_log_debug("RAOP: SETUP");
1018 
1019             ajs = pa_xstrdup(pa_headerlist_gets(headers, "Audio-Jack-Status"));
1020 
1021             if (ajs) {
1022                 c->jack_type = JACK_TYPE_ANALOG;
1023                 c->jack_status = JACK_STATUS_DISCONNECTED;
1024 
1025                 while ((token = pa_split(ajs, delimiters, &token_state))) {
1026                     if ((pc = strstr(token, "="))) {
1027                       *pc = 0;
1028                       if (pa_streq(token, "type") && pa_streq(pc + 1, "digital"))
1029                           c->jack_type = JACK_TYPE_DIGITAL;
1030                     } else {
1031                         if (pa_streq(token, "connected"))
1032                             c->jack_status = JACK_STATUS_CONNECTED;
1033                     }
1034                     pa_xfree(token);
1035                 }
1036 
1037             } else {
1038                 pa_log_warn("\"Audio-Jack-Status\" missing in RTSP setup response");
1039             }
1040 
1041             sport = pa_rtsp_serverport(c->rtsp);
1042             if (sport <= 0)
1043                 goto setup_error;
1044 
1045             token_state = NULL;
1046             if (c->protocol == PA_RAOP_PROTOCOL_TCP) {
1047                 if (!(sc = pa_socket_client_new_string(c->core->mainloop, true, c->host, sport)))
1048                     goto setup_error;
1049 
1050                 pa_socket_client_ref(sc);
1051                 pa_socket_client_set_callback(sc, tcp_connection_cb, c);
1052 
1053                 pa_socket_client_unref(sc);
1054                 sc = NULL;
1055             } else if (c->protocol == PA_RAOP_PROTOCOL_UDP) {
1056                 trs = pa_xstrdup(pa_headerlist_gets(headers, "Transport"));
1057 
1058                 if (trs) {
1059                     /* Now parse out the server port component of the response. */
1060                     while ((token = pa_split(trs, delimiters, &token_state))) {
1061                         if ((pc = strstr(token, "="))) {
1062                             *pc = 0;
1063                             if (pa_streq(token, "control_port")) {
1064                                 if (pa_atou(pc + 1, &cport) < 0)
1065                                     goto setup_error_parse;
1066                             }
1067                             if (pa_streq(token, "timing_port")) {
1068                                 if (pa_atou(pc + 1, &tport) < 0)
1069                                     goto setup_error_parse;
1070                             }
1071                             *pc = '=';
1072                         }
1073                         pa_xfree(token);
1074                     }
1075                     pa_xfree(trs);
1076                 } else {
1077                     pa_log_warn("\"Transport\" missing in RTSP setup response");
1078                 }
1079 
1080                 if (cport <= 0 || tport <= 0)
1081                     goto setup_error;
1082 
1083                 if ((c->udp_sfd = connect_udp_socket(c, -1, sport)) <= 0)
1084                     goto setup_error;
1085                 if ((c->udp_cfd = connect_udp_socket(c, c->udp_cfd, cport)) <= 0)
1086                     goto setup_error;
1087                 if ((c->udp_tfd = connect_udp_socket(c, c->udp_tfd, tport)) <= 0)
1088                     goto setup_error;
1089 
1090                 pa_log_debug("Connection established (UDP;control_port=%d;timing_port=%d)", cport, tport);
1091 
1092                 /* Send an initial UDP packet so a connection tracking firewall
1093                  * knows the src_ip:src_port <-> dest_ip:dest_port relation
1094                  * and accepts the incoming timing packets.
1095                  */
1096                 send_initial_udp_timing_packet(c);
1097                 pa_log_debug("Sent initial timing packet to UDP port %d", tport);
1098 
1099                 if (c->state_callback)
1100                     c->state_callback(PA_RAOP_CONNECTED, c->state_userdata);
1101             }
1102 
1103             pa_rtsp_record(c->rtsp, &c->seq, &c->rtptime);
1104 
1105             pa_xfree(ajs);
1106             break;
1107 
1108         setup_error_parse:
1109             pa_log("Failed parsing server port components");
1110             pa_xfree(token);
1111             pa_xfree(trs);
1112             /* fall-thru */
1113         setup_error:
1114             if (c->tcp_sfd >= 0)
1115                 pa_close(c->tcp_sfd);
1116             c->tcp_sfd = -1;
1117 
1118             if (c->udp_sfd >= 0)
1119                 pa_close(c->udp_sfd);
1120             c->udp_sfd = -1;
1121 
1122             c->udp_cfd = c->udp_tfd = -1;
1123 
1124             pa_rtsp_client_free(c->rtsp);
1125 
1126             pa_log_error("aborting RTSP setup, failed creating required sockets");
1127 
1128             if (c->state_callback)
1129                 c->state_callback(PA_RAOP_DISCONNECTED, c->state_userdata);
1130 
1131             c->rtsp = NULL;
1132             break;
1133         }
1134 
1135         case STATE_RECORD: {
1136             int32_t latency = 0;
1137             uint32_t ssrc;
1138             char *alt;
1139 
1140             pa_log_debug("RAOP: RECORD");
1141 
1142             alt = pa_xstrdup(pa_headerlist_gets(headers, "Audio-Latency"));
1143             if (alt) {
1144                 if (pa_atoi(alt, &latency) < 0)
1145                     pa_log("Failed to parse audio latency");
1146             }
1147 
1148             pa_raop_packet_buffer_reset(c->pbuf, c->seq);
1149 
1150             pa_random(&ssrc, sizeof(ssrc));
1151             c->is_first_packet = true;
1152             c->is_recording = true;
1153             c->sync_count = 0;
1154             c->ssrc = ssrc;
1155 
1156             if (c->state_callback)
1157                 c->state_callback((int) PA_RAOP_RECORDING, c->state_userdata);
1158 
1159             pa_xfree(alt);
1160             break;
1161         }
1162 
1163         case STATE_SET_PARAMETER: {
1164             pa_log_debug("RAOP: SET_PARAMETER");
1165 
1166             break;
1167         }
1168 
1169         case STATE_FLUSH: {
1170             pa_log_debug("RAOP: FLUSHED");
1171 
1172             break;
1173         }
1174 
1175         case STATE_TEARDOWN: {
1176             pa_log_debug("RAOP: TEARDOWN");
1177 
1178             if (c->tcp_sfd >= 0)
1179                 pa_close(c->tcp_sfd);
1180             c->tcp_sfd = -1;
1181 
1182             if (c->udp_sfd >= 0)
1183                 pa_close(c->udp_sfd);
1184             c->udp_sfd = -1;
1185 
1186             /* Polling sockets will be closed by sink */
1187             c->udp_cfd = c->udp_tfd = -1;
1188             c->tcp_sfd = -1;
1189 
1190             pa_rtsp_client_free(c->rtsp);
1191             pa_xfree(c->sid);
1192             c->rtsp = NULL;
1193             c->sid = NULL;
1194 
1195             if (c->state_callback)
1196                 c->state_callback(PA_RAOP_DISCONNECTED, c->state_userdata);
1197 
1198             break;
1199         }
1200 
1201         case STATE_DISCONNECTED: {
1202             pa_log_debug("RAOP: DISCONNECTED");
1203 
1204             c->is_recording = false;
1205 
1206             if (c->tcp_sfd >= 0)
1207                 pa_close(c->tcp_sfd);
1208             c->tcp_sfd = -1;
1209 
1210             if (c->udp_sfd >= 0)
1211                 pa_close(c->udp_sfd);
1212             c->udp_sfd = -1;
1213 
1214             /* Polling sockets will be closed by sink */
1215             c->udp_cfd = c->udp_tfd = -1;
1216             c->tcp_sfd = -1;
1217 
1218             pa_log_error("RTSP control channel closed (disconnected)");
1219 
1220             pa_rtsp_client_free(c->rtsp);
1221             pa_xfree(c->sid);
1222             c->rtsp = NULL;
1223             c->sid = NULL;
1224 
1225             if (c->state_callback)
1226                 c->state_callback((int) PA_RAOP_DISCONNECTED, c->state_userdata);
1227 
1228             break;
1229         }
1230     }
1231 }
1232 
rtsp_auth_cb(pa_rtsp_client * rtsp,pa_rtsp_state_t state,pa_rtsp_status_t status,pa_headerlist * headers,void * userdata)1233 static void rtsp_auth_cb(pa_rtsp_client *rtsp, pa_rtsp_state_t state, pa_rtsp_status_t status, pa_headerlist *headers, void *userdata) {
1234     pa_raop_client *c = userdata;
1235 
1236     pa_assert(c);
1237     pa_assert(rtsp);
1238     pa_assert(rtsp == c->rtsp);
1239 
1240     switch (state) {
1241         case STATE_CONNECT: {
1242             char *sci = NULL, *sac = NULL;
1243             uint8_t rac[APPLE_CHALLENGE_LENGTH];
1244             struct {
1245                 uint32_t ci1;
1246                 uint32_t ci2;
1247             } rci;
1248 
1249             pa_random(&rci, sizeof(rci));
1250             /* Generate a random Client-Instance number */
1251             sci = pa_sprintf_malloc("%08x%08x",rci.ci1, rci.ci2);
1252             pa_rtsp_add_header(c->rtsp, "Client-Instance", sci);
1253 
1254             pa_random(rac, APPLE_CHALLENGE_LENGTH);
1255             /* Generate a random Apple-Challenge key */
1256             pa_raop_base64_encode(rac, APPLE_CHALLENGE_LENGTH, &sac);
1257             rtrim_char(sac, '=');
1258             pa_rtsp_add_header(c->rtsp, "Apple-Challenge", sac);
1259 
1260             pa_rtsp_options(c->rtsp);
1261 
1262             pa_xfree(sac);
1263             pa_xfree(sci);
1264             break;
1265         }
1266 
1267         case STATE_OPTIONS: {
1268             static bool waiting = false;
1269             const char *current = NULL;
1270             char space[] = " ";
1271             char *token, *ath = NULL;
1272             char *publ, *wath, *mth = NULL, *val;
1273             char *realm = NULL, *nonce = NULL, *response = NULL;
1274             char comma[] = ",";
1275 
1276             pa_log_debug("RAOP: OPTIONS (auth cb)");
1277             /* We do not consider the Apple-Response */
1278             pa_rtsp_remove_header(c->rtsp, "Apple-Challenge");
1279 
1280             if (STATUS_UNAUTHORIZED == status) {
1281                 wath = pa_xstrdup(pa_headerlist_gets(headers, "WWW-Authenticate"));
1282                 if (true == waiting) {
1283                     pa_xfree(wath);
1284                     goto fail;
1285                 }
1286 
1287                 if (wath) {
1288                     mth = pa_split(wath, space, &current);
1289                     while ((token = pa_split(wath, comma, &current))) {
1290                         if ((val = strstr(token, "="))) {
1291                             if (NULL == realm && val > strstr(token, "realm"))
1292                                 realm = pa_xstrdup(val + 2);
1293                             else if (NULL == nonce && val > strstr(token, "nonce"))
1294                                 nonce = pa_xstrdup(val + 2);
1295                         }
1296 
1297                         pa_xfree(token);
1298                     }
1299                 }
1300 
1301                 if (pa_safe_streq(mth, "Basic") && realm) {
1302                     rtrim_char(realm, '\"');
1303 
1304                     pa_raop_basic_response(DEFAULT_USER_NAME, c->password, &response);
1305                     ath = pa_sprintf_malloc("Basic %s",
1306                         response);
1307                 } else if (pa_safe_streq(mth, "Digest") && realm && nonce) {
1308                     rtrim_char(realm, '\"');
1309                     rtrim_char(nonce, '\"');
1310 
1311                     pa_raop_digest_response(DEFAULT_USER_NAME, realm, c->password, nonce, "*", &response);
1312                     ath = pa_sprintf_malloc("Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"*\", response=\"%s\"",
1313                         DEFAULT_USER_NAME, realm, nonce,
1314                         response);
1315                 } else {
1316                     pa_log_error("unsupported authentication method: %s", mth);
1317                     pa_xfree(realm);
1318                     pa_xfree(nonce);
1319                     pa_xfree(wath);
1320                     pa_xfree(mth);
1321                     goto error;
1322                 }
1323 
1324                 pa_xfree(response);
1325                 pa_xfree(realm);
1326                 pa_xfree(nonce);
1327                 pa_xfree(wath);
1328                 pa_xfree(mth);
1329 
1330                 pa_rtsp_add_header(c->rtsp, "Authorization", ath);
1331                 pa_xfree(ath);
1332 
1333                 waiting = true;
1334                 pa_rtsp_options(c->rtsp);
1335                 break;
1336             }
1337 
1338             if (STATUS_OK == status) {
1339                 publ = pa_xstrdup(pa_headerlist_gets(headers, "Public"));
1340                 c->sci = pa_xstrdup(pa_rtsp_get_header(c->rtsp, "Client-Instance"));
1341 
1342                 if (c->password)
1343                     pa_xfree(c->password);
1344                 pa_xfree(publ);
1345                 c->password = NULL;
1346             }
1347 
1348             pa_rtsp_client_free(c->rtsp);
1349             c->rtsp = NULL;
1350             /* Ensure everything is cleaned before calling the callback, otherwise it may raise a crash */
1351             if (c->state_callback)
1352                 c->state_callback((int) PA_RAOP_AUTHENTICATED, c->state_userdata);
1353 
1354             waiting = false;
1355             break;
1356 
1357         fail:
1358             if (c->state_callback)
1359                 c->state_callback((int) PA_RAOP_DISCONNECTED, c->state_userdata);
1360             pa_rtsp_client_free(c->rtsp);
1361             c->rtsp = NULL;
1362 
1363             pa_log_error("aborting authentication, wrong password");
1364 
1365             waiting = false;
1366             break;
1367 
1368         error:
1369             if (c->state_callback)
1370                 c->state_callback((int) PA_RAOP_DISCONNECTED, c->state_userdata);
1371             pa_rtsp_client_free(c->rtsp);
1372             c->rtsp = NULL;
1373 
1374             pa_log_error("aborting authentication, unexpected failure");
1375 
1376             waiting = false;
1377             break;
1378         }
1379 
1380         case STATE_ANNOUNCE:
1381         case STATE_SETUP:
1382         case STATE_RECORD:
1383         case STATE_SET_PARAMETER:
1384         case STATE_FLUSH:
1385         case STATE_TEARDOWN:
1386         case STATE_DISCONNECTED:
1387         default: {
1388             if (c->state_callback)
1389                 c->state_callback((int) PA_RAOP_DISCONNECTED, c->state_userdata);
1390             pa_rtsp_client_free(c->rtsp);
1391             c->rtsp = NULL;
1392 
1393             if (c->sci)
1394                 pa_xfree(c->sci);
1395             c->sci = NULL;
1396 
1397             break;
1398         }
1399     }
1400 }
1401 
1402 
pa_raop_client_disconnect(pa_raop_client * c)1403 void pa_raop_client_disconnect(pa_raop_client *c) {
1404     c->is_recording = false;
1405 
1406     if (c->tcp_sfd >= 0)
1407         pa_close(c->tcp_sfd);
1408     c->tcp_sfd = -1;
1409 
1410     if (c->udp_sfd >= 0)
1411         pa_close(c->udp_sfd);
1412     c->udp_sfd = -1;
1413 
1414     /* Polling sockets will be closed by sink */
1415     c->udp_cfd = c->udp_tfd = -1;
1416     c->tcp_sfd = -1;
1417 
1418     pa_log_error("RTSP control channel closed (disconnected)");
1419 
1420     if (c->rtsp)
1421         pa_rtsp_client_free(c->rtsp);
1422     if (c->sid)
1423         pa_xfree(c->sid);
1424     c->rtsp = NULL;
1425     c->sid = NULL;
1426 
1427     if (c->state_callback)
1428         c->state_callback((int) PA_RAOP_DISCONNECTED, c->state_userdata);
1429 
1430 }
1431 
1432 
pa_raop_client_new(pa_core * core,const char * host,pa_raop_protocol_t protocol,pa_raop_encryption_t encryption,pa_raop_codec_t codec,bool autoreconnect)1433 pa_raop_client* pa_raop_client_new(pa_core *core, const char *host, pa_raop_protocol_t protocol,
1434                                    pa_raop_encryption_t encryption, pa_raop_codec_t codec, bool autoreconnect) {
1435     pa_raop_client *c;
1436 
1437     pa_parsed_address a;
1438     pa_sample_spec ss;
1439     size_t size = 2;
1440 
1441     pa_assert(core);
1442     pa_assert(host);
1443 
1444     if (pa_parse_address(host, &a) < 0)
1445         return NULL;
1446 
1447     if (a.type == PA_PARSED_ADDRESS_UNIX) {
1448         pa_xfree(a.path_or_host);
1449         return NULL;
1450     }
1451 
1452     c = pa_xnew0(pa_raop_client, 1);
1453     c->core = core;
1454     c->host = a.path_or_host; /* Will eventually be freed on destruction of c */
1455     if (a.port > 0)
1456         c->port = a.port;
1457     else
1458         c->port = DEFAULT_RAOP_PORT;
1459     c->rtsp = NULL;
1460     c->sci = c->sid = NULL;
1461     c->password = NULL;
1462     c->autoreconnect = autoreconnect;
1463 
1464     c->protocol = protocol;
1465     c->encryption = encryption;
1466     c->codec = codec;
1467 
1468     c->tcp_sfd = -1;
1469 
1470     c->udp_sfd = -1;
1471     c->udp_cfd = -1;
1472     c->udp_tfd = -1;
1473 
1474     c->secret = NULL;
1475     if (c->encryption != PA_RAOP_ENCRYPTION_NONE)
1476         c->secret = pa_raop_secret_new();
1477 
1478     ss = core->default_sample_spec;
1479     if (c->protocol == PA_RAOP_PROTOCOL_UDP)
1480         size = RTX_BUFFERING_SECONDS * ss.rate / FRAMES_PER_UDP_PACKET;
1481 
1482     c->is_recording = false;
1483     c->is_first_packet = true;
1484     /* Packet sync interval should be around 1s (UDP only) */
1485     c->sync_interval = ss.rate / FRAMES_PER_UDP_PACKET;
1486     c->sync_count = 0;
1487 
1488     c->pbuf = pa_raop_packet_buffer_new(c->core->mempool, size);
1489 
1490     return c;
1491 }
1492 
pa_raop_client_free(pa_raop_client * c)1493 void pa_raop_client_free(pa_raop_client *c) {
1494     pa_assert(c);
1495 
1496     pa_raop_packet_buffer_free(c->pbuf);
1497 
1498     pa_xfree(c->sid);
1499     pa_xfree(c->sci);
1500     if (c->secret)
1501         pa_raop_secret_free(c->secret);
1502     pa_xfree(c->password);
1503     c->sci = c->sid = NULL;
1504     c->password = NULL;
1505     c->secret = NULL;
1506 
1507     if (c->rtsp)
1508         pa_rtsp_client_free(c->rtsp);
1509     c->rtsp = NULL;
1510 
1511     pa_xfree(c->host);
1512     pa_xfree(c);
1513 }
1514 
pa_raop_client_authenticate(pa_raop_client * c,const char * password)1515 int pa_raop_client_authenticate (pa_raop_client *c, const char *password) {
1516     int rv = 0;
1517 
1518     pa_assert(c);
1519 
1520     if (c->rtsp || c->password) {
1521         pa_log_debug("Authentication/Connection already in progress...");
1522         return 0;
1523     }
1524 
1525     c->password = NULL;
1526     if (password)
1527         c->password = pa_xstrdup(password);
1528     c->rtsp = pa_rtsp_client_new(c->core->mainloop, c->host, c->port, DEFAULT_USER_AGENT, c->autoreconnect);
1529 
1530     pa_assert(c->rtsp);
1531 
1532     pa_rtsp_set_callback(c->rtsp, rtsp_auth_cb, c);
1533     rv = pa_rtsp_connect(c->rtsp);
1534     return rv;
1535 }
1536 
pa_raop_client_is_authenticated(pa_raop_client * c)1537 bool pa_raop_client_is_authenticated(pa_raop_client *c) {
1538     pa_assert(c);
1539 
1540     return (c->sci != NULL);
1541 }
1542 
pa_raop_client_announce(pa_raop_client * c)1543 int pa_raop_client_announce(pa_raop_client *c) {
1544     uint32_t sid;
1545     int rv = 0;
1546 
1547     pa_assert(c);
1548 
1549     if (c->rtsp) {
1550         pa_log_debug("Connection already in progress...");
1551         return 0;
1552     } else if (!c->sci) {
1553         pa_log_debug("ANNOUNCE requires a preliminary authentication");
1554         return 1;
1555     }
1556 
1557     c->rtsp = pa_rtsp_client_new(c->core->mainloop, c->host, c->port, DEFAULT_USER_AGENT, c->autoreconnect);
1558 
1559     pa_assert(c->rtsp);
1560 
1561     c->sync_count = 0;
1562     c->is_recording = false;
1563     c->is_first_packet = true;
1564     pa_random(&sid, sizeof(sid));
1565     c->sid = pa_sprintf_malloc("%u", sid);
1566     pa_rtsp_set_callback(c->rtsp, rtsp_stream_cb, c);
1567 
1568     rv = pa_rtsp_connect(c->rtsp);
1569     return rv;
1570 }
1571 
pa_raop_client_is_alive(pa_raop_client * c)1572 bool pa_raop_client_is_alive(pa_raop_client *c) {
1573     pa_assert(c);
1574 
1575     if (!c->rtsp || !c->sci) {
1576         pa_log_debug("Not alive, connection not established yet...");
1577         return false;
1578     }
1579 
1580     switch (c->protocol) {
1581         case PA_RAOP_PROTOCOL_TCP:
1582             if (c->tcp_sfd >= 0)
1583                 return true;
1584             break;
1585         case PA_RAOP_PROTOCOL_UDP:
1586             if (c->udp_sfd >= 0)
1587                 return true;
1588             break;
1589         default:
1590             break;
1591     }
1592 
1593     return false;
1594 }
1595 
pa_raop_client_can_stream(pa_raop_client * c)1596 bool pa_raop_client_can_stream(pa_raop_client *c) {
1597     pa_assert(c);
1598 
1599     if (!c->rtsp || !c->sci) {
1600         return false;
1601     }
1602 
1603     switch (c->protocol) {
1604         case PA_RAOP_PROTOCOL_TCP:
1605             if (c->tcp_sfd >= 0 && c->is_recording)
1606                 return true;
1607             break;
1608         case PA_RAOP_PROTOCOL_UDP:
1609             if (c->udp_sfd >= 0 && c->is_recording)
1610                 return true;
1611             break;
1612         default:
1613             break;
1614     }
1615 
1616     return false;
1617 }
1618 
pa_raop_client_is_recording(pa_raop_client * c)1619 bool pa_raop_client_is_recording(pa_raop_client *c) {
1620     return c->is_recording;
1621 }
1622 
pa_raop_client_stream(pa_raop_client * c)1623 int pa_raop_client_stream(pa_raop_client *c) {
1624     int rv = 0;
1625 
1626     pa_assert(c);
1627 
1628     if (!c->rtsp || !c->sci) {
1629         pa_log_debug("Streaming's impossible, connection not established yet...");
1630         return 0;
1631     }
1632 
1633     switch (c->protocol) {
1634         case PA_RAOP_PROTOCOL_TCP:
1635             if (c->tcp_sfd >= 0 && !c->is_recording) {
1636                 c->is_recording = true;
1637                 c->is_first_packet = true;
1638                 c->sync_count = 0;
1639             }
1640             break;
1641         case PA_RAOP_PROTOCOL_UDP:
1642             if (c->udp_sfd >= 0 && !c->is_recording) {
1643                 c->is_recording = true;
1644                 c->is_first_packet = true;
1645                 c->sync_count = 0;
1646             }
1647             break;
1648         default:
1649             rv = 1;
1650             break;
1651     }
1652 
1653     return rv;
1654 }
1655 
pa_raop_client_set_volume(pa_raop_client * c,pa_volume_t volume)1656 int pa_raop_client_set_volume(pa_raop_client *c, pa_volume_t volume) {
1657     char *param;
1658     int rv = 0;
1659     double db;
1660 
1661     pa_assert(c);
1662 
1663     if (!c->rtsp) {
1664         pa_log_debug("Cannot SET_PARAMETER, connection not established yet...");
1665         return 0;
1666     } else if (!c->sci) {
1667         pa_log_debug("SET_PARAMETER requires a preliminary authentication");
1668         return 1;
1669     }
1670 
1671     db = pa_sw_volume_to_dB(volume);
1672     if (db < VOLUME_MIN)
1673         db = VOLUME_MIN;
1674     else if (db > VOLUME_MAX)
1675         db = VOLUME_MAX;
1676 
1677     pa_log_debug("volume=%u db=%.6f", volume, db);
1678 
1679     param = pa_sprintf_malloc("volume: %0.6f\r\n", db);
1680     /* We just hit and hope, cannot wait for the callback. */
1681     if (c->rtsp != NULL && pa_rtsp_exec_ready(c->rtsp))
1682         rv = pa_rtsp_setparameter(c->rtsp, param);
1683 
1684     pa_xfree(param);
1685     return rv;
1686 }
1687 
pa_raop_client_flush(pa_raop_client * c)1688 int pa_raop_client_flush(pa_raop_client *c) {
1689     int rv = 0;
1690 
1691     pa_assert(c);
1692 
1693     if (!c->rtsp || !pa_rtsp_exec_ready(c->rtsp)) {
1694         pa_log_debug("Cannot FLUSH, connection not established yet...)");
1695         return 0;
1696     } else if (!c->sci) {
1697         pa_log_debug("FLUSH requires a preliminary authentication");
1698         return 1;
1699     }
1700 
1701     c->is_recording = false;
1702 
1703     rv = pa_rtsp_flush(c->rtsp, c->seq, c->rtptime);
1704     return rv;
1705 }
1706 
pa_raop_client_teardown(pa_raop_client * c)1707 int pa_raop_client_teardown(pa_raop_client *c) {
1708     int rv = 0;
1709 
1710     pa_assert(c);
1711 
1712     if (!c->rtsp) {
1713         pa_log_debug("Cannot TEARDOWN, connection not established yet...");
1714         return 0;
1715     } else if (!c->sci) {
1716         pa_log_debug("TEARDOWN requires a preliminary authentication");
1717         return 1;
1718     }
1719 
1720     c->is_recording = false;
1721 
1722     rv = pa_rtsp_teardown(c->rtsp);
1723     return rv;
1724 }
1725 
pa_raop_client_get_frames_per_block(pa_raop_client * c,size_t * frames)1726 void pa_raop_client_get_frames_per_block(pa_raop_client *c, size_t *frames) {
1727     pa_assert(c);
1728     pa_assert(frames);
1729 
1730     switch (c->protocol) {
1731         case PA_RAOP_PROTOCOL_TCP:
1732             *frames = FRAMES_PER_TCP_PACKET;
1733             break;
1734         case PA_RAOP_PROTOCOL_UDP:
1735             *frames = FRAMES_PER_UDP_PACKET;
1736             break;
1737         default:
1738             *frames = 0;
1739             break;
1740     }
1741 }
1742 
pa_raop_client_register_pollfd(pa_raop_client * c,pa_rtpoll * poll,pa_rtpoll_item ** poll_item)1743 bool pa_raop_client_register_pollfd(pa_raop_client *c, pa_rtpoll *poll, pa_rtpoll_item **poll_item) {
1744     struct pollfd *pollfd = NULL;
1745     pa_rtpoll_item *item = NULL;
1746     bool oob = true;
1747 
1748     pa_assert(c);
1749     pa_assert(poll);
1750     pa_assert(poll_item);
1751 
1752     switch (c->protocol) {
1753         case PA_RAOP_PROTOCOL_TCP:
1754             item = pa_rtpoll_item_new(poll, PA_RTPOLL_NEVER, 1);
1755             pollfd = pa_rtpoll_item_get_pollfd(item, NULL);
1756             pollfd->fd = c->tcp_sfd;
1757             pollfd->events = POLLOUT;
1758             pollfd->revents = 0;
1759             *poll_item = item;
1760             oob = false;
1761             break;
1762         case PA_RAOP_PROTOCOL_UDP:
1763             item = pa_rtpoll_item_new(poll, PA_RTPOLL_NEVER, 2);
1764             pollfd = pa_rtpoll_item_get_pollfd(item, NULL);
1765             pollfd->fd = c->udp_cfd;
1766             pollfd->events = POLLIN | POLLPRI;
1767             pollfd->revents = 0;
1768             pollfd++;
1769             pollfd->fd = c->udp_tfd;
1770             pollfd->events = POLLIN | POLLPRI;
1771             pollfd->revents = 0;
1772             *poll_item = item;
1773             oob = true;
1774             break;
1775         default:
1776             *poll_item = NULL;
1777             break;
1778     }
1779 
1780     return oob;
1781 }
1782 
pa_raop_client_is_timing_fd(pa_raop_client * c,const int fd)1783 bool pa_raop_client_is_timing_fd(pa_raop_client *c, const int fd) {
1784     return fd == c->udp_tfd;
1785 }
1786 
pa_raop_client_adjust_volume(pa_raop_client * c,pa_volume_t volume)1787 pa_volume_t pa_raop_client_adjust_volume(pa_raop_client *c, pa_volume_t volume) {
1788     double minv, maxv;
1789 
1790     pa_assert(c);
1791 
1792     if (c->protocol != PA_RAOP_PROTOCOL_UDP)
1793         return volume;
1794 
1795     maxv = pa_sw_volume_from_dB(0.0);
1796     minv = maxv * pow(10.0, VOLUME_DEF / 60.0);
1797 
1798     /* Adjust volume so that it fits into VOLUME_DEF <= v <= 0 dB */
1799     return volume - volume * (minv / maxv) + minv;
1800 }
1801 
pa_raop_client_handle_oob_packet(pa_raop_client * c,const int fd,const uint8_t packet[],ssize_t size)1802 void pa_raop_client_handle_oob_packet(pa_raop_client *c, const int fd, const uint8_t packet[], ssize_t size) {
1803     pa_assert(c);
1804     pa_assert(fd >= 0);
1805     pa_assert(packet);
1806 
1807     if (c->protocol == PA_RAOP_PROTOCOL_UDP) {
1808         if (fd == c->udp_cfd) {
1809             pa_log_debug("Received UDP control packet...");
1810             handle_udp_control_packet(c, packet, size);
1811         } else if (fd == c->udp_tfd) {
1812             pa_log_debug("Received UDP timing packet...");
1813             handle_udp_timing_packet(c, packet, size);
1814         }
1815     }
1816 }
1817 
pa_raop_client_send_audio_packet(pa_raop_client * c,pa_memchunk * block,size_t offset)1818 ssize_t pa_raop_client_send_audio_packet(pa_raop_client *c, pa_memchunk *block, size_t offset) {
1819     ssize_t written = 0;
1820 
1821     pa_assert(c);
1822     pa_assert(block);
1823 
1824     /* Sync RTP & NTP timestamp if required (UDP). */
1825     if (c->protocol == PA_RAOP_PROTOCOL_UDP) {
1826         c->sync_count++;
1827         if (c->is_first_packet || c->sync_count >= c->sync_interval) {
1828             send_udp_sync_packet(c, c->rtptime);
1829             c->sync_count = 0;
1830         }
1831     }
1832 
1833     switch (c->protocol) {
1834         case PA_RAOP_PROTOCOL_TCP:
1835             written = send_tcp_audio_packet(c, block, offset);
1836             break;
1837         case PA_RAOP_PROTOCOL_UDP:
1838             written = send_udp_audio_packet(c, block, offset);
1839             break;
1840         default:
1841             written = -1;
1842             break;
1843     }
1844 
1845     c->is_first_packet = false;
1846     return written;
1847 }
1848 
pa_raop_client_set_state_callback(pa_raop_client * c,pa_raop_client_state_cb_t callback,void * userdata)1849 void pa_raop_client_set_state_callback(pa_raop_client *c, pa_raop_client_state_cb_t callback, void *userdata) {
1850     pa_assert(c);
1851 
1852     c->state_callback = callback;
1853     c->state_userdata = userdata;
1854 }
1855