]> code.delx.au - pulseaudio/blob - src/modules/raop/raop_client.c
98a98224acccd2f0ac4f6984647eb1de1d3d2426
[pulseaudio] / src / modules / raop / raop_client.c
1 /***
2 This file is part of PulseAudio.
3
4 Copyright 2008 Colin Guthrie
5
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published
8 by the Free Software Foundation; either version 2.1 of the License,
9 or (at your option) any later version.
10
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with PulseAudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <sys/ioctl.h>
31
32 #ifdef HAVE_SYS_FILIO_H
33 #include <sys/filio.h>
34 #endif
35
36 /* TODO: Replace OpenSSL with NSS */
37 #include <openssl/err.h>
38 #include <openssl/rand.h>
39 #include <openssl/aes.h>
40 #include <openssl/rsa.h>
41 #include <openssl/engine.h>
42
43 #include <pulse/xmalloc.h>
44
45 #include <pulsecore/core-error.h>
46 #include <pulsecore/core-util.h>
47 #include <pulsecore/iochannel.h>
48 #include <pulsecore/socket-util.h>
49 #include <pulsecore/log.h>
50 #include <pulsecore/parseaddr.h>
51 #include <pulsecore/macro.h>
52 #include <pulsecore/memchunk.h>
53 #include <pulsecore/random.h>
54
55 #include "raop_client.h"
56 #include "rtsp_client.h"
57 #include "base64.h"
58
59 #define AES_CHUNKSIZE 16
60
61 #define JACK_STATUS_DISCONNECTED 0
62 #define JACK_STATUS_CONNECTED 1
63
64 #define JACK_TYPE_ANALOG 0
65 #define JACK_TYPE_DIGITAL 1
66
67 #define VOLUME_DEF -30
68 #define VOLUME_MIN -144
69 #define VOLUME_MAX 0
70
71 #define RAOP_PORT 5000
72
73 struct pa_raop_client {
74 pa_core *core;
75 char *host;
76 uint16_t port;
77 char *sid;
78 pa_rtsp_client *rtsp;
79
80 uint8_t jack_type;
81 uint8_t jack_status;
82
83 /* Encryption Related bits */
84 AES_KEY aes;
85 uint8_t aes_iv[AES_CHUNKSIZE]; /* initialization vector for aes-cbc */
86 uint8_t aes_nv[AES_CHUNKSIZE]; /* next vector for aes-cbc */
87 uint8_t aes_key[AES_CHUNKSIZE]; /* key for aes-cbc */
88
89 pa_socket_client *sc;
90 int fd;
91
92 uint16_t seq;
93 uint32_t rtptime;
94
95 pa_raop_client_cb_t callback;
96 void* userdata;
97 pa_raop_client_closed_cb_t closed_callback;
98 void* closed_userdata;
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 definately 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 incremented 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 const 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 const 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 uint8_t *buf;
180 int i=0, j;
181
182 pa_assert(c);
183
184 memcpy(c->aes_nv, c->aes_iv, AES_CHUNKSIZE);
185 while (i+AES_CHUNKSIZE <= size) {
186 buf = data + i;
187 for (j=0; j<AES_CHUNKSIZE; ++j)
188 buf[j] ^= c->aes_nv[j];
189
190 AES_encrypt(buf, buf, &c->aes);
191 memcpy(c->aes_nv, buf, AES_CHUNKSIZE);
192 i += AES_CHUNKSIZE;
193 }
194 return i;
195 }
196
197 static inline void rtrimchar(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 static void on_connection(pa_socket_client *sc, pa_iochannel *io, void *userdata) {
206 pa_raop_client *c = userdata;
207
208 pa_assert(sc);
209 pa_assert(c);
210 pa_assert(c->sc == sc);
211 pa_assert(c->fd < 0);
212 pa_assert(c->callback);
213
214 pa_socket_client_unref(c->sc);
215 c->sc = NULL;
216
217 if (!io) {
218 pa_log("Connection failed: %s", pa_cstrerror(errno));
219 return;
220 }
221
222 c->fd = pa_iochannel_get_send_fd(io);
223
224 pa_iochannel_set_noclose(io, true);
225 pa_iochannel_free(io);
226
227 pa_make_tcp_socket_low_delay(c->fd);
228
229 pa_log_debug("Connection established");
230 c->callback(c->fd, c->userdata);
231 }
232
233 static void rtsp_cb(pa_rtsp_client *rtsp, pa_rtsp_state state, pa_headerlist* headers, void *userdata) {
234 pa_raop_client* c = userdata;
235 pa_assert(c);
236 pa_assert(rtsp);
237 pa_assert(rtsp == c->rtsp);
238
239 switch (state) {
240 case STATE_CONNECT: {
241 int i;
242 uint8_t rsakey[512];
243 char *key, *iv, *sac, *sdp;
244 uint16_t rand_data;
245 const char *ip;
246 char *url;
247
248 pa_log_debug("RAOP: CONNECTED");
249 ip = pa_rtsp_localip(c->rtsp);
250 /* First of all set the url properly */
251 url = pa_sprintf_malloc("rtsp://%s/%s", ip, c->sid);
252 pa_rtsp_set_url(c->rtsp, url);
253 pa_xfree(url);
254
255 /* Now encrypt our aes_public key to send to the device */
256 i = rsa_encrypt(c->aes_key, AES_CHUNKSIZE, rsakey);
257 pa_base64_encode(rsakey, i, &key);
258 rtrimchar(key, '=');
259 pa_base64_encode(c->aes_iv, AES_CHUNKSIZE, &iv);
260 rtrimchar(iv, '=');
261
262 pa_random(&rand_data, sizeof(rand_data));
263 pa_base64_encode(&rand_data, AES_CHUNKSIZE, &sac);
264 rtrimchar(sac, '=');
265 pa_rtsp_add_header(c->rtsp, "Apple-Challenge", sac);
266 sdp = pa_sprintf_malloc(
267 "v=0\r\n"
268 "o=iTunes %s 0 IN IP4 %s\r\n"
269 "s=iTunes\r\n"
270 "c=IN IP4 %s\r\n"
271 "t=0 0\r\n"
272 "m=audio 0 RTP/AVP 96\r\n"
273 "a=rtpmap:96 AppleLossless\r\n"
274 "a=fmtp:96 4096 0 16 40 10 14 2 255 0 0 44100\r\n"
275 "a=rsaaeskey:%s\r\n"
276 "a=aesiv:%s\r\n",
277 c->sid, ip, c->host, key, iv);
278 pa_rtsp_announce(c->rtsp, sdp);
279 pa_xfree(key);
280 pa_xfree(iv);
281 pa_xfree(sac);
282 pa_xfree(sdp);
283 break;
284 }
285
286 case STATE_ANNOUNCE:
287 pa_log_debug("RAOP: ANNOUNCED");
288 pa_rtsp_remove_header(c->rtsp, "Apple-Challenge");
289 pa_rtsp_setup(c->rtsp);
290 break;
291
292 case STATE_SETUP: {
293 char *aj = pa_xstrdup(pa_headerlist_gets(headers, "Audio-Jack-Status"));
294 pa_log_debug("RAOP: SETUP");
295 if (aj) {
296 char *token, *pc;
297 char delimiters[] = ";";
298 const char* token_state = NULL;
299 c->jack_type = JACK_TYPE_ANALOG;
300 c->jack_status = JACK_STATUS_DISCONNECTED;
301
302 while ((token = pa_split(aj, delimiters, &token_state))) {
303 if ((pc = strstr(token, "="))) {
304 *pc = 0;
305 if (pa_streq(token, "type") && pa_streq(pc+1, "digital")) {
306 c->jack_type = JACK_TYPE_DIGITAL;
307 }
308 } else {
309 if (pa_streq(token, "connected"))
310 c->jack_status = JACK_STATUS_CONNECTED;
311 }
312 pa_xfree(token);
313 }
314 pa_xfree(aj);
315 } else {
316 pa_log_warn("Audio Jack Status missing");
317 }
318 pa_rtsp_record(c->rtsp, &c->seq, &c->rtptime);
319 break;
320 }
321
322 case STATE_RECORD: {
323 uint32_t port = pa_rtsp_serverport(c->rtsp);
324 pa_log_debug("RAOP: RECORDED");
325
326 if (!(c->sc = pa_socket_client_new_string(c->core->mainloop, true, c->host, port))) {
327 pa_log("failed to connect to server '%s:%d'", c->host, port);
328 return;
329 }
330 pa_socket_client_set_callback(c->sc, on_connection, c);
331 break;
332 }
333
334 case STATE_FLUSH:
335 pa_log_debug("RAOP: FLUSHED");
336 break;
337
338 case STATE_TEARDOWN:
339 pa_log_debug("RAOP: TEARDOWN");
340 break;
341
342 case STATE_SET_PARAMETER:
343 pa_log_debug("RAOP: SET_PARAMETER");
344 break;
345
346 case STATE_DISCONNECTED:
347 pa_assert(c->closed_callback);
348 pa_assert(c->rtsp);
349
350 pa_log_debug("RTSP control channel closed");
351 pa_rtsp_client_free(c->rtsp);
352 c->rtsp = NULL;
353 if (c->fd > 0) {
354 /* We do not close the fd, we leave it to the closed callback to do that */
355 c->fd = -1;
356 }
357 if (c->sc) {
358 pa_socket_client_unref(c->sc);
359 c->sc = NULL;
360 }
361 pa_xfree(c->sid);
362 c->sid = NULL;
363 c->closed_callback(c->closed_userdata);
364 break;
365 }
366 }
367
368 pa_raop_client* pa_raop_client_new(pa_core *core, const char* host) {
369 pa_parsed_address a;
370 pa_raop_client* c = pa_xnew0(pa_raop_client, 1);
371
372 pa_assert(core);
373 pa_assert(host);
374
375 if (pa_parse_address(host, &a) < 0 || a.type == PA_PARSED_ADDRESS_UNIX)
376 return NULL;
377
378 c->core = core;
379 c->fd = -1;
380
381 c->host = pa_xstrdup(a.path_or_host);
382 if (a.port)
383 c->port = a.port;
384 else
385 c->port = RAOP_PORT;
386
387 if (pa_raop_connect(c)) {
388 pa_raop_client_free(c);
389 return NULL;
390 }
391 return c;
392 }
393
394 void pa_raop_client_free(pa_raop_client* c) {
395 pa_assert(c);
396
397 if (c->rtsp)
398 pa_rtsp_client_free(c->rtsp);
399 if (c->sid)
400 pa_xfree(c->sid);
401 pa_xfree(c->host);
402 pa_xfree(c);
403 }
404
405 int pa_raop_connect(pa_raop_client* c) {
406 char *sci;
407 struct {
408 uint32_t a;
409 uint32_t b;
410 uint32_t c;
411 } rand_data;
412
413 pa_assert(c);
414
415 if (c->rtsp) {
416 pa_log_debug("Connection already in progress");
417 return 0;
418 }
419
420 c->rtsp = pa_rtsp_client_new(c->core->mainloop, c->host, c->port, "iTunes/4.6 (Macintosh; U; PPC Mac OS X 10.3)");
421
422 /* Initialise the AES encryption system */
423 pa_random(c->aes_iv, sizeof(c->aes_iv));
424 pa_random(c->aes_key, sizeof(c->aes_key));
425 memcpy(c->aes_nv, c->aes_iv, sizeof(c->aes_nv));
426 AES_set_encrypt_key(c->aes_key, 128, &c->aes);
427
428 /* Generate random instance id */
429 pa_random(&rand_data, sizeof(rand_data));
430 c->sid = pa_sprintf_malloc("%u", rand_data.a);
431 sci = pa_sprintf_malloc("%08x%08x",rand_data.b, rand_data.c);
432 pa_rtsp_add_header(c->rtsp, "Client-Instance", sci);
433 pa_xfree(sci);
434 pa_rtsp_set_callback(c->rtsp, rtsp_cb, c);
435 return pa_rtsp_connect(c->rtsp);
436 }
437
438 int pa_raop_flush(pa_raop_client* c) {
439 pa_assert(c);
440
441 pa_rtsp_flush(c->rtsp, c->seq, c->rtptime);
442 return 0;
443 }
444
445 int pa_raop_client_set_volume(pa_raop_client* c, pa_volume_t volume) {
446 int rv;
447 double db;
448 char *param;
449
450 pa_assert(c);
451
452 db = pa_sw_volume_to_dB(volume);
453 if (db < VOLUME_MIN)
454 db = VOLUME_MIN;
455 else if (db > VOLUME_MAX)
456 db = VOLUME_MAX;
457
458 param = pa_sprintf_malloc("volume: %0.6f\r\n", db);
459
460 /* We just hit and hope, cannot wait for the callback */
461 rv = pa_rtsp_setparameter(c->rtsp, param);
462 pa_xfree(param);
463 return rv;
464 }
465
466 int pa_raop_client_encode_sample(pa_raop_client* c, pa_memchunk* raw, pa_memchunk* encoded) {
467 uint16_t len;
468 size_t bufmax;
469 uint8_t *bp, bpos;
470 uint8_t *ibp, *maxibp;
471 int size;
472 uint8_t *b, *p;
473 uint32_t bsize;
474 size_t length;
475 static uint8_t header[] = {
476 0x24, 0x00, 0x00, 0x00,
477 0xF0, 0xFF, 0x00, 0x00,
478 0x00, 0x00, 0x00, 0x00,
479 0x00, 0x00, 0x00, 0x00,
480 };
481 int header_size = sizeof(header);
482
483 pa_assert(c);
484 pa_assert(c->fd > 0);
485 pa_assert(raw);
486 pa_assert(raw->memblock);
487 pa_assert(raw->length > 0);
488 pa_assert(encoded);
489
490 /* We have to send 4 byte chunks */
491 bsize = (int)(raw->length / 4);
492 length = bsize * 4;
493
494 /* Leave 16 bytes extra to allow for the ALAC header which is about 55 bits */
495 bufmax = length + header_size + 16;
496 pa_memchunk_reset(encoded);
497 encoded->memblock = pa_memblock_new(c->core->mempool, bufmax);
498 b = pa_memblock_acquire(encoded->memblock);
499 memcpy(b, header, header_size);
500
501 /* Now write the actual samples */
502 bp = b + header_size;
503 size = bpos = 0;
504 bit_writer(&bp,&bpos,&size,1,3); /* channel=1, stereo */
505 bit_writer(&bp,&bpos,&size,0,4); /* unknown */
506 bit_writer(&bp,&bpos,&size,0,8); /* unknown */
507 bit_writer(&bp,&bpos,&size,0,4); /* unknown */
508 bit_writer(&bp,&bpos,&size,1,1); /* hassize */
509 bit_writer(&bp,&bpos,&size,0,2); /* unused */
510 bit_writer(&bp,&bpos,&size,1,1); /* is-not-compressed */
511
512 /* size of data, integer, big endian */
513 bit_writer(&bp,&bpos,&size,(bsize>>24)&0xff,8);
514 bit_writer(&bp,&bpos,&size,(bsize>>16)&0xff,8);
515 bit_writer(&bp,&bpos,&size,(bsize>>8)&0xff,8);
516 bit_writer(&bp,&bpos,&size,(bsize)&0xff,8);
517
518 ibp = p = pa_memblock_acquire(raw->memblock);
519 maxibp = p + raw->length - 4;
520 while (ibp <= maxibp) {
521 /* Byte swap stereo data */
522 bit_writer(&bp,&bpos,&size,*(ibp+1),8);
523 bit_writer(&bp,&bpos,&size,*(ibp+0),8);
524 bit_writer(&bp,&bpos,&size,*(ibp+3),8);
525 bit_writer(&bp,&bpos,&size,*(ibp+2),8);
526 ibp += 4;
527 raw->index += 4;
528 raw->length -= 4;
529 }
530 pa_memblock_release(raw->memblock);
531 encoded->length = header_size + size;
532
533 /* store the length (endian swapped: make this better) */
534 len = size + header_size - 4;
535 *(b + 2) = len >> 8;
536 *(b + 3) = len & 0xff;
537
538 /* encrypt our data */
539 aes_encrypt(c, (b + header_size), size);
540
541 /* We're done with the chunk */
542 pa_memblock_release(encoded->memblock);
543
544 return 0;
545 }
546
547 void pa_raop_client_set_callback(pa_raop_client* c, pa_raop_client_cb_t callback, void *userdata) {
548 pa_assert(c);
549
550 c->callback = callback;
551 c->userdata = userdata;
552 }
553
554 void pa_raop_client_set_closed_callback(pa_raop_client* c, pa_raop_client_closed_cb_t callback, void *userdata) {
555 pa_assert(c);
556
557 c->closed_callback = callback;
558 c->closed_userdata = userdata;
559 }