]> code.delx.au - pulseaudio/blob - src/modules/raop/raop_client.c
b11cafba7047dd80e56533358cb920237c30c5dd
[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
74 struct pa_raop_client {
75 pa_core *core;
76 char *host;
77 uint16_t port;
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
93 uint16_t seq;
94 uint32_t rtptime;
95
96 pa_raop_client_cb_t callback;
97 void* userdata;
98 pa_raop_client_closed_cb_t closed_callback;
99 void* closed_userdata;
100 };
101
102 /**
103 * Function to write bits into a buffer.
104 * @param buffer Handle to the buffer. It will be incremented if new data requires it.
105 * @param bit_pos A pointer to a position buffer to keep track the current write location (0 for MSB, 7 for LSB)
106 * @param size A pointer to the byte size currently written. This allows the calling function to do simple buffer overflow checks
107 * @param data The data to write
108 * @param data_bit_len The number of bits from data to write
109 */
110 static inline void bit_writer(uint8_t **buffer, uint8_t *bit_pos, int *size, uint8_t data, uint8_t data_bit_len) {
111 int bits_left, bit_overflow;
112 uint8_t bit_data;
113
114 if (!data_bit_len)
115 return;
116
117 /* If bit pos is zero, we will definately use at least one bit from the current byte so size increments. */
118 if (!*bit_pos)
119 *size += 1;
120
121 /* Calc the number of bits left in the current byte of buffer */
122 bits_left = 7 - *bit_pos + 1;
123 /* Calc the overflow of bits in relation to how much space we have left... */
124 bit_overflow = bits_left - data_bit_len;
125 if (bit_overflow >= 0) {
126 /* We can fit the new data in our current byte */
127 /* As we write from MSB->LSB we need to left shift by the overflow amount */
128 bit_data = data << bit_overflow;
129 if (*bit_pos)
130 **buffer |= bit_data;
131 else
132 **buffer = bit_data;
133 /* If our data fits exactly into the current byte, we need to increment our pointer */
134 if (0 == bit_overflow) {
135 /* Do not increment size as it will be incremented on next call as bit_pos is zero */
136 *buffer += 1;
137 *bit_pos = 0;
138 } else {
139 *bit_pos += data_bit_len;
140 }
141 } else {
142 /* bit_overflow is negative, there for we will need a new byte from our buffer */
143 /* Firstly fill up what's left in the current byte */
144 bit_data = data >> -bit_overflow;
145 **buffer |= bit_data;
146 /* Increment our buffer pointer and size counter*/
147 *buffer += 1;
148 *size += 1;
149 **buffer = data << (8 + bit_overflow);
150 *bit_pos = -bit_overflow;
151 }
152 }
153
154 static int rsa_encrypt(uint8_t *text, int len, uint8_t *res) {
155 const char n[] =
156 "59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUtwC"
157 "5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDR"
158 "KSKv6kDqnw4UwPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuB"
159 "OitnZ/bDzPHrTOZz0Dew0uowxf/+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJ"
160 "Q+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/UAaHqn9JdsBWLUEpVviYnh"
161 "imNVvYFZeCXg/IdTQ+x4IRdiXNv5hEew==";
162 const char e[] = "AQAB";
163 uint8_t modules[256];
164 uint8_t exponent[8];
165 int size;
166 RSA *rsa;
167
168 rsa = RSA_new();
169 size = pa_base64_decode(n, modules);
170 rsa->n = BN_bin2bn(modules, size, NULL);
171 size = pa_base64_decode(e, exponent);
172 rsa->e = BN_bin2bn(exponent, size, NULL);
173
174 size = RSA_public_encrypt(len, text, res, rsa, RSA_PKCS1_OAEP_PADDING);
175 RSA_free(rsa);
176 return size;
177 }
178
179 static int aes_encrypt(pa_raop_client* c, uint8_t *data, int size) {
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 char *sp = str + strlen(str) - 1;
200 while (sp >= str && *sp == rc) {
201 *sp = '\0';
202 sp -= 1;
203 }
204 }
205
206 static void on_connection(pa_socket_client *sc, pa_iochannel *io, void *userdata) {
207 pa_raop_client *c = userdata;
208
209 pa_assert(sc);
210 pa_assert(c);
211 pa_assert(c->sc == sc);
212 pa_assert(c->fd < 0);
213 pa_assert(c->callback);
214
215 pa_socket_client_unref(c->sc);
216 c->sc = NULL;
217
218 if (!io) {
219 pa_log("Connection failed: %s", pa_cstrerror(errno));
220 return;
221 }
222
223 c->fd = pa_iochannel_get_send_fd(io);
224
225 pa_iochannel_set_noclose(io, TRUE);
226 pa_iochannel_free(io);
227
228 pa_make_tcp_socket_low_delay(c->fd);
229
230 pa_log_debug("Connection established");
231 c->callback(c->fd, c->userdata);
232 }
233
234 static void rtsp_cb(pa_rtsp_client *rtsp, pa_rtsp_state state, pa_headerlist* headers, void *userdata) {
235 pa_raop_client* c = userdata;
236 pa_assert(c);
237 pa_assert(rtsp);
238 pa_assert(rtsp == c->rtsp);
239
240 switch (state) {
241 case STATE_CONNECT: {
242 int i;
243 uint8_t rsakey[512];
244 char *key, *iv, *sac, *sdp;
245 uint16_t rand_data;
246 const char *ip;
247 char *url;
248
249 pa_log_debug("RAOP: CONNECTED");
250 ip = pa_rtsp_localip(c->rtsp);
251 /* First of all set the url properly */
252 url = pa_sprintf_malloc("rtsp://%s/%s", ip, c->sid);
253 pa_rtsp_set_url(c->rtsp, url);
254 pa_xfree(url);
255
256 /* Now encrypt our aes_public key to send to the device */
257 i = rsa_encrypt(c->aes_key, AES_CHUNKSIZE, rsakey);
258 pa_base64_encode(rsakey, i, &key);
259 rtrimchar(key, '=');
260 pa_base64_encode(c->aes_iv, AES_CHUNKSIZE, &iv);
261 rtrimchar(iv, '=');
262
263 pa_random(&rand_data, sizeof(rand_data));
264 pa_base64_encode(&rand_data, AES_CHUNKSIZE, &sac);
265 rtrimchar(sac, '=');
266 pa_rtsp_add_header(c->rtsp, "Apple-Challenge", sac);
267 sdp = pa_sprintf_malloc(
268 "v=0\r\n"
269 "o=iTunes %s 0 IN IP4 %s\r\n"
270 "s=iTunes\r\n"
271 "c=IN IP4 %s\r\n"
272 "t=0 0\r\n"
273 "m=audio 0 RTP/AVP 96\r\n"
274 "a=rtpmap:96 AppleLossless\r\n"
275 "a=fmtp:96 4096 0 16 40 10 14 2 255 0 0 44100\r\n"
276 "a=rsaaeskey:%s\r\n"
277 "a=aesiv:%s\r\n",
278 c->sid, ip, c->host, key, iv);
279 pa_rtsp_announce(c->rtsp, sdp);
280 pa_xfree(key);
281 pa_xfree(iv);
282 pa_xfree(sac);
283 pa_xfree(sdp);
284 break;
285 }
286
287 case STATE_ANNOUNCE:
288 pa_log_debug("RAOP: ANNOUNCED");
289 pa_rtsp_remove_header(c->rtsp, "Apple-Challenge");
290 pa_rtsp_setup(c->rtsp);
291 break;
292
293 case STATE_SETUP: {
294 char *aj = pa_xstrdup(pa_headerlist_gets(headers, "Audio-Jack-Status"));
295 pa_log_debug("RAOP: SETUP");
296 if (aj) {
297 char *token, *pc;
298 char delimiters[] = ";";
299 const char* token_state = NULL;
300 c->jack_type = JACK_TYPE_ANALOG;
301 c->jack_status = JACK_STATUS_DISCONNECTED;
302
303 while ((token = pa_split(aj, delimiters, &token_state))) {
304 if ((pc = strstr(token, "="))) {
305 *pc = 0;
306 if (pa_streq(token, "type") && pa_streq(pc+1, "digital")) {
307 c->jack_type = JACK_TYPE_DIGITAL;
308 }
309 } else {
310 if (pa_streq(token, "connected"))
311 c->jack_status = JACK_STATUS_CONNECTED;
312 }
313 pa_xfree(token);
314 }
315 pa_xfree(aj);
316 } else {
317 pa_log_warn("Audio Jack Status missing");
318 }
319 pa_rtsp_record(c->rtsp, &c->seq, &c->rtptime);
320 break;
321 }
322
323 case STATE_RECORD: {
324 uint32_t port = pa_rtsp_serverport(c->rtsp);
325 pa_log_debug("RAOP: RECORDED");
326
327 if (!(c->sc = pa_socket_client_new_string(c->core->mainloop, TRUE, c->host, port))) {
328 pa_log("failed to connect to server '%s:%d'", c->host, port);
329 return;
330 }
331 pa_socket_client_set_callback(c->sc, on_connection, c);
332 break;
333 }
334
335 case STATE_FLUSH:
336 pa_log_debug("RAOP: FLUSHED");
337 break;
338
339 case STATE_TEARDOWN:
340 pa_log_debug("RAOP: TEARDOWN");
341 break;
342
343 case STATE_SET_PARAMETER:
344 pa_log_debug("RAOP: SET_PARAMETER");
345 break;
346
347 case STATE_DISCONNECTED:
348 pa_assert(c->closed_callback);
349 pa_assert(c->rtsp);
350
351 pa_log_debug("RTSP control channel closed");
352 pa_rtsp_client_free(c->rtsp);
353 c->rtsp = NULL;
354 if (c->fd > 0) {
355 /* We do not close the fd, we leave it to the closed callback to do that */
356 c->fd = -1;
357 }
358 if (c->sc) {
359 pa_socket_client_unref(c->sc);
360 c->sc = NULL;
361 }
362 pa_xfree(c->sid);
363 c->sid = NULL;
364 c->closed_callback(c->closed_userdata);
365 break;
366 }
367 }
368
369 pa_raop_client* pa_raop_client_new(pa_core *core, const char* host) {
370 pa_parsed_address a;
371 pa_raop_client* c = pa_xnew0(pa_raop_client, 1);
372
373 pa_assert(core);
374 pa_assert(host);
375
376 if (pa_parse_address(host, &a) < 0 || a.type == PA_PARSED_ADDRESS_UNIX)
377 return NULL;
378
379 c->core = core;
380 c->fd = -1;
381
382 c->host = pa_xstrdup(a.path_or_host);
383 if (a.port)
384 c->port = a.port;
385 else
386 c->port = RAOP_PORT;
387
388 if (pa_raop_connect(c)) {
389 pa_raop_client_free(c);
390 return NULL;
391 }
392 return c;
393 }
394
395
396 void pa_raop_client_free(pa_raop_client* c) {
397 pa_assert(c);
398
399 if (c->rtsp)
400 pa_rtsp_client_free(c->rtsp);
401 if (c->sid)
402 pa_xfree(c->sid);
403 pa_xfree(c->host);
404 pa_xfree(c);
405 }
406
407
408 int pa_raop_connect(pa_raop_client* c) {
409 char *sci;
410 struct {
411 uint32_t a;
412 uint32_t b;
413 uint32_t c;
414 } rand_data;
415
416 pa_assert(c);
417
418 if (c->rtsp) {
419 pa_log_debug("Connection already in progress");
420 return 0;
421 }
422
423 c->rtsp = pa_rtsp_client_new(c->core->mainloop, c->host, c->port, "iTunes/4.6 (Macintosh; U; PPC Mac OS X 10.3)");
424
425 /* Initialise the AES encryption system */
426 pa_random(c->aes_iv, sizeof(c->aes_iv));
427 pa_random(c->aes_key, sizeof(c->aes_key));
428 memcpy(c->aes_nv, c->aes_iv, sizeof(c->aes_nv));
429 AES_set_encrypt_key(c->aes_key, 128, &c->aes);
430
431 /* Generate random instance id */
432 pa_random(&rand_data, sizeof(rand_data));
433 c->sid = pa_sprintf_malloc("%u", rand_data.a);
434 sci = pa_sprintf_malloc("%08x%08x",rand_data.b, rand_data.c);
435 pa_rtsp_add_header(c->rtsp, "Client-Instance", sci);
436 pa_xfree(sci);
437 pa_rtsp_set_callback(c->rtsp, rtsp_cb, c);
438 return pa_rtsp_connect(c->rtsp);
439 }
440
441
442 int pa_raop_flush(pa_raop_client* c) {
443 pa_assert(c);
444
445 pa_rtsp_flush(c->rtsp, c->seq, c->rtptime);
446 return 0;
447 }
448
449
450 int pa_raop_client_set_volume(pa_raop_client* c, pa_volume_t volume) {
451 int rv;
452 double db;
453 char *param;
454
455 pa_assert(c);
456
457 db = pa_sw_volume_to_dB(volume);
458 if (db < VOLUME_MIN)
459 db = VOLUME_MIN;
460 else if (db > VOLUME_MAX)
461 db = VOLUME_MAX;
462
463 param = pa_sprintf_malloc("volume: %0.6f\r\n", db);
464
465 /* We just hit and hope, cannot wait for the callback */
466 rv = pa_rtsp_setparameter(c->rtsp, param);
467 pa_xfree(param);
468 return rv;
469 }
470
471
472 int pa_raop_client_encode_sample(pa_raop_client* c, pa_memchunk* raw, pa_memchunk* encoded) {
473 uint16_t len;
474 size_t bufmax;
475 uint8_t *bp, bpos;
476 uint8_t *ibp, *maxibp;
477 int size;
478 uint8_t *b, *p;
479 uint32_t bsize;
480 size_t length;
481 static uint8_t header[] = {
482 0x24, 0x00, 0x00, 0x00,
483 0xF0, 0xFF, 0x00, 0x00,
484 0x00, 0x00, 0x00, 0x00,
485 0x00, 0x00, 0x00, 0x00,
486 };
487 int header_size = sizeof(header);
488
489 pa_assert(c);
490 pa_assert(c->fd > 0);
491 pa_assert(raw);
492 pa_assert(raw->memblock);
493 pa_assert(raw->length > 0);
494 pa_assert(encoded);
495
496 /* We have to send 4 byte chunks */
497 bsize = (int)(raw->length / 4);
498 length = bsize * 4;
499
500 /* Leave 16 bytes extra to allow for the ALAC header which is about 55 bits */
501 bufmax = length + header_size + 16;
502 pa_memchunk_reset(encoded);
503 encoded->memblock = pa_memblock_new(c->core->mempool, bufmax);
504 b = pa_memblock_acquire(encoded->memblock);
505 memcpy(b, header, header_size);
506
507 /* Now write the actual samples */
508 bp = b + header_size;
509 size = bpos = 0;
510 bit_writer(&bp,&bpos,&size,1,3); /* channel=1, stereo */
511 bit_writer(&bp,&bpos,&size,0,4); /* unknown */
512 bit_writer(&bp,&bpos,&size,0,8); /* unknown */
513 bit_writer(&bp,&bpos,&size,0,4); /* unknown */
514 bit_writer(&bp,&bpos,&size,1,1); /* hassize */
515 bit_writer(&bp,&bpos,&size,0,2); /* unused */
516 bit_writer(&bp,&bpos,&size,1,1); /* is-not-compressed */
517
518 /* size of data, integer, big endian */
519 bit_writer(&bp,&bpos,&size,(bsize>>24)&0xff,8);
520 bit_writer(&bp,&bpos,&size,(bsize>>16)&0xff,8);
521 bit_writer(&bp,&bpos,&size,(bsize>>8)&0xff,8);
522 bit_writer(&bp,&bpos,&size,(bsize)&0xff,8);
523
524 ibp = p = pa_memblock_acquire(raw->memblock);
525 maxibp = p + raw->length - 4;
526 while (ibp <= maxibp) {
527 /* Byte swap stereo data */
528 bit_writer(&bp,&bpos,&size,*(ibp+1),8);
529 bit_writer(&bp,&bpos,&size,*(ibp+0),8);
530 bit_writer(&bp,&bpos,&size,*(ibp+3),8);
531 bit_writer(&bp,&bpos,&size,*(ibp+2),8);
532 ibp += 4;
533 raw->index += 4;
534 raw->length -= 4;
535 }
536 pa_memblock_release(raw->memblock);
537 encoded->length = header_size + size;
538
539 /* store the length (endian swapped: make this better) */
540 len = size + header_size - 4;
541 *(b + 2) = len >> 8;
542 *(b + 3) = len & 0xff;
543
544 /* encrypt our data */
545 aes_encrypt(c, (b + header_size), size);
546
547 /* We're done with the chunk */
548 pa_memblock_release(encoded->memblock);
549
550 return 0;
551 }
552
553
554 void pa_raop_client_set_callback(pa_raop_client* c, pa_raop_client_cb_t callback, void *userdata) {
555 pa_assert(c);
556
557 c->callback = callback;
558 c->userdata = userdata;
559 }
560
561 void pa_raop_client_set_closed_callback(pa_raop_client* c, pa_raop_client_closed_cb_t callback, void *userdata) {
562 pa_assert(c);
563
564 c->closed_callback = callback;
565 c->closed_userdata = userdata;
566 }