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