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