]> code.delx.au - pulseaudio/blob - src/modules/raop/raop_client.c
e3152dd3e1bee44d716f308d5dd5b0305dee8a79
[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 <fcntl.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <arpa/inet.h>
31 #include <unistd.h>
32 #include <sys/ioctl.h>
33
34 #ifdef HAVE_SYS_FILIO_H
35 #include <sys/filio.h>
36 #endif
37
38 /* TODO: Replace OpenSSL with NSS */
39 #include <openssl/err.h>
40 #include <openssl/rand.h>
41 #include <openssl/aes.h>
42 #include <openssl/rsa.h>
43 #include <openssl/engine.h>
44
45 #include <pulse/xmalloc.h>
46
47 #include <pulsecore/core-error.h>
48 #include <pulsecore/core-util.h>
49 #include <pulsecore/socket-util.h>
50 #include <pulsecore/log.h>
51 #include <pulsecore/macro.h>
52 #include <pulsecore/strbuf.h>
53 #include <pulsecore/random.h>
54 #include <pulsecore/poll.h>
55
56 #include "raop_client.h"
57 #include "rtsp_client.h"
58 #include "base64.h"
59
60 #define AES_CHUNKSIZE 16
61
62 #define JACK_STATUS_DISCONNECTED 0
63 #define JACK_STATUS_CONNECTED 1
64
65 #define JACK_TYPE_ANALOG 0
66 #define JACK_TYPE_DIGITAL 1
67
68 #define VOLUME_DEF -30
69 #define VOLUME_MIN -144
70 #define VOLUME_MAX 0
71
72
73 struct pa_raop_client {
74 pa_core *core;
75 char *host;
76 char *sid;
77 pa_rtsp_client *rtsp;
78
79 uint8_t jack_type;
80 uint8_t jack_status;
81
82 /* Encryption Related bits */
83 AES_KEY aes;
84 uint8_t aes_iv[AES_CHUNKSIZE]; /* initialization vector for aes-cbc */
85 uint8_t aes_nv[AES_CHUNKSIZE]; /* next vector for aes-cbc */
86 uint8_t aes_key[AES_CHUNKSIZE]; /* key for aes-cbc */
87
88 pa_socket_client *sc;
89 int fd;
90
91 uint16_t seq;
92 uint32_t rtptime;
93
94 pa_raop_client_cb_t callback;
95 void* userdata;
96 pa_raop_client_closed_cb_t closed_callback;
97 void* closed_userdata;
98 };
99
100 /**
101 * Function to write bits into a buffer.
102 * @param buffer Handle to the buffer. It will be incremented if new data requires it.
103 * @param bit_pos A pointer to a position buffer to keep track the current write location (0 for MSB, 7 for LSB)
104 * @param size A pointer to the byte size currently written. This allows the calling function to do simple buffer overflow checks
105 * @param data The data to write
106 * @param data_bit_len The number of bits from data to write
107 */
108 static inline void bit_writer(uint8_t **buffer, uint8_t *bit_pos, int *size, uint8_t data, uint8_t data_bit_len) {
109 int bits_left, bit_overflow;
110 uint8_t bit_data;
111
112 if (!data_bit_len)
113 return;
114
115 /* If bit pos is zero, we will definatly use at least one bit from the current byte so size increments. */
116 if (!*bit_pos)
117 *size += 1;
118
119 /* Calc the number of bits left in the current byte of buffer */
120 bits_left = 7 - *bit_pos + 1;
121 /* Calc the overflow of bits in relation to how much space we have left... */
122 bit_overflow = bits_left - data_bit_len;
123 if (bit_overflow >= 0) {
124 /* We can fit the new data in our current byte */
125 /* As we write from MSB->LSB we need to left shift by the overflow amount */
126 bit_data = data << bit_overflow;
127 if (*bit_pos)
128 **buffer |= bit_data;
129 else
130 **buffer = bit_data;
131 /* If our data fits exactly into the current byte, we need to increment our pointer */
132 if (0 == bit_overflow) {
133 /* Do not increment size as it will be incremeneted on next call as bit_pos is zero */
134 *buffer += 1;
135 *bit_pos = 0;
136 } else {
137 *bit_pos += data_bit_len;
138 }
139 } else {
140 /* bit_overflow is negative, there for we will need a new byte from our buffer */
141 /* Firstly fill up what's left in the current byte */
142 bit_data = data >> -bit_overflow;
143 **buffer |= bit_data;
144 /* Increment our buffer pointer and size counter*/
145 *buffer += 1;
146 *size += 1;
147 **buffer = data << (8 + bit_overflow);
148 *bit_pos = -bit_overflow;
149 }
150 }
151
152 static int rsa_encrypt(uint8_t *text, int len, uint8_t *res) {
153 const char n[] =
154 "59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUtwC"
155 "5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDR"
156 "KSKv6kDqnw4UwPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuB"
157 "OitnZ/bDzPHrTOZz0Dew0uowxf/+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJ"
158 "Q+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/UAaHqn9JdsBWLUEpVviYnh"
159 "imNVvYFZeCXg/IdTQ+x4IRdiXNv5hEew==";
160 const char e[] = "AQAB";
161 uint8_t modules[256];
162 uint8_t exponent[8];
163 int size;
164 RSA *rsa;
165
166 rsa = RSA_new();
167 size = pa_base64_decode(n, modules);
168 rsa->n = BN_bin2bn(modules, size, NULL);
169 size = pa_base64_decode(e, exponent);
170 rsa->e = BN_bin2bn(exponent, size, NULL);
171
172 size = RSA_public_encrypt(len, text, res, rsa, RSA_PKCS1_OAEP_PADDING);
173 RSA_free(rsa);
174 return size;
175 }
176
177 static int aes_encrypt(pa_raop_client* c, uint8_t *data, int size)
178 {
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 {
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_socket_set_sndbuf(io, 1024);
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, &c->seq, &c->rtptime);
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->core->mainloop, TRUE, 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_FLUSH:
338 pa_log_debug("RAOP: FLUSHED");
339 break;
340
341 case STATE_TEARDOWN:
342 pa_log_debug("RAOP: TEARDOWN");
343 break;
344
345 case STATE_SET_PARAMETER:
346 pa_log_debug("RAOP: SET_PARAMETER");
347 break;
348
349 case STATE_DISCONNECTED:
350 pa_assert(c->closed_callback);
351 pa_assert(c->rtsp);
352
353 pa_log_debug("RTSP control channel closed");
354 pa_rtsp_client_free(c->rtsp);
355 c->rtsp = NULL;
356 if (c->fd > 0) {
357 /* We do not close the fd, we leave it to the closed callback to do that */
358 c->fd = -1;
359 }
360 if (c->sc) {
361 pa_socket_client_unref(c->sc);
362 c->sc = NULL;
363 }
364 pa_xfree(c->sid);
365 c->sid = NULL;
366 c->closed_callback(c->closed_userdata);
367 break;
368 }
369 }
370
371 pa_raop_client* pa_raop_client_new(pa_core *core, const char* host)
372 {
373 pa_raop_client* c = pa_xnew0(pa_raop_client, 1);
374
375 pa_assert(core);
376 pa_assert(host);
377
378 c->core = core;
379 c->fd = -1;
380 c->host = pa_xstrdup(host);
381
382 if (pa_raop_connect(c)) {
383 pa_raop_client_free(c);
384 return NULL;
385 }
386 return c;
387 }
388
389
390 void pa_raop_client_free(pa_raop_client* c)
391 {
392 pa_assert(c);
393
394 if (c->rtsp)
395 pa_rtsp_client_free(c->rtsp);
396 pa_xfree(c->host);
397 pa_xfree(c);
398 }
399
400
401 int pa_raop_connect(pa_raop_client* c)
402 {
403 char *sci;
404 struct {
405 uint32_t a;
406 uint32_t b;
407 uint32_t c;
408 } rand_data;
409
410 pa_assert(c);
411
412 if (c->rtsp) {
413 pa_log_debug("Connection already in progress");
414 return 0;
415 }
416
417 c->rtsp = pa_rtsp_client_new(c->core->mainloop, c->host, 5000, "iTunes/4.6 (Macintosh; U; PPC Mac OS X 10.3)");
418
419 /* Initialise the AES encryption system */
420 pa_random(c->aes_iv, sizeof(c->aes_iv));
421 pa_random(c->aes_key, sizeof(c->aes_key));
422 memcpy(c->aes_nv, c->aes_iv, sizeof(c->aes_nv));
423 AES_set_encrypt_key(c->aes_key, 128, &c->aes);
424
425 /* Generate random instance id */
426 pa_random(&rand_data, sizeof(rand_data));
427 c->sid = pa_sprintf_malloc("%u", rand_data.a);
428 sci = pa_sprintf_malloc("%08x%08x",rand_data.b, rand_data.c);
429 pa_rtsp_add_header(c->rtsp, "Client-Instance", sci);
430 pa_xfree(sci);
431 pa_rtsp_set_callback(c->rtsp, rtsp_cb, c);
432 return pa_rtsp_connect(c->rtsp);
433 }
434
435
436 int pa_raop_flush(pa_raop_client* c)
437 {
438 pa_assert(c);
439
440 pa_rtsp_flush(c->rtsp, c->seq, c->rtptime);
441 return 0;
442 }
443
444
445 int pa_raop_client_set_volume(pa_raop_client* c, pa_volume_t volume)
446 {
447 int rv;
448 double db;
449 char *param;
450
451 pa_assert(c);
452
453 db = pa_sw_volume_to_dB(volume);
454 if (db < VOLUME_MIN)
455 db = VOLUME_MIN;
456 else if (db > VOLUME_MAX)
457 db = VOLUME_MAX;
458
459 param = pa_sprintf_malloc("volume: %0.6f\r\n", db);
460
461 /* We just hit and hope, cannot wait for the callback */
462 rv = pa_rtsp_setparameter(c->rtsp, param);
463 pa_xfree(param);
464 return rv;
465 }
466
467
468 int pa_raop_client_encode_sample(pa_raop_client* c, pa_memchunk* raw, pa_memchunk* encoded)
469 {
470 uint16_t len;
471 size_t bufmax;
472 uint8_t *bp, bpos;
473 uint8_t *ibp, *maxibp;
474 int size;
475 uint8_t *b, *p;
476 uint32_t bsize;
477 size_t length;
478 static uint8_t header[] = {
479 0x24, 0x00, 0x00, 0x00,
480 0xF0, 0xFF, 0x00, 0x00,
481 0x00, 0x00, 0x00, 0x00,
482 0x00, 0x00, 0x00, 0x00,
483 };
484 int header_size = sizeof(header);
485
486 pa_assert(c);
487 pa_assert(c->fd > 0);
488 pa_assert(raw);
489 pa_assert(raw->memblock);
490 pa_assert(raw->length > 0);
491 pa_assert(encoded);
492
493 /* We have to send 4 byte chunks */
494 bsize = (int)(raw->length / 4);
495 length = bsize * 4;
496
497 /* Leave 16 bytes extra to allow for the ALAC header which is about 55 bits */
498 bufmax = length + header_size + 16;
499 pa_memchunk_reset(encoded);
500 encoded->memblock = pa_memblock_new(c->core->mempool, bufmax);
501 b = pa_memblock_acquire(encoded->memblock);
502 memcpy(b, header, header_size);
503
504 /* Now write the actual samples */
505 bp = b + header_size;
506 size = bpos = 0;
507 bit_writer(&bp,&bpos,&size,1,3); /* channel=1, stereo */
508 bit_writer(&bp,&bpos,&size,0,4); /* unknown */
509 bit_writer(&bp,&bpos,&size,0,8); /* unknown */
510 bit_writer(&bp,&bpos,&size,0,4); /* unknown */
511 bit_writer(&bp,&bpos,&size,1,1); /* hassize */
512 bit_writer(&bp,&bpos,&size,0,2); /* unused */
513 bit_writer(&bp,&bpos,&size,1,1); /* is-not-compressed */
514
515 /* size of data, integer, big endian */
516 bit_writer(&bp,&bpos,&size,(bsize>>24)&0xff,8);
517 bit_writer(&bp,&bpos,&size,(bsize>>16)&0xff,8);
518 bit_writer(&bp,&bpos,&size,(bsize>>8)&0xff,8);
519 bit_writer(&bp,&bpos,&size,(bsize)&0xff,8);
520
521 ibp = p = pa_memblock_acquire(raw->memblock);
522 maxibp = p + raw->length - 4;
523 while (ibp <= maxibp) {
524 /* Byte swap stereo data */
525 bit_writer(&bp,&bpos,&size,*(ibp+1),8);
526 bit_writer(&bp,&bpos,&size,*(ibp+0),8);
527 bit_writer(&bp,&bpos,&size,*(ibp+3),8);
528 bit_writer(&bp,&bpos,&size,*(ibp+2),8);
529 ibp += 4;
530 raw->index += 4;
531 raw->length -= 4;
532 }
533 pa_memblock_release(raw->memblock);
534 encoded->length = header_size + size;
535
536 /* store the lenght (endian swapped: make this better) */
537 len = size + header_size - 4;
538 *(b + 2) = len >> 8;
539 *(b + 3) = len & 0xff;
540
541 /* encrypt our data */
542 aes_encrypt(c, (b + header_size), size);
543
544 /* We're done with the chunk */
545 pa_memblock_release(encoded->memblock);
546
547 return 0;
548 }
549
550
551 void pa_raop_client_set_callback(pa_raop_client* c, pa_raop_client_cb_t callback, void *userdata)
552 {
553 pa_assert(c);
554
555 c->callback = callback;
556 c->userdata = userdata;
557 }
558
559 void pa_raop_client_set_closed_callback(pa_raop_client* c, pa_raop_client_closed_cb_t callback, void *userdata)
560 {
561 pa_assert(c);
562
563 c->closed_callback = callback;
564 c->closed_userdata = userdata;
565 }