4 This file is part of PulseAudio.
6 Copyright 2008 Colin Guthrie
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 of the License,
11 or (at your option) any later version.
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.
18 You should have received a copy of the GNU Lesser General Public License
19 along with PulseAudio; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
32 #include <arpa/inet.h>
34 #include <sys/ioctl.h>
36 #ifdef HAVE_SYS_FILIO_H
37 #include <sys/filio.h>
40 /* TODO: Replace OpenSSL with NSS */
41 #include <openssl/err.h>
42 #include <openssl/rand.h>
43 #include <openssl/aes.h>
44 #include <openssl/rsa.h>
45 #include <openssl/engine.h>
47 #include <pulse/xmalloc.h>
49 #include <pulsecore/core-error.h>
50 #include <pulsecore/core-util.h>
51 #include <pulsecore/socket-util.h>
52 #include <pulsecore/log.h>
53 #include <pulsecore/macro.h>
54 #include <pulsecore/strbuf.h>
55 #include <pulsecore/random.h>
56 #include <pulsecore/poll.h>
58 #include "raop_client.h"
59 #include "rtsp_client.h"
62 #define AES_CHUNKSIZE 16
64 #define JACK_STATUS_DISCONNECTED 0
65 #define JACK_STATUS_CONNECTED 1
67 #define JACK_TYPE_ANALOG 0
68 #define JACK_TYPE_DIGITAL 1
70 #define VOLUME_DEF -30
71 #define VOLUME_MIN -144
75 struct pa_raop_client {
84 /* Encryption Related bits */
86 uint8_t aes_iv[AES_CHUNKSIZE]; /* initialization vector for aes-cbc */
87 uint8_t aes_nv[AES_CHUNKSIZE]; /* next vector for aes-cbc */
88 uint8_t aes_key[AES_CHUNKSIZE]; /* key for aes-cbc */
93 pa_raop_client_cb_t callback;
95 pa_raop_client_closed_cb_t closed_callback;
96 void* closed_userdata;
99 pa_memblock *memblock;
100 size_t buffer_length;
101 uint8_t *buffer_index;
102 uint16_t buffer_count;
106 * Function to write bits into a buffer.
107 * @param buffer Handle to the buffer. It will be incremented if new data requires it.
108 * @param bit_pos A pointer to a position buffer to keep track the current write location (0 for MSB, 7 for LSB)
109 * @param size A pointer to the byte size currently written. This allows the calling function to do simple buffer overflow checks
110 * @param data The data to write
111 * @param data_bit_len The number of bits from data to write
113 static inline void bit_writer(uint8_t **buffer, uint8_t *bit_pos, int *size, uint8_t data, uint8_t data_bit_len) {
114 int bits_left, bit_overflow;
120 /* If bit pos is zero, we will definatly use at least one bit from the current byte so size increments. */
124 /* Calc the number of bits left in the current byte of buffer */
125 bits_left = 7 - *bit_pos + 1;
126 /* Calc the overflow of bits in relation to how much space we have left... */
127 bit_overflow = bits_left - data_bit_len;
128 if (bit_overflow >= 0) {
129 /* We can fit the new data in our current byte */
130 /* As we write from MSB->LSB we need to left shift by the overflow amount */
131 bit_data = data << bit_overflow;
133 **buffer |= bit_data;
136 /* If our data fits exactly into the current byte, we need to increment our pointer */
137 if (0 == bit_overflow) {
138 /* Do not increment size as it will be incremeneted on next call as bit_pos is zero */
142 *bit_pos += data_bit_len;
145 /* bit_overflow is negative, there for we will need a new byte from our buffer */
146 /* Firstly fill up what's left in the current byte */
147 bit_data = data >> -bit_overflow;
148 **buffer |= bit_data;
149 /* Increment our buffer pointer and size counter*/
152 **buffer = data << (8 + bit_overflow);
153 *bit_pos = -bit_overflow;
157 static int rsa_encrypt(uint8_t *text, int len, uint8_t *res) {
159 "59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUtwC"
160 "5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDR"
161 "KSKv6kDqnw4UwPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuB"
162 "OitnZ/bDzPHrTOZz0Dew0uowxf/+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJ"
163 "Q+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/UAaHqn9JdsBWLUEpVviYnh"
164 "imNVvYFZeCXg/IdTQ+x4IRdiXNv5hEew==";
165 const char e[] = "AQAB";
166 uint8_t modules[256];
172 size = pa_base64_decode(n, modules);
173 rsa->n = BN_bin2bn(modules, size, NULL);
174 size = pa_base64_decode(e, exponent);
175 rsa->e = BN_bin2bn(exponent, size, NULL);
177 size = RSA_public_encrypt(len, text, res, rsa, RSA_PKCS1_OAEP_PADDING);
182 static int aes_encrypt(pa_raop_client* c, uint8_t *data, int size)
189 memcpy(c->aes_nv, c->aes_iv, AES_CHUNKSIZE);
190 while (i+AES_CHUNKSIZE <= size) {
192 for (j=0; j<AES_CHUNKSIZE; ++j)
193 buf[j] ^= c->aes_nv[j];
195 AES_encrypt(buf, buf, &c->aes);
196 memcpy(c->aes_nv, buf, AES_CHUNKSIZE);
202 static inline void rtrimchar(char *str, char rc)
204 char *sp = str + strlen(str) - 1;
205 while (sp >= str && *sp == rc) {
211 static void on_connection(pa_socket_client *sc, pa_iochannel *io, void *userdata) {
212 pa_raop_client *c = userdata;
216 pa_assert(c->sc == sc);
217 pa_assert(c->fd < 0);
218 pa_assert(c->callback);
220 pa_socket_client_unref(c->sc);
224 pa_log("Connection failed: %s", pa_cstrerror(errno));
228 c->fd = pa_iochannel_get_send_fd(io);
230 pa_iochannel_set_noclose(io, TRUE);
231 pa_iochannel_socket_set_sndbuf(io, 1024);
232 pa_iochannel_free(io);
234 pa_make_tcp_socket_low_delay(c->fd);
236 pa_log_debug("Connection established");
237 c->callback(c->fd, c->userdata);
240 static void rtsp_cb(pa_rtsp_client *rtsp, pa_rtsp_state state, pa_headerlist* headers, void *userdata)
242 pa_raop_client* c = userdata;
245 pa_assert(rtsp == c->rtsp);
248 case STATE_CONNECT: {
251 char *key, *iv, *sac, *sdp;
256 pa_log_debug("RAOP: CONNECTED");
257 ip = pa_rtsp_localip(c->rtsp);
258 /* First of all set the url properly */
259 url = pa_sprintf_malloc("rtsp://%s/%s", ip, c->sid);
260 pa_rtsp_set_url(c->rtsp, url);
263 /* Now encrypt our aes_public key to send to the device */
264 i = rsa_encrypt(c->aes_key, AES_CHUNKSIZE, rsakey);
265 pa_base64_encode(rsakey, i, &key);
267 pa_base64_encode(c->aes_iv, AES_CHUNKSIZE, &iv);
270 pa_random(&rand_data, sizeof(rand_data));
271 pa_base64_encode(&rand_data, AES_CHUNKSIZE, &sac);
273 pa_rtsp_add_header(c->rtsp, "Apple-Challenge", sac);
274 sdp = pa_sprintf_malloc(
276 "o=iTunes %s 0 IN IP4 %s\r\n"
280 "m=audio 0 RTP/AVP 96\r\n"
281 "a=rtpmap:96 AppleLossless\r\n"
282 "a=fmtp:96 4096 0 16 40 10 14 2 255 0 0 44100\r\n"
285 c->sid, ip, c->host, key, iv);
286 pa_rtsp_announce(c->rtsp, sdp);
295 pa_log_debug("RAOP: ANNOUNCED");
296 pa_rtsp_remove_header(c->rtsp, "Apple-Challenge");
297 pa_rtsp_setup(c->rtsp);
301 char *aj = pa_xstrdup(pa_headerlist_gets(headers, "Audio-Jack-Status"));
302 pa_log_debug("RAOP: SETUP");
305 char delimiters[] = ";";
306 const char* token_state = NULL;
307 c->jack_type = JACK_TYPE_ANALOG;
308 c->jack_status = JACK_STATUS_DISCONNECTED;
310 while ((token = pa_split(aj, delimiters, &token_state))) {
311 if ((pc = strstr(token, "="))) {
313 if (!strcmp(token, "type") && !strcmp(pc+1, "digital")) {
314 c->jack_type = JACK_TYPE_DIGITAL;
317 if (!strcmp(token,"connected"))
318 c->jack_status = JACK_STATUS_CONNECTED;
324 pa_log_warn("Audio Jack Status missing");
326 pa_rtsp_record(c->rtsp);
331 uint32_t port = pa_rtsp_serverport(c->rtsp);
332 pa_log_debug("RAOP: RECORDED");
334 if (!(c->sc = pa_socket_client_new_string(c->core->mainloop, c->host, port))) {
335 pa_log("failed to connect to server '%s:%d'", c->host, port);
338 pa_socket_client_set_callback(c->sc, on_connection, c);
343 case STATE_SET_PARAMETER:
346 case STATE_DISCONNECTED:
347 pa_assert(c->closed_callback);
348 pa_log_debug("RTSP channel closed");
355 pa_socket_client_unref(c->sc);
358 c->closed_callback(c->closed_userdata);
363 pa_raop_client* pa_raop_client_new(pa_core *core, const char* host)
371 pa_raop_client* c = pa_xnew0(pa_raop_client, 1);
378 c->host = pa_xstrdup(host);
379 c->rtsp = pa_rtsp_client_new("iTunes/4.6 (Macintosh; U; PPC Mac OS X 10.3)");
381 /* Initialise the AES encryption system */
382 pa_random(c->aes_iv, sizeof(c->aes_iv));
383 pa_random(c->aes_key, sizeof(c->aes_key));
384 memcpy(c->aes_nv, c->aes_iv, sizeof(c->aes_nv));
385 AES_set_encrypt_key(c->aes_key, 128, &c->aes);
387 /* Generate random instance id */
388 pa_random(&rand_data, sizeof(rand_data));
389 c->sid = pa_sprintf_malloc("%u", rand_data.a);
390 sci = pa_sprintf_malloc("%08x%08x",rand_data.b, rand_data.c);
391 pa_rtsp_add_header(c->rtsp, "Client-Instance", sci);
392 pa_rtsp_set_callback(c->rtsp, rtsp_cb, c);
393 if (pa_rtsp_connect(c->rtsp, c->core->mainloop, host, 5000)) {
394 pa_rtsp_client_free(c->rtsp);
401 void pa_raop_client_free(pa_raop_client* c)
407 pa_rtsp_client_free(c->rtsp);
413 static void noop(PA_GCC_UNUSED void* p) {}
415 int pa_raop_client_encode_sample(pa_raop_client* c, pa_memchunk* raw, pa_memchunk* encoded)
420 uint8_t *ibp, *maxibp;
425 static uint8_t header[] = {
426 0x24, 0x00, 0x00, 0x00,
427 0xF0, 0xFF, 0x00, 0x00,
428 0x00, 0x00, 0x00, 0x00,
429 0x00, 0x00, 0x00, 0x00,
431 int header_size = sizeof(header);
434 pa_assert(c->fd > 0);
436 pa_assert(raw->memblock);
437 pa_assert(raw->length > 0);
440 /* We have to send 4 byte chunks */
441 bsize = (int)(raw->length / 4);
444 /* Leave 16 bytes extra to allow for the ALAC header which is about 55 bits */
445 bufmax = length + header_size + 16;
446 if (bufmax > c->buffer_length) {
447 c->buffer = pa_xrealloc(c->buffer, bufmax);
448 c->buffer_length = bufmax;
450 pa_memblock_unref(c->memblock);
451 c->memblock = pa_memblock_new_user(c->core->mempool, c->buffer, bufmax, noop, 0);
453 pa_memchunk_reset(encoded);
454 encoded->memblock = c->memblock;
455 b = pa_memblock_acquire(encoded->memblock);
456 memcpy(b, header, header_size);
458 /* Now write the actual samples */
459 bp = b + header_size;
461 bit_writer(&bp,&bpos,&size,1,3); /* channel=1, stereo */
462 bit_writer(&bp,&bpos,&size,0,4); /* unknown */
463 bit_writer(&bp,&bpos,&size,0,8); /* unknown */
464 bit_writer(&bp,&bpos,&size,0,4); /* unknown */
465 bit_writer(&bp,&bpos,&size,1,1); /* hassize */
466 bit_writer(&bp,&bpos,&size,0,2); /* unused */
467 bit_writer(&bp,&bpos,&size,1,1); /* is-not-compressed */
469 /* size of data, integer, big endian */
470 bit_writer(&bp,&bpos,&size,(bsize>>24)&0xff,8);
471 bit_writer(&bp,&bpos,&size,(bsize>>16)&0xff,8);
472 bit_writer(&bp,&bpos,&size,(bsize>>8)&0xff,8);
473 bit_writer(&bp,&bpos,&size,(bsize)&0xff,8);
475 ibp = p = pa_memblock_acquire(raw->memblock);
476 maxibp = p + raw->length - 4;
477 while (ibp <= maxibp) {
478 /* Byte swap stereo data */
479 bit_writer(&bp,&bpos,&size,*(ibp+1),8);
480 bit_writer(&bp,&bpos,&size,*(ibp+0),8);
481 bit_writer(&bp,&bpos,&size,*(ibp+3),8);
482 bit_writer(&bp,&bpos,&size,*(ibp+2),8);
487 pa_memblock_release(raw->memblock);
488 encoded->length = header_size + size;
490 /* store the lenght (endian swapped: make this better) */
491 len = size + header_size - 4;
493 *(b + 3) = len & 0xff;
495 /* encrypt our data */
496 aes_encrypt(c, (b + header_size), size);
498 /* We're done with the chunk */
499 pa_memblock_release(encoded->memblock);
505 void pa_raop_client_set_callback(pa_raop_client* c, pa_raop_client_cb_t callback, void *userdata)
509 c->callback = callback;
510 c->userdata = userdata;
513 void pa_raop_client_set_closed_callback(pa_raop_client* c, pa_raop_client_closed_cb_t callback, void *userdata)
517 c->closed_callback = callback;
518 c->closed_userdata = userdata;