]> code.delx.au - pulseaudio/blob - src/modules/rtp/raop_client.c
bad747bb984239be4f95faa23a073a8ee3039882
[pulseaudio] / src / modules / rtp / raop_client.c
1 /* $Id$ */
2
3 /***
4 This file is part of PulseAudio.
5
6 Copyright 2008 Colin Guthrie
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 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, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21 USA.
22 ***/
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <fcntl.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <arpa/inet.h>
33 #include <unistd.h>
34 #include <sys/ioctl.h>
35
36 #ifdef HAVE_SYS_FILIO_H
37 #include <sys/filio.h>
38 #endif
39
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>
46
47 #include <pulse/xmalloc.h>
48
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>
57
58 #include "raop_client.h"
59 #include "rtsp_client.h"
60 #include "base64.h"
61
62 #define AES_CHUNKSIZE 16
63
64 #define JACK_STATUS_DISCONNECTED 0
65 #define JACK_STATUS_CONNECTED 1
66
67 #define JACK_TYPE_ANALOG 0
68 #define JACK_TYPE_DIGITAL 1
69
70 #define VOLUME_DEF -30
71 #define VOLUME_MIN -144
72 #define VOLUME_MAX 0
73
74
75 struct pa_raop_client {
76 pa_mainloop_api *mainloop;
77 const char *host;
78 char *sid;
79 pa_rtsp_client *rtsp;
80
81 uint8_t jack_type;
82 uint8_t jack_status;
83
84 /* Encryption Related bits */
85 AES_KEY aes;
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 */
89
90 pa_socket_client *sc;
91 int fd;
92 pa_raop_client_cb_t callback;
93 void* userdata;
94
95 uint8_t *buffer;
96 uint8_t *buffer_index;
97 uint16_t buffer_count;
98 /*pa_memchunk memchunk;*/
99 };
100
101 /**
102 * Function to write bits into a buffer.
103 * @param buffer Handle to the buffer. It will be incremented if new data requires it.
104 * @param bit_pos A pointer to a position buffer to keep track the current write location (0 for MSB, 7 for LSB)
105 * @param size A pointer to the byte size currently written. This allows the calling function to do simple buffer overflow checks
106 * @param data The data to write
107 * @param data_bit_len The number of bits from data to write
108 */
109 static inline void bit_writer(uint8_t **buffer, uint8_t *bit_pos, int *size, uint8_t data, uint8_t data_bit_len) {
110 int bits_left, bit_overflow;
111 uint8_t bit_data;
112
113 if (!data_bit_len)
114 return;
115
116 /* If bit pos is zero, we will definatly use at least one bit from the current byte so size increments. */
117 if (!*bit_pos)
118 *size += 1;
119
120 /* Calc the number of bits left in the current byte of buffer */
121 bits_left = 7 - *bit_pos + 1;
122 /* Calc the overflow of bits in relation to how much space we have left... */
123 bit_overflow = bits_left - data_bit_len;
124 if (bit_overflow >= 0) {
125 /* We can fit the new data in our current byte */
126 /* As we write from MSB->LSB we need to left shift by the overflow amount */
127 bit_data = data << bit_overflow;
128 if (*bit_pos)
129 **buffer |= bit_data;
130 else
131 **buffer = bit_data;
132 /* If our data fits exactly into the current byte, we need to increment our pointer */
133 if (0 == bit_overflow) {
134 /* Do not increment size as it will be incremeneted on next call as bit_pos is zero */
135 *buffer += 1;
136 *bit_pos = 0;
137 } else {
138 *bit_pos += data_bit_len;
139 }
140 } else {
141 /* bit_overflow is negative, there for we will need a new byte from our buffer */
142 /* Firstly fill up what's left in the current byte */
143 bit_data = data >> -bit_overflow;
144 **buffer |= bit_data;
145 /* Increment our buffer pointer and size counter*/
146 *buffer += 1;
147 *size += 1;
148 **buffer = data << (8 + bit_overflow);
149 *bit_pos = -bit_overflow;
150 }
151 }
152
153 static int rsa_encrypt(uint8_t *text, int len, uint8_t *res) {
154 char n[] =
155 "59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUtwC"
156 "5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDR"
157 "KSKv6kDqnw4UwPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuB"
158 "OitnZ/bDzPHrTOZz0Dew0uowxf/+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJ"
159 "Q+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/UAaHqn9JdsBWLUEpVviYnh"
160 "imNVvYFZeCXg/IdTQ+x4IRdiXNv5hEew==";
161 char e[] = "AQAB";
162 uint8_t modules[256];
163 uint8_t exponent[8];
164 int size;
165 RSA *rsa;
166
167 rsa = RSA_new();
168 size = pa_base64_decode(n, modules);
169 rsa->n = BN_bin2bn(modules, size, NULL);
170 size = pa_base64_decode(e, exponent);
171 rsa->e = BN_bin2bn(exponent, size, NULL);
172
173 size = RSA_public_encrypt(len, text, res, rsa, RSA_PKCS1_OAEP_PADDING);
174 RSA_free(rsa);
175 return size;
176 }
177
178 static int aes_encrypt(pa_raop_client* c, uint8_t *data, int size)
179 {
180 uint8_t *buf;
181 int i=0, j;
182
183 pa_assert(c);
184
185 memcpy(c->aes_nv, c->aes_iv, AES_CHUNKSIZE);
186 while (i+AES_CHUNKSIZE <= size) {
187 buf = data + i;
188 for (j=0; j<AES_CHUNKSIZE; ++j)
189 buf[j] ^= c->aes_nv[j];
190
191 AES_encrypt(buf, buf, &c->aes);
192 memcpy(c->aes_nv, buf, AES_CHUNKSIZE);
193 i += AES_CHUNKSIZE;
194 }
195 return i;
196 }
197
198 static inline void rtrimchar(char *str, char rc)
199 {
200 char *sp = str + strlen(str) - 1;
201 while (sp >= str && *sp == rc) {
202 *sp = '\0';
203 sp -= 1;
204 }
205 }
206
207 static void on_connection(pa_socket_client *sc, pa_iochannel *io, void *userdata) {
208 pa_raop_client *c = userdata;
209
210 pa_assert(sc);
211 pa_assert(c);
212 pa_assert(c->sc == sc);
213 pa_assert(c->fd < 0);
214 pa_assert(c->callback);
215
216 pa_socket_client_unref(c->sc);
217 c->sc = NULL;
218
219 if (!io) {
220 pa_log("Connection failed: %s", pa_cstrerror(errno));
221 return;
222 }
223
224 c->fd = pa_iochannel_get_send_fd(io);
225
226 pa_iochannel_set_noclose(io, TRUE);
227 pa_iochannel_free(io);
228
229 pa_make_tcp_socket_low_delay(c->fd);
230
231 pa_log_debug("Connection established");
232 c->callback(c->fd, c->userdata);
233 }
234
235 static void rtsp_cb(pa_rtsp_client *rtsp, pa_rtsp_state state, pa_headerlist* headers, void *userdata)
236 {
237 pa_raop_client* c = userdata;
238 pa_assert(c);
239 pa_assert(rtsp);
240 pa_assert(rtsp == c->rtsp);
241
242 switch (state) {
243 case STATE_CONNECT: {
244 int i;
245 uint8_t rsakey[512];
246 char *key, *iv, *sac, *sdp;
247 uint16_t rand_data;
248 const char *ip;
249 char *url;
250
251 pa_log_debug("RAOP: CONNECTED");
252 ip = pa_rtsp_localip(c->rtsp);
253 /* First of all set the url properly */
254 url = pa_sprintf_malloc("rtsp://%s/%s", ip, c->sid);
255 pa_rtsp_set_url(c->rtsp, url);
256 pa_xfree(url);
257
258 /* Now encrypt our aes_public key to send to the device */
259 i = rsa_encrypt(c->aes_key, AES_CHUNKSIZE, rsakey);
260 pa_base64_encode(rsakey, i, &key);
261 rtrimchar(key, '=');
262 pa_base64_encode(c->aes_iv, AES_CHUNKSIZE, &iv);
263 rtrimchar(iv, '=');
264
265 pa_random(&rand_data, sizeof(rand_data));
266 pa_base64_encode(&rand_data, AES_CHUNKSIZE, &sac);
267 rtrimchar(sac, '=');
268 pa_rtsp_add_header(c->rtsp, "Apple-Challenge", sac);
269 sdp = pa_sprintf_malloc(
270 "v=0\r\n"
271 "o=iTunes %s 0 IN IP4 %s\r\n"
272 "s=iTunes\r\n"
273 "c=IN IP4 %s\r\n"
274 "t=0 0\r\n"
275 "m=audio 0 RTP/AVP 96\r\n"
276 "a=rtpmap:96 AppleLossless\r\n"
277 "a=fmtp:96 4096 0 16 40 10 14 2 255 0 0 44100\r\n"
278 "a=rsaaeskey:%s\r\n"
279 "a=aesiv:%s\r\n",
280 c->sid, ip, c->host, key, iv);
281 pa_rtsp_announce(c->rtsp, sdp);
282 pa_xfree(key);
283 pa_xfree(iv);
284 pa_xfree(sac);
285 pa_xfree(sdp);
286 break;
287 }
288
289 case STATE_ANNOUNCE:
290 pa_log_debug("RAOP: ANNOUNCED");
291 pa_rtsp_remove_header(c->rtsp, "Apple-Challenge");
292 pa_rtsp_setup(c->rtsp);
293 break;
294
295 case STATE_SETUP: {
296 char *aj = pa_xstrdup(pa_headerlist_gets(headers, "Audio-Jack-Status"));
297 pa_log_debug("RAOP: SETUP");
298 if (aj) {
299 char *token, *pc;
300 char delimiters[] = ";";
301 const char* token_state = NULL;
302 c->jack_type = JACK_TYPE_ANALOG;
303 c->jack_status = JACK_STATUS_DISCONNECTED;
304
305 while ((token = pa_split(aj, delimiters, &token_state))) {
306 if ((pc = strstr(token, "="))) {
307 *pc = 0;
308 if (!strcmp(token, "type") && !strcmp(pc+1, "digital")) {
309 c->jack_type = JACK_TYPE_DIGITAL;
310 }
311 } else {
312 if (!strcmp(token,"connected"))
313 c->jack_status = JACK_STATUS_CONNECTED;
314 }
315 pa_xfree(token);
316 }
317 pa_xfree(aj);
318 } else {
319 pa_log_warn("Audio Jack Status missing");
320 }
321 pa_rtsp_record(c->rtsp);
322 break;
323 }
324
325 case STATE_RECORD: {
326 uint32_t port = pa_rtsp_serverport(c->rtsp);
327 pa_log_debug("RAOP: RECORDED");
328
329 if (!(c->sc = pa_socket_client_new_string(c->mainloop, c->host, port))) {
330 pa_log("failed to connect to server '%s:%d'", c->host, port);
331 return;
332 }
333 pa_socket_client_set_callback(c->sc, on_connection, c);
334 break;
335 }
336
337 case STATE_TEARDOWN:
338 case STATE_SET_PARAMETER:
339 case STATE_FLUSH:
340 break;
341 }
342 }
343
344 pa_raop_client* pa_raop_client_new(pa_mainloop_api *mainloop, const char* host)
345 {
346 char *sci;
347 struct {
348 uint32_t a;
349 uint32_t b;
350 uint32_t c;
351 } rand_data;
352 pa_raop_client* c = pa_xnew0(pa_raop_client, 1);
353
354 pa_assert(host);
355
356 c->mainloop = mainloop;
357 c->fd = -1;
358 c->host = pa_xstrdup(host);
359 c->rtsp = pa_rtsp_client_new("iTunes/4.6 (Macintosh; U; PPC Mac OS X 10.3)");
360
361 /* Initialise the AES encryption system */
362 pa_random_seed();
363 pa_random(c->aes_iv, sizeof(c->aes_iv));
364 pa_random(c->aes_key, sizeof(c->aes_key));
365 memcpy(c->aes_nv, c->aes_iv, sizeof(c->aes_nv));
366 AES_set_encrypt_key(c->aes_key, 128, &c->aes);
367
368 /* Generate random instance id */
369 pa_random(&rand_data, sizeof(rand_data));
370 c->sid = pa_sprintf_malloc("%u", rand_data.a);
371 sci = pa_sprintf_malloc("%08x%08x",rand_data.b, rand_data.c);
372 pa_rtsp_add_header(c->rtsp, "Client-Instance", sci);
373 pa_rtsp_set_callback(c->rtsp, rtsp_cb, c);
374 if (pa_rtsp_connect(c->rtsp, mainloop, host, 5000)) {
375 pa_rtsp_client_free(c->rtsp);
376 pa_xfree(c->aes_iv);
377 pa_xfree(c->aes_nv);
378 pa_xfree(c->aes_key);
379 return NULL;
380 }
381 return c;
382 }
383
384
385 void pa_raop_client_free(pa_raop_client* c)
386 {
387 pa_assert(c);
388
389 pa_rtsp_client_free(c->rtsp);
390 pa_xfree(c->aes_iv);
391 pa_xfree(c->aes_nv);
392 pa_xfree(c->aes_key);
393 pa_xfree(c->host);
394 pa_xfree(c);
395 }
396
397
398 static void noop(PA_GCC_UNUSED void* p) {}
399
400 pa_memchunk pa_raop_client_encode_sample(pa_raop_client* c, pa_mempool* mempool, pa_memchunk* raw)
401 {
402 uint16_t len, bufmax;
403 uint8_t *bp, bpos;
404 uint8_t *ibp, *maxibp;
405 int size;
406 uint8_t *p;
407 uint16_t bsize;
408 pa_memchunk rv;
409 size_t length;
410 static uint8_t header[] = {
411 0x24, 0x00, 0x00, 0x00,
412 0xF0, 0xFF, 0x00, 0x00,
413 0x00, 0x00, 0x00, 0x00,
414 0x00, 0x00, 0x00, 0x00,
415 };
416 const int header_size = sizeof(header);
417
418 pa_assert(c);
419 pa_assert(c->fd > 0);
420 pa_assert(raw);
421 pa_assert(raw->memblock);
422 pa_assert(raw->length > 0);
423
424 /* We have to send 4 byte chunks */
425 bsize = (int)(raw->length / 4);
426 length = bsize * 4;
427
428 /* Leave 16 bytes extra to allow for the ALAC header which is about 55 bits */
429 bufmax = length + header_size + 16;
430 c->buffer = pa_xrealloc(c->buffer, bufmax);
431 memcpy(c->buffer, header, header_size);
432 pa_memchunk_reset(&rv);
433 rv.memblock = pa_memblock_new_user(mempool, c->buffer, (header_size + length), noop, 1);
434
435 /* Now write the actual samples */
436 bp = c->buffer + header_size;
437 size = bpos = 0;
438 bit_writer(&bp,&bpos,&size,1,3); // channel=1, stereo
439 bit_writer(&bp,&bpos,&size,0,4); // unknown
440 bit_writer(&bp,&bpos,&size,0,8); // unknown
441 bit_writer(&bp,&bpos,&size,0,4); // unknown
442 bit_writer(&bp,&bpos,&size,1,1); // hassize
443 bit_writer(&bp,&bpos,&size,0,2); // unused
444 bit_writer(&bp,&bpos,&size,1,1); // is-not-compressed
445
446 /* size of data, integer, big endian */
447 bit_writer(&bp,&bpos,&size,(bsize>>24)&0xff,8);
448 bit_writer(&bp,&bpos,&size,(bsize>>16)&0xff,8);
449 bit_writer(&bp,&bpos,&size,(bsize>>8)&0xff,8);
450 bit_writer(&bp,&bpos,&size,(bsize)&0xff,8);
451
452 ibp = p = pa_memblock_acquire(raw->memblock);
453 maxibp = p + raw->length - 4;
454 while (ibp <= maxibp) {
455 /* Byte swap stereo data */
456 bit_writer(&bp,&bpos,&size,*(ibp+1),8);
457 bit_writer(&bp,&bpos,&size,*(ibp+0),8);
458 bit_writer(&bp,&bpos,&size,*(ibp+3),8);
459 bit_writer(&bp,&bpos,&size,*(ibp+2),8);
460 ibp += 4;
461 raw->index += 4;
462 raw->length -= 4;
463 }
464 pa_memblock_release(raw->memblock);
465 rv.length = header_size + size;
466
467 /* store the lenght (endian swapped: make this better) */
468 len = size + header_size - 4;
469 *(c->buffer + 2) = len >> 8;
470 *(c->buffer + 3) = len & 0xff;
471
472 /* encrypt our data */
473 aes_encrypt(c, (c->buffer + header_size), size);
474 return rv;
475 }
476
477
478 void pa_raop_client_set_callback(pa_raop_client* c, pa_raop_client_cb_t callback, void *userdata)
479 {
480 pa_assert(c);
481
482 c->callback = callback;
483 c->userdata = userdata;
484 }