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