tizen 2.4 release
[framework/connectivity/bluez.git] / profiles / audio / avctp.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2006-2010  Nokia Corporation
6  *  Copyright (C) 2004-2010  Marcel Holtmann <marcel@holtmann.org>
7  *  Copyright (C) 2011  Texas Instruments, Inc.
8  *
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software
22  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23  *
24  */
25
26 #ifdef HAVE_CONFIG_H
27 #include <config.h>
28 #endif
29
30 #include <stdlib.h>
31 #include <stdint.h>
32 #include <stdbool.h>
33 #include <errno.h>
34 #include <unistd.h>
35 #include <assert.h>
36 #include <signal.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <fcntl.h>
40 #include <netinet/in.h>
41
42 #include <glib.h>
43
44 #include "lib/bluetooth.h"
45 #include "lib/sdp.h"
46 #include "lib/l2cap.h"
47 #include "lib/uuid.h"
48
49 #include "btio/btio.h"
50 #include "src/adapter.h"
51 #include "src/device.h"
52 #include "src/log.h"
53 #include "src/error.h"
54 #include "src/uinput.h"
55
56 #include "avctp.h"
57 #include "avrcp.h"
58
59 /* AV/C Panel 1.23, page 76:
60  * command with the pressed value is valid for two seconds
61  */
62 #define AVC_PRESS_TIMEOUT       2
63
64 #define QUIRK_NO_RELEASE 1 << 0
65
66 /* Message types */
67 #define AVCTP_COMMAND           0
68 #define AVCTP_RESPONSE          1
69
70 /* Packet types */
71 #define AVCTP_PACKET_SINGLE     0
72 #define AVCTP_PACKET_START      1
73 #define AVCTP_PACKET_CONTINUE   2
74 #define AVCTP_PACKET_END        3
75
76 #if __BYTE_ORDER == __LITTLE_ENDIAN
77
78 struct avctp_header {
79         uint8_t ipid:1;
80         uint8_t cr:1;
81         uint8_t packet_type:2;
82         uint8_t transaction:4;
83         uint16_t pid;
84 } __attribute__ ((packed));
85 #define AVCTP_HEADER_LENGTH 3
86
87 struct avc_header {
88         uint8_t code:4;
89         uint8_t _hdr0:4;
90         uint8_t subunit_id:3;
91         uint8_t subunit_type:5;
92         uint8_t opcode;
93 } __attribute__ ((packed));
94
95 #elif __BYTE_ORDER == __BIG_ENDIAN
96
97 struct avctp_header {
98         uint8_t transaction:4;
99         uint8_t packet_type:2;
100         uint8_t cr:1;
101         uint8_t ipid:1;
102         uint16_t pid;
103 } __attribute__ ((packed));
104 #define AVCTP_HEADER_LENGTH 3
105
106 struct avc_header {
107         uint8_t _hdr0:4;
108         uint8_t code:4;
109         uint8_t subunit_type:5;
110         uint8_t subunit_id:3;
111         uint8_t opcode;
112 } __attribute__ ((packed));
113
114 #else
115 #error "Unknown byte order"
116 #endif
117
118 struct avctp_state_callback {
119         avctp_state_cb cb;
120         struct btd_device *dev;
121         unsigned int id;
122         void *user_data;
123 };
124
125 struct avctp_server {
126         struct btd_adapter *adapter;
127         GIOChannel *control_io;
128         GIOChannel *browsing_io;
129         GSList *sessions;
130 };
131
132 struct avctp_control_req {
133         struct avctp_pending_req *p;
134         uint8_t code;
135         uint8_t subunit;
136         uint8_t op;
137         uint8_t *operands;
138         uint16_t operand_count;
139         avctp_rsp_cb func;
140         void *user_data;
141 };
142
143 struct avctp_browsing_req {
144         struct avctp_pending_req *p;
145         uint8_t *operands;
146         uint16_t operand_count;
147         avctp_browsing_rsp_cb func;
148         void *user_data;
149 };
150
151 typedef int (*avctp_process_cb) (void *data);
152
153 struct avctp_pending_req {
154         struct avctp_channel *chan;
155         uint8_t transaction;
156         guint timeout;
157         int err;
158         avctp_process_cb process;
159         void *data;
160         GDestroyNotify destroy;
161 };
162
163 struct avctp_channel {
164         struct avctp *session;
165         GIOChannel *io;
166         uint8_t transaction;
167         guint watch;
168         uint16_t imtu;
169         uint16_t omtu;
170         uint8_t *buffer;
171         GSList *handlers;
172         struct avctp_pending_req *p;
173         GQueue *queue;
174         GSList *processed;
175         guint process_id;
176         GDestroyNotify destroy;
177 };
178
179 struct key_pressed {
180         uint16_t op;
181         guint timer;
182 };
183
184 struct avctp {
185         struct avctp_server *server;
186         struct btd_device *device;
187
188         avctp_state_t state;
189
190         int uinput;
191
192         guint auth_id;
193         unsigned int passthrough_id;
194         unsigned int unit_id;
195         unsigned int subunit_id;
196
197         struct avctp_channel *control;
198         struct avctp_channel *browsing;
199
200         struct avctp_passthrough_handler *handler;
201
202         uint8_t key_quirks[256];
203         struct key_pressed key;
204         bool initiator;
205 };
206
207 struct avctp_passthrough_handler {
208         avctp_passthrough_cb cb;
209         void *user_data;
210         unsigned int id;
211 };
212
213 struct avctp_pdu_handler {
214         uint8_t opcode;
215         avctp_control_pdu_cb cb;
216         void *user_data;
217         unsigned int id;
218 };
219
220 struct avctp_browsing_pdu_handler {
221         avctp_browsing_pdu_cb cb;
222         void *user_data;
223         unsigned int id;
224         GDestroyNotify destroy;
225 };
226
227 static struct {
228         const char *name;
229         uint8_t avc;
230         uint16_t uinput;
231 } key_map[] = {
232         { "SELECT",             AVC_SELECT,             KEY_SELECT },
233         { "UP",                 AVC_UP,                 KEY_UP },
234         { "DOWN",               AVC_DOWN,               KEY_DOWN },
235         { "LEFT",               AVC_LEFT,               KEY_LEFT },
236         { "RIGHT",              AVC_RIGHT,              KEY_RIGHT },
237         { "ROOT MENU",          AVC_ROOT_MENU,          KEY_MENU },
238         { "CONTENTS MENU",      AVC_CONTENTS_MENU,      KEY_PROGRAM },
239         { "FAVORITE MENU",      AVC_FAVORITE_MENU,      KEY_FAVORITES },
240         { "EXIT",               AVC_EXIT,               KEY_EXIT },
241         { "ON DEMAND MENU",     AVC_ON_DEMAND_MENU,     KEY_MENU },
242         { "APPS MENU",          AVC_APPS_MENU,          KEY_MENU },
243         { "0",                  AVC_0,                  KEY_0 },
244         { "1",                  AVC_1,                  KEY_1 },
245         { "2",                  AVC_2,                  KEY_2 },
246         { "3",                  AVC_3,                  KEY_3 },
247         { "4",                  AVC_4,                  KEY_4 },
248         { "5",                  AVC_5,                  KEY_5 },
249         { "6",                  AVC_6,                  KEY_6 },
250         { "7",                  AVC_7,                  KEY_7 },
251         { "8",                  AVC_8,                  KEY_8 },
252         { "9",                  AVC_9,                  KEY_9 },
253         { "DOT",                AVC_DOT,                KEY_DOT },
254         { "ENTER",              AVC_ENTER,              KEY_ENTER },
255         { "CHANNEL UP",         AVC_CHANNEL_UP,         KEY_CHANNELUP },
256         { "CHANNEL DOWN",       AVC_CHANNEL_DOWN,       KEY_CHANNELDOWN },
257         { "CHANNEL PREVIOUS",   AVC_CHANNEL_PREVIOUS,   KEY_LAST },
258         { "INPUT SELECT",       AVC_INPUT_SELECT,       KEY_CONFIG },
259         { "INFO",               AVC_INFO,               KEY_INFO },
260         { "HELP",               AVC_HELP,               KEY_HELP },
261         { "POWER",              AVC_POWER,              KEY_POWER2 },
262         { "VOLUME UP",          AVC_VOLUME_UP,          KEY_VOLUMEUP },
263         { "VOLUME DOWN",        AVC_VOLUME_DOWN,        KEY_VOLUMEDOWN },
264         { "MUTE",               AVC_MUTE,               KEY_MUTE },
265         { "PLAY",               AVC_PLAY,               KEY_PLAYCD },
266         { "STOP",               AVC_STOP,               KEY_STOPCD },
267         { "PAUSE",              AVC_PAUSE,              KEY_PAUSECD },
268         { "FORWARD",            AVC_FORWARD,            KEY_NEXTSONG },
269         { "BACKWARD",           AVC_BACKWARD,           KEY_PREVIOUSSONG },
270         { "RECORD",             AVC_RECORD,             KEY_RECORD },
271         { "REWIND",             AVC_REWIND,             KEY_REWIND },
272         { "FAST FORWARD",       AVC_FAST_FORWARD,       KEY_FASTFORWARD },
273         { "LIST",               AVC_LIST,               KEY_LIST },
274         { "F1",                 AVC_F1,                 KEY_F1 },
275         { "F2",                 AVC_F2,                 KEY_F2 },
276         { "F3",                 AVC_F3,                 KEY_F3 },
277         { "F4",                 AVC_F4,                 KEY_F4 },
278         { "F5",                 AVC_F5,                 KEY_F5 },
279         { "F6",                 AVC_F6,                 KEY_F6 },
280         { "F7",                 AVC_F7,                 KEY_F7 },
281         { "F8",                 AVC_F8,                 KEY_F8 },
282         { "F9",                 AVC_F9,                 KEY_F9 },
283         { "RED",                AVC_RED,                KEY_RED },
284         { "GREEN",              AVC_GREEN,              KEY_GREEN },
285         { "BLUE",               AVC_BLUE,               KEY_BLUE },
286         { "YELLOW",             AVC_YELLOW,             KEY_YELLOW },
287         { NULL }
288 };
289
290 static GSList *callbacks = NULL;
291 static GSList *servers = NULL;
292
293 static void auth_cb(DBusError *derr, void *user_data);
294 static gboolean process_queue(gpointer user_data);
295 static gboolean avctp_passthrough_rsp(struct avctp *session, uint8_t code,
296                                         uint8_t subunit, uint8_t *operands,
297                                         size_t operand_count, void *user_data);
298
299 static int send_event(int fd, uint16_t type, uint16_t code, int32_t value)
300 {
301         struct uinput_event event;
302
303         memset(&event, 0, sizeof(event));
304         event.type      = type;
305         event.code      = code;
306         event.value     = value;
307
308         return write(fd, &event, sizeof(event));
309 }
310
311 static void send_key(int fd, uint16_t key, int pressed)
312 {
313         if (fd < 0)
314                 return;
315
316         send_event(fd, EV_KEY, key, pressed);
317         send_event(fd, EV_SYN, SYN_REPORT, 0);
318 }
319
320 static gboolean auto_release(gpointer user_data)
321 {
322         struct avctp *session = user_data;
323
324         session->key.timer = 0;
325
326         DBG("AV/C: key press timeout");
327
328         send_key(session->uinput, session->key.op, 0);
329
330         return FALSE;
331 }
332
333 static void handle_press(struct avctp *session, uint16_t op)
334 {
335         if (session->key.timer > 0) {
336                 g_source_remove(session->key.timer);
337
338                 /* Only auto release if keys are different */
339                 if (session->key.op == op)
340                         goto done;
341
342                 send_key(session->uinput, session->key.op, 0);
343         }
344
345         session->key.op = op;
346
347         send_key(session->uinput, op, 1);
348
349 done:
350         session->key.timer = g_timeout_add_seconds(AVC_PRESS_TIMEOUT,
351                                                         auto_release, session);
352 }
353
354 static void handle_release(struct avctp *session, uint16_t op)
355 {
356         if (session->key.timer > 0) {
357                 g_source_remove(session->key.timer);
358                 session->key.timer = 0;
359         }
360
361         send_key(session->uinput, op, 0);
362 }
363 #ifdef __TIZEN_PATCH__
364 extern void avrcp_stop_position_timer(void);
365 #endif
366
367 static size_t handle_panel_passthrough(struct avctp *session,
368                                         uint8_t transaction, uint8_t *code,
369                                         uint8_t *subunit, uint8_t *operands,
370                                         size_t operand_count, void *user_data)
371 {
372         struct avctp_passthrough_handler *handler = session->handler;
373         const char *status;
374         int pressed, i;
375
376         if (*code != AVC_CTYPE_CONTROL || *subunit != AVC_SUBUNIT_PANEL) {
377                 *code = AVC_CTYPE_REJECTED;
378                 return operand_count;
379         }
380
381         if (operand_count == 0)
382                 goto done;
383
384         if (operands[0] & 0x80) {
385                 status = "released";
386                 pressed = 0;
387         } else {
388                 status = "pressed";
389                 pressed = 1;
390         }
391
392         if (session->key.timer == 0 && handler != NULL) {
393                 if (handler->cb(session, operands[0] & 0x7F,
394                                                 pressed, handler->user_data))
395                         goto done;
396         }
397
398         for (i = 0; key_map[i].name != NULL; i++) {
399                 uint8_t key_quirks;
400
401                 if ((operands[0] & 0x7F) != key_map[i].avc)
402                         continue;
403
404                 DBG("AV/C: %s %s", key_map[i].name, status);
405
406                 key_quirks = session->key_quirks[key_map[i].avc];
407
408                 if (key_quirks & QUIRK_NO_RELEASE) {
409                         if (!pressed) {
410                                 DBG("AV/C: Ignoring release");
411                                 break;
412                         }
413
414                         DBG("AV/C: treating key press as press + release");
415                         send_key(session->uinput, key_map[i].uinput, 1);
416                         send_key(session->uinput, key_map[i].uinput, 0);
417                         break;
418                 }
419
420                 if (pressed) {
421                         handle_press(session, key_map[i].uinput);
422 #ifdef __TIZEN_PATCH__
423                         if (key_map[i].avc == AVC_REWIND)
424                                 avrcp_stop_position_timer();
425 #endif
426                 } else
427                         handle_release(session, key_map[i].uinput);
428
429                 break;
430         }
431
432         if (key_map[i].name == NULL) {
433                 DBG("AV/C: unknown button 0x%02X %s",
434                                                 operands[0] & 0x7F, status);
435                 *code = AVC_CTYPE_NOT_IMPLEMENTED;
436                 return operand_count;
437         }
438
439 done:
440         *code = AVC_CTYPE_ACCEPTED;
441         return operand_count;
442 }
443
444 static size_t handle_unit_info(struct avctp *session,
445                                         uint8_t transaction, uint8_t *code,
446                                         uint8_t *subunit, uint8_t *operands,
447                                         size_t operand_count, void *user_data)
448 {
449         if (*code != AVC_CTYPE_STATUS) {
450                 *code = AVC_CTYPE_REJECTED;
451                 return 0;
452         }
453
454         *code = AVC_CTYPE_STABLE;
455
456         /* The first operand should be 0x07 for the UNITINFO response.
457          * Neither AVRCP (section 22.1, page 117) nor AVC Digital
458          * Interface Command Set (section 9.2.1, page 45) specs
459          * explain this value but both use it */
460         if (operand_count >= 1)
461                 operands[0] = 0x07;
462         if (operand_count >= 2)
463                 operands[1] = AVC_SUBUNIT_PANEL << 3;
464
465         DBG("reply to AVC_OP_UNITINFO");
466
467         return operand_count;
468 }
469
470 static size_t handle_subunit_info(struct avctp *session,
471                                         uint8_t transaction, uint8_t *code,
472                                         uint8_t *subunit, uint8_t *operands,
473                                         size_t operand_count, void *user_data)
474 {
475         if (*code != AVC_CTYPE_STATUS) {
476                 *code = AVC_CTYPE_REJECTED;
477                 return 0;
478         }
479
480         *code = AVC_CTYPE_STABLE;
481
482         /* The first operand should be 0x07 for the UNITINFO response.
483          * Neither AVRCP (section 22.1, page 117) nor AVC Digital
484          * Interface Command Set (section 9.2.1, page 45) specs
485          * explain this value but both use it */
486         if (operand_count >= 2)
487                 operands[1] = AVC_SUBUNIT_PANEL << 3;
488
489         DBG("reply to AVC_OP_SUBUNITINFO");
490
491         return operand_count;
492 }
493
494 static struct avctp_pdu_handler *find_handler(GSList *list, uint8_t opcode)
495 {
496         for (; list; list = list->next) {
497                 struct avctp_pdu_handler *handler = list->data;
498
499                 if (handler->opcode == opcode)
500                         return handler;
501         }
502
503         return NULL;
504 }
505
506 static void pending_destroy(gpointer data, gpointer user_data)
507 {
508         struct avctp_pending_req *req = data;
509
510         if (req->destroy)
511                 req->destroy(req->data);
512
513         if (req->timeout > 0)
514                 g_source_remove(req->timeout);
515
516         g_free(req);
517 }
518
519 static void avctp_channel_destroy(struct avctp_channel *chan)
520 {
521         g_io_channel_shutdown(chan->io, TRUE, NULL);
522         g_io_channel_unref(chan->io);
523
524         if (chan->watch)
525                 g_source_remove(chan->watch);
526
527         if (chan->p)
528                 pending_destroy(chan->p, NULL);
529
530         if (chan->process_id > 0)
531                 g_source_remove(chan->process_id);
532
533         if (chan->destroy)
534                 chan->destroy(chan);
535
536         g_free(chan->buffer);
537         g_queue_foreach(chan->queue, pending_destroy, NULL);
538         g_queue_free(chan->queue);
539         g_slist_foreach(chan->processed, pending_destroy, NULL);
540         g_slist_free(chan->processed);
541         g_slist_free_full(chan->handlers, g_free);
542         g_free(chan);
543 }
544
545 static void avctp_disconnected(struct avctp *session)
546 {
547         struct avctp_server *server;
548
549         if (!session)
550                 return;
551
552         if (session->browsing)
553                 avctp_channel_destroy(session->browsing);
554
555         if (session->control)
556                 avctp_channel_destroy(session->control);
557
558         if (session->auth_id != 0) {
559                 btd_cancel_authorization(session->auth_id);
560                 session->auth_id = 0;
561         }
562
563         if (session->key.timer > 0)
564                 g_source_remove(session->key.timer);
565
566         if (session->uinput >= 0) {
567                 char address[18];
568
569                 ba2str(device_get_address(session->device), address);
570                 DBG("AVCTP: closing uinput for %s", address);
571
572                 ioctl(session->uinput, UI_DEV_DESTROY);
573                 close(session->uinput);
574                 session->uinput = -1;
575         }
576
577         server = session->server;
578         server->sessions = g_slist_remove(server->sessions, session);
579         btd_device_unref(session->device);
580         g_free(session);
581 }
582
583 static void avctp_set_state(struct avctp *session, avctp_state_t new_state,
584                                                                         int err)
585 {
586         GSList *l;
587         avctp_state_t old_state = session->state;
588
589         session->state = new_state;
590
591         for (l = callbacks; l != NULL; l = l->next) {
592                 struct avctp_state_callback *cb = l->data;
593
594                 if (cb->dev && cb->dev != session->device)
595                         continue;
596
597                 cb->cb(session->device, old_state, new_state, err,
598                                                                 cb->user_data);
599         }
600
601         switch (new_state) {
602         case AVCTP_STATE_DISCONNECTED:
603                 DBG("AVCTP Disconnected");
604                 avctp_disconnected(session);
605                 break;
606         case AVCTP_STATE_CONNECTING:
607                 DBG("AVCTP Connecting");
608                 break;
609         case AVCTP_STATE_CONNECTED:
610                 DBG("AVCTP Connected");
611                 break;
612         case AVCTP_STATE_BROWSING_CONNECTING:
613                 DBG("AVCTP Browsing Connecting");
614                 break;
615         case AVCTP_STATE_BROWSING_CONNECTED:
616                 DBG("AVCTP Browsing Connected");
617                 break;
618         default:
619                 error("Invalid AVCTP state %d", new_state);
620                 return;
621         }
622 }
623
624 static int avctp_send(struct avctp_channel *control, uint8_t transaction,
625                                 uint8_t cr, uint8_t code,
626                                 uint8_t subunit, uint8_t opcode,
627                                 uint8_t *operands, size_t operand_count)
628 {
629         struct avctp_header *avctp;
630         struct avc_header *avc;
631         struct msghdr msg;
632         struct iovec iov[2];
633         int sk, err = 0;
634
635         iov[0].iov_base = control->buffer;
636         iov[0].iov_len  = sizeof(*avctp) + sizeof(*avc);
637         iov[1].iov_base = operands;
638         iov[1].iov_len  = operand_count;
639
640         if (control->omtu < (iov[0].iov_len + iov[1].iov_len))
641                 return -EOVERFLOW;
642
643         sk = g_io_channel_unix_get_fd(control->io);
644
645         memset(control->buffer, 0, iov[0].iov_len);
646
647         avctp = (void *) control->buffer;
648         avc = (void *) avctp + sizeof(*avctp);
649
650         avctp->transaction = transaction;
651         avctp->packet_type = AVCTP_PACKET_SINGLE;
652         avctp->cr = cr;
653         avctp->pid = htons(AV_REMOTE_SVCLASS_ID);
654
655         avc->code = code;
656         avc->subunit_type = subunit;
657         avc->opcode = opcode;
658
659         memset(&msg, 0, sizeof(msg));
660         msg.msg_iov = iov;
661         msg.msg_iovlen = 2;
662
663         if (sendmsg(sk, &msg, 0) < 0)
664                 err = -errno;
665
666         return err;
667 }
668
669 static int avctp_browsing_send(struct avctp_channel *browsing,
670                                 uint8_t transaction, uint8_t cr,
671                                 uint8_t *operands, size_t operand_count)
672 {
673         struct avctp_header *avctp;
674         struct msghdr msg;
675         struct iovec iov[2];
676         int sk, err = 0;
677
678         iov[0].iov_base = browsing->buffer;
679         iov[0].iov_len  = sizeof(*avctp);
680         iov[1].iov_base = operands;
681         iov[1].iov_len  = operand_count;
682
683         if (browsing->omtu < (iov[0].iov_len + iov[1].iov_len))
684                 return -EOVERFLOW;
685
686         sk = g_io_channel_unix_get_fd(browsing->io);
687
688         memset(browsing->buffer, 0, iov[0].iov_len);
689
690         avctp = (void *) browsing->buffer;
691
692         avctp->transaction = transaction;
693         avctp->packet_type = AVCTP_PACKET_SINGLE;
694         avctp->cr = cr;
695         avctp->pid = htons(AV_REMOTE_SVCLASS_ID);
696
697         memset(&msg, 0, sizeof(msg));
698         msg.msg_iov = iov;
699         msg.msg_iovlen = 2;
700
701         if (sendmsg(sk, &msg, 0) < 0)
702                 err = -errno;
703
704         return err;
705 }
706
707 static void control_req_destroy(void *data)
708 {
709         struct avctp_control_req *req = data;
710         struct avctp_pending_req *p = req->p;
711         struct avctp *session = p->chan->session;
712
713         if (p->err == 0 || req->func == NULL)
714                 goto done;
715
716         req->func(session, AVC_CTYPE_REJECTED, req->subunit, NULL, 0,
717                                                         req->user_data);
718
719 done:
720         g_free(req->operands);
721         g_free(req);
722 }
723
724 static void browsing_req_destroy(void *data)
725 {
726         struct avctp_browsing_req *req = data;
727         struct avctp_pending_req *p = req->p;
728         struct avctp *session = p->chan->session;
729
730         if (p->err == 0 || req->func == NULL)
731                 goto done;
732
733         req->func(session, NULL, 0, req->user_data);
734
735 done:
736         g_free(req->operands);
737         g_free(req);
738 }
739
740 static gboolean req_timeout(gpointer user_data)
741 {
742         struct avctp_channel *chan = user_data;
743         struct avctp_pending_req *p = chan->p;
744
745         DBG("transaction %u", p->transaction);
746
747         p->timeout = 0;
748         p->err = -ETIMEDOUT;
749
750         pending_destroy(p, NULL);
751         chan->p = NULL;
752
753         if (chan->process_id == 0)
754                 chan->process_id = g_idle_add(process_queue, chan);
755
756         return FALSE;
757 }
758
759 static int process_control(void *data)
760 {
761         struct avctp_control_req *req = data;
762         struct avctp_pending_req *p = req->p;
763
764         return avctp_send(p->chan, p->transaction, AVCTP_COMMAND, req->code,
765                                         req->subunit, req->op,
766                                         req->operands, req->operand_count);
767 }
768
769 static int process_browsing(void *data)
770 {
771         struct avctp_browsing_req *req = data;
772         struct avctp_pending_req *p = req->p;
773
774         return avctp_browsing_send(p->chan, p->transaction, AVCTP_COMMAND,
775                                         req->operands, req->operand_count);
776 }
777
778 static gboolean process_queue(void *user_data)
779 {
780         struct avctp_channel *chan = user_data;
781         struct avctp_pending_req *p = chan->p;
782
783         chan->process_id = 0;
784
785         if (p != NULL)
786                 return FALSE;
787
788         while ((p = g_queue_pop_head(chan->queue))) {
789
790                 if (p->process(p->data) == 0)
791                         break;
792
793                 pending_destroy(p, NULL);
794         }
795
796         if (p == NULL)
797                 return FALSE;
798
799         chan->p = p;
800         p->timeout = g_timeout_add_seconds(2, req_timeout, chan);
801
802         return FALSE;
803
804 }
805
806 static void control_response(struct avctp_channel *control,
807                                         struct avctp_header *avctp,
808                                         struct avc_header *avc,
809                                         uint8_t *operands,
810                                         size_t operand_count)
811 {
812         struct avctp_pending_req *p = control->p;
813         struct avctp_control_req *req;
814         GSList *l;
815
816         if (p && p->transaction == avctp->transaction) {
817                 control->processed = g_slist_prepend(control->processed, p);
818
819                 if (p->timeout > 0) {
820                         g_source_remove(p->timeout);
821                         p->timeout = 0;
822                 }
823
824                 control->p = NULL;
825
826                 if (control->process_id == 0)
827                         control->process_id = g_idle_add(process_queue,
828                                                                 control);
829         }
830
831         for (l = control->processed; l; l = l->next) {
832                 p = l->data;
833                 req = p->data;
834
835                 if (p->transaction != avctp->transaction)
836                         continue;
837
838                 if (req->func && req->func(control->session, avc->code,
839                                                 avc->subunit_type,
840                                                 operands, operand_count,
841                                                 req->user_data))
842                         return;
843
844                 control->processed = g_slist_remove(control->processed, p);
845                 pending_destroy(p, NULL);
846
847                 return;
848         }
849 }
850
851 static void browsing_response(struct avctp_channel *browsing,
852                                         struct avctp_header *avctp,
853                                         uint8_t *operands,
854                                         size_t operand_count)
855 {
856         struct avctp_pending_req *p = browsing->p;
857         struct avctp_browsing_req *req;
858         GSList *l;
859
860         if (p && p->transaction == avctp->transaction) {
861                 browsing->processed = g_slist_prepend(browsing->processed, p);
862
863                 if (p->timeout > 0) {
864                         g_source_remove(p->timeout);
865                         p->timeout = 0;
866                 }
867
868                 browsing->p = NULL;
869
870                 if (browsing->process_id == 0)
871                         browsing->process_id = g_idle_add(process_queue,
872                                                                 browsing);
873         }
874
875         for (l = browsing->processed; l; l = l->next) {
876                 p = l->data;
877                 req = p->data;
878
879                 if (p->transaction != avctp->transaction)
880                         continue;
881
882                 if (req->func && req->func(browsing->session, operands,
883                                                 operand_count, req->user_data))
884                         return;
885
886                 browsing->processed = g_slist_remove(browsing->processed, p);
887                 pending_destroy(p, NULL);
888
889                 return;
890         }
891 }
892
893 static gboolean session_browsing_cb(GIOChannel *chan, GIOCondition cond,
894                                 gpointer data)
895 {
896         struct avctp *session = data;
897         struct avctp_channel *browsing = session->browsing;
898         uint8_t *buf = browsing->buffer;
899         uint8_t *operands;
900         struct avctp_header *avctp;
901         int sock, ret, packet_size, operand_count;
902         struct avctp_browsing_pdu_handler *handler;
903
904         if (cond & (G_IO_ERR | G_IO_HUP | G_IO_NVAL))
905                 goto failed;
906
907         sock = g_io_channel_unix_get_fd(chan);
908
909         ret = read(sock, buf, browsing->imtu);
910         if (ret <= 0)
911                 goto failed;
912
913         avctp = (struct avctp_header *) buf;
914
915         if (avctp->packet_type != AVCTP_PACKET_SINGLE)
916                 goto failed;
917
918         operands = buf + AVCTP_HEADER_LENGTH;
919         ret -= AVCTP_HEADER_LENGTH;
920         operand_count = ret;
921
922         if (avctp->cr == AVCTP_RESPONSE) {
923                 browsing_response(browsing, avctp, operands, operand_count);
924                 return TRUE;
925         }
926
927         packet_size = AVCTP_HEADER_LENGTH;
928         avctp->cr = AVCTP_RESPONSE;
929
930         handler = g_slist_nth_data(browsing->handlers, 0);
931         if (handler == NULL) {
932                 DBG("handler not found");
933                 packet_size += avrcp_browsing_general_reject(operands);
934                 goto send;
935         }
936
937         packet_size += handler->cb(session, avctp->transaction,
938                                                 operands, operand_count,
939                                                 handler->user_data);
940
941 send:
942         if (packet_size != 0) {
943                 ret = write(sock, buf, packet_size);
944                 if (ret != packet_size)
945                         goto failed;
946         }
947
948         return TRUE;
949
950 failed:
951         DBG("AVCTP Browsing: disconnected");
952         avctp_set_state(session, AVCTP_STATE_CONNECTED, 0);
953
954         if (session->browsing) {
955                 avctp_channel_destroy(session->browsing);
956                 session->browsing = NULL;
957         }
958
959         return FALSE;
960 }
961
962 static gboolean session_cb(GIOChannel *chan, GIOCondition cond, gpointer data)
963 {
964         struct avctp *session = data;
965         struct avctp_channel *control = session->control;
966         uint8_t *buf = control->buffer;
967         uint8_t *operands, code, subunit;
968         struct avctp_header *avctp;
969         struct avc_header *avc;
970         int ret, packet_size, operand_count, sock;
971         struct avctp_pdu_handler *handler;
972
973         if (cond & (G_IO_ERR | G_IO_HUP | G_IO_NVAL))
974                 goto failed;
975
976         sock = g_io_channel_unix_get_fd(chan);
977
978         ret = read(sock, buf, control->imtu);
979         if (ret <= 0)
980                 goto failed;
981
982         if (ret < AVCTP_HEADER_LENGTH) {
983                 error("Too small AVCTP packet");
984                 goto failed;
985         }
986
987         avctp = (struct avctp_header *) buf;
988
989         ret -= AVCTP_HEADER_LENGTH;
990         if (ret < AVC_HEADER_LENGTH) {
991                 error("Too small AVC packet");
992                 goto failed;
993         }
994
995         avc = (struct avc_header *) (buf + AVCTP_HEADER_LENGTH);
996
997         ret -= AVC_HEADER_LENGTH;
998
999         operands = (uint8_t *) avc + AVC_HEADER_LENGTH;
1000         operand_count = ret;
1001
1002         if (avctp->cr == AVCTP_RESPONSE) {
1003                 control_response(control, avctp, avc, operands, operand_count);
1004                 return TRUE;
1005         }
1006
1007         packet_size = AVCTP_HEADER_LENGTH + AVC_HEADER_LENGTH;
1008         avctp->cr = AVCTP_RESPONSE;
1009
1010         if (avctp->packet_type != AVCTP_PACKET_SINGLE) {
1011                 avc->code = AVC_CTYPE_NOT_IMPLEMENTED;
1012                 goto done;
1013         }
1014
1015         if (avctp->pid != htons(AV_REMOTE_SVCLASS_ID)) {
1016                 avctp->ipid = 1;
1017                 packet_size = AVCTP_HEADER_LENGTH;
1018                 goto done;
1019         }
1020
1021         handler = find_handler(control->handlers, avc->opcode);
1022         if (!handler) {
1023                 DBG("handler not found for 0x%02x", avc->opcode);
1024                 packet_size += avrcp_handle_vendor_reject(&code, operands);
1025                 avc->code = code;
1026                 goto done;
1027         }
1028
1029         code = avc->code;
1030         subunit = avc->subunit_type;
1031
1032         packet_size += handler->cb(session, avctp->transaction, &code,
1033                                         &subunit, operands, operand_count,
1034                                         handler->user_data);
1035
1036         avc->code = code;
1037         avc->subunit_type = subunit;
1038
1039 done:
1040         ret = write(sock, buf, packet_size);
1041         if (ret != packet_size)
1042                 goto failed;
1043
1044         return TRUE;
1045
1046 failed:
1047         DBG("AVCTP session %p got disconnected", session);
1048         avctp_set_state(session, AVCTP_STATE_DISCONNECTED, -EIO);
1049         return FALSE;
1050 }
1051
1052 static int uinput_create(char *name)
1053 {
1054         struct uinput_dev dev;
1055         int fd, err, i;
1056
1057         fd = open("/dev/uinput", O_RDWR);
1058         if (fd < 0) {
1059                 fd = open("/dev/input/uinput", O_RDWR);
1060                 if (fd < 0) {
1061                         fd = open("/dev/misc/uinput", O_RDWR);
1062                         if (fd < 0) {
1063                                 err = -errno;
1064                                 error("Can't open input device: %s (%d)",
1065                                                         strerror(-err), -err);
1066                                 return err;
1067                         }
1068                 }
1069         }
1070
1071         memset(&dev, 0, sizeof(dev));
1072         if (name)
1073                 strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE - 1);
1074
1075         dev.id.bustype = BUS_BLUETOOTH;
1076         dev.id.vendor  = 0x0000;
1077         dev.id.product = 0x0000;
1078         dev.id.version = 0x0000;
1079
1080         if (write(fd, &dev, sizeof(dev)) < 0) {
1081                 err = -errno;
1082                 error("Can't write device information: %s (%d)",
1083                                                 strerror(-err), -err);
1084                 close(fd);
1085                 return err;
1086         }
1087
1088         ioctl(fd, UI_SET_EVBIT, EV_KEY);
1089         ioctl(fd, UI_SET_EVBIT, EV_REL);
1090         ioctl(fd, UI_SET_EVBIT, EV_REP);
1091         ioctl(fd, UI_SET_EVBIT, EV_SYN);
1092
1093         for (i = 0; key_map[i].name != NULL; i++)
1094                 ioctl(fd, UI_SET_KEYBIT, key_map[i].uinput);
1095
1096         if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) {
1097                 err = -errno;
1098                 error("Can't create uinput device: %s (%d)",
1099                                                 strerror(-err), -err);
1100                 close(fd);
1101                 return err;
1102         }
1103
1104         send_event(fd, EV_REP, REP_DELAY, 300);
1105
1106         return fd;
1107 }
1108
1109 static void init_uinput(struct avctp *session)
1110 {
1111         char address[18], name[248 + 1];
1112
1113         device_get_name(session->device, name, sizeof(name));
1114         if (g_str_equal(name, "Nokia CK-20W")) {
1115                 session->key_quirks[AVC_FORWARD] |= QUIRK_NO_RELEASE;
1116                 session->key_quirks[AVC_BACKWARD] |= QUIRK_NO_RELEASE;
1117                 session->key_quirks[AVC_PLAY] |= QUIRK_NO_RELEASE;
1118                 session->key_quirks[AVC_PAUSE] |= QUIRK_NO_RELEASE;
1119         }
1120
1121         ba2str(device_get_address(session->device), address);
1122         session->uinput = uinput_create(address);
1123         if (session->uinput < 0)
1124                 error("AVRCP: failed to init uinput for %s", address);
1125         else
1126                 DBG("AVRCP: uinput initialized for %s", address);
1127 }
1128
1129 static struct avctp_channel *avctp_channel_create(struct avctp *session,
1130                                                         GIOChannel *io,
1131                                                         GDestroyNotify destroy)
1132 {
1133         struct avctp_channel *chan;
1134
1135         chan = g_new0(struct avctp_channel, 1);
1136         chan->session = session;
1137         chan->io = g_io_channel_ref(io);
1138         chan->queue = g_queue_new();
1139         chan->destroy = destroy;
1140
1141         return chan;
1142 }
1143
1144 static void handler_free(void *data)
1145 {
1146         struct avctp_browsing_pdu_handler *handler = data;
1147
1148         if (handler->destroy)
1149                 handler->destroy(handler->user_data);
1150
1151         g_free(data);
1152 }
1153
1154 static void avctp_destroy_browsing(void *data)
1155 {
1156         struct avctp_channel *chan = data;
1157
1158         g_slist_free_full(chan->handlers, handler_free);
1159
1160         chan->handlers = NULL;
1161 }
1162
1163 static void avctp_connect_browsing_cb(GIOChannel *chan, GError *err,
1164                                                         gpointer data)
1165 {
1166         struct avctp *session = data;
1167         struct avctp_channel *browsing = session->browsing;
1168         char address[18];
1169         uint16_t imtu, omtu;
1170         GError *gerr = NULL;
1171
1172         if (err) {
1173                 error("Browsing: %s", err->message);
1174                 goto fail;
1175         }
1176
1177         bt_io_get(chan, &gerr,
1178                         BT_IO_OPT_DEST, &address,
1179                         BT_IO_OPT_IMTU, &imtu,
1180                         BT_IO_OPT_OMTU, &omtu,
1181                         BT_IO_OPT_INVALID);
1182         if (gerr) {
1183                 error("%s", gerr->message);
1184                 g_io_channel_shutdown(chan, TRUE, NULL);
1185                 g_io_channel_unref(chan);
1186                 g_error_free(gerr);
1187                 goto fail;
1188         }
1189
1190         DBG("AVCTP Browsing: connected to %s", address);
1191
1192         if (browsing == NULL) {
1193                 browsing = avctp_channel_create(session, chan,
1194                                                 avctp_destroy_browsing);
1195                 session->browsing = browsing;
1196         }
1197
1198         browsing->imtu = imtu;
1199         browsing->omtu = omtu;
1200         browsing->buffer = g_malloc0(MAX(imtu, omtu));
1201         browsing->watch = g_io_add_watch(session->browsing->io,
1202                                 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
1203                                 (GIOFunc) session_browsing_cb, session);
1204
1205         avctp_set_state(session, AVCTP_STATE_BROWSING_CONNECTED, 0);
1206
1207         /* Process any request that was pending the connection to complete */
1208         if (browsing->process_id == 0 && !g_queue_is_empty(browsing->queue))
1209                 browsing->process_id = g_idle_add(process_queue, browsing);
1210
1211         return;
1212
1213 fail:
1214         avctp_set_state(session, AVCTP_STATE_CONNECTED, 0);
1215
1216         if (session->browsing) {
1217                 avctp_channel_destroy(session->browsing);
1218                 session->browsing = NULL;
1219         }
1220 }
1221
1222 static void avctp_connect_cb(GIOChannel *chan, GError *err, gpointer data)
1223 {
1224         struct avctp *session = data;
1225         char address[18];
1226         uint16_t imtu, omtu;
1227         GError *gerr = NULL;
1228
1229         if (err) {
1230                 avctp_set_state(session, AVCTP_STATE_DISCONNECTED, -EIO);
1231                 error("%s", err->message);
1232                 return;
1233         }
1234
1235         bt_io_get(chan, &gerr,
1236                         BT_IO_OPT_DEST, &address,
1237                         BT_IO_OPT_IMTU, &imtu,
1238                         BT_IO_OPT_IMTU, &omtu,
1239                         BT_IO_OPT_INVALID);
1240         if (gerr) {
1241                 avctp_set_state(session, AVCTP_STATE_DISCONNECTED, -EIO);
1242                 error("%s", gerr->message);
1243                 g_error_free(gerr);
1244                 return;
1245         }
1246
1247         DBG("AVCTP: connected to %s", address);
1248
1249         if (session->control == NULL)
1250                 session->control = avctp_channel_create(session, chan, NULL);
1251
1252         session->control->imtu = imtu;
1253         session->control->omtu = omtu;
1254         session->control->buffer = g_malloc0(MAX(imtu, omtu));
1255         session->control->watch = g_io_add_watch(session->control->io,
1256                                 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
1257                                 (GIOFunc) session_cb, session);
1258
1259         session->passthrough_id = avctp_register_pdu_handler(session,
1260                                                 AVC_OP_PASSTHROUGH,
1261                                                 handle_panel_passthrough,
1262                                                 NULL);
1263         session->unit_id = avctp_register_pdu_handler(session,
1264                                                 AVC_OP_UNITINFO,
1265                                                 handle_unit_info,
1266                                                 NULL);
1267         session->subunit_id = avctp_register_pdu_handler(session,
1268                                                 AVC_OP_SUBUNITINFO,
1269                                                 handle_subunit_info,
1270                                                 NULL);
1271
1272         init_uinput(session);
1273
1274         avctp_set_state(session, AVCTP_STATE_CONNECTED, 0);
1275 }
1276
1277 static void auth_cb(DBusError *derr, void *user_data)
1278 {
1279         struct avctp *session = user_data;
1280         GError *err = NULL;
1281
1282         session->auth_id = 0;
1283
1284         if (session->control->watch > 0) {
1285                 g_source_remove(session->control->watch);
1286                 session->control->watch = 0;
1287         }
1288
1289         if (derr && dbus_error_is_set(derr)) {
1290                 error("Access denied: %s", derr->message);
1291                 avctp_set_state(session, AVCTP_STATE_DISCONNECTED, -EIO);
1292                 return;
1293         }
1294
1295         if (!bt_io_accept(session->control->io, avctp_connect_cb, session,
1296                                                                 NULL, &err)) {
1297                 error("bt_io_accept: %s", err->message);
1298                 g_error_free(err);
1299                 avctp_set_state(session, AVCTP_STATE_DISCONNECTED, -EIO);
1300         }
1301 }
1302
1303 static struct avctp_server *find_server(GSList *list, struct btd_adapter *a)
1304 {
1305         for (; list; list = list->next) {
1306                 struct avctp_server *server = list->data;
1307
1308                 if (server->adapter == a)
1309                         return server;
1310         }
1311
1312         return NULL;
1313 }
1314
1315 static struct avctp *find_session(GSList *list, struct btd_device *device)
1316 {
1317         for (; list != NULL; list = g_slist_next(list)) {
1318                 struct avctp *s = list->data;
1319
1320                 if (s->device == device)
1321                         return s;
1322         }
1323
1324         return NULL;
1325 }
1326
1327 static struct avctp *avctp_get_internal(struct btd_device *device)
1328 {
1329         struct avctp_server *server;
1330         struct avctp *session;
1331
1332         server = find_server(servers, device_get_adapter(device));
1333         if (server == NULL)
1334                 return NULL;
1335
1336         session = find_session(server->sessions, device);
1337         if (session)
1338                 return session;
1339
1340         session = g_new0(struct avctp, 1);
1341
1342         session->server = server;
1343         session->device = btd_device_ref(device);
1344         session->state = AVCTP_STATE_DISCONNECTED;
1345         session->uinput = -1;
1346
1347         server->sessions = g_slist_append(server->sessions, session);
1348
1349         return session;
1350 }
1351
1352 static void avctp_control_confirm(struct avctp *session, GIOChannel *chan,
1353                                                 struct btd_device *dev)
1354 {
1355         const bdaddr_t *src;
1356         const bdaddr_t *dst;
1357
1358         if (session->control != NULL) {
1359                 error("Control: Refusing unexpected connect");
1360                 g_io_channel_shutdown(chan, TRUE, NULL);
1361
1362                 /*
1363                  * Close AVCTP channel if remote tried connect
1364                  * at the same time
1365                  * AVRCP SPEC V1.5 4.1.1 Connection Establishment
1366                  */
1367                 avctp_set_state(session, AVCTP_STATE_DISCONNECTED, -EAGAIN);
1368                 return;
1369         }
1370
1371         avctp_set_state(session, AVCTP_STATE_CONNECTING, 0);
1372         session->control = avctp_channel_create(session, chan, NULL);
1373
1374         src = btd_adapter_get_address(device_get_adapter(dev));
1375         dst = device_get_address(dev);
1376
1377 #ifdef __TIZEN_PATCH__
1378         session->auth_id = btd_request_authorization(src, dst,
1379                                                         AVRCP_TARGET_UUID,
1380                                                         auth_cb, session);
1381 #else
1382         session->auth_id = btd_request_authorization(src, dst,
1383                                                         AVRCP_REMOTE_UUID,
1384                                                         auth_cb, session);
1385 #endif
1386         if (session->auth_id == 0)
1387                 goto drop;
1388
1389         session->control->watch = g_io_add_watch(chan, G_IO_ERR | G_IO_HUP |
1390                                                 G_IO_NVAL, session_cb, session);
1391         return;
1392
1393 drop:
1394         avctp_set_state(session, AVCTP_STATE_DISCONNECTED, -EIO);
1395 }
1396
1397 static void avctp_browsing_confirm(struct avctp *session, GIOChannel *chan,
1398                                                 struct btd_device *dev)
1399 {
1400         GError *err = NULL;
1401
1402         if (session->control == NULL || session->browsing != NULL) {
1403                 error("Browsing: Refusing unexpected connect");
1404                 g_io_channel_shutdown(chan, TRUE, NULL);
1405                 return;
1406         }
1407
1408         if (bt_io_accept(chan, avctp_connect_browsing_cb, session, NULL,
1409                                                                 &err)) {
1410                 avctp_set_state(session, AVCTP_STATE_BROWSING_CONNECTING, 0);
1411                 return;
1412         }
1413
1414         error("Browsing: %s", err->message);
1415         g_error_free(err);
1416
1417         return;
1418 }
1419
1420 static void avctp_confirm_cb(GIOChannel *chan, gpointer data)
1421 {
1422         struct avctp *session;
1423         char address[18];
1424         bdaddr_t src, dst;
1425         GError *err = NULL;
1426         uint16_t psm;
1427         struct btd_device *device;
1428
1429         bt_io_get(chan, &err,
1430                         BT_IO_OPT_SOURCE_BDADDR, &src,
1431                         BT_IO_OPT_DEST_BDADDR, &dst,
1432                         BT_IO_OPT_DEST, address,
1433                         BT_IO_OPT_PSM, &psm,
1434                         BT_IO_OPT_INVALID);
1435         if (err) {
1436                 error("%s", err->message);
1437                 g_error_free(err);
1438                 g_io_channel_shutdown(chan, TRUE, NULL);
1439                 return;
1440         }
1441
1442         DBG("AVCTP: incoming connect from %s", address);
1443
1444         device = btd_adapter_find_device(adapter_find(&src), &dst,
1445                                                                 BDADDR_BREDR);
1446         if (!device)
1447                 return;
1448
1449         session = avctp_get_internal(device);
1450         if (session == NULL)
1451                 return;
1452
1453         if (btd_device_get_service(device, AVRCP_REMOTE_UUID) == NULL)
1454                 btd_device_add_uuid(device, AVRCP_REMOTE_UUID);
1455
1456         if (btd_device_get_service(device, AVRCP_TARGET_UUID) == NULL)
1457                 btd_device_add_uuid(device, AVRCP_TARGET_UUID);
1458
1459         switch (psm) {
1460         case AVCTP_CONTROL_PSM:
1461                 avctp_control_confirm(session, chan, device);
1462                 break;
1463         case AVCTP_BROWSING_PSM:
1464                 avctp_browsing_confirm(session, chan, device);
1465                 break;
1466         }
1467
1468         return;
1469 }
1470
1471 static GIOChannel *avctp_server_socket(const bdaddr_t *src, gboolean master,
1472                                                 uint8_t mode, uint16_t psm)
1473 {
1474         GError *err = NULL;
1475         GIOChannel *io;
1476
1477         io = bt_io_listen(NULL, avctp_confirm_cb, NULL,
1478                                 NULL, &err,
1479                                 BT_IO_OPT_SOURCE_BDADDR, src,
1480                                 BT_IO_OPT_PSM, psm,
1481                                 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
1482                                 BT_IO_OPT_MASTER, master,
1483                                 BT_IO_OPT_MODE, mode,
1484                                 BT_IO_OPT_INVALID);
1485         if (!io) {
1486                 error("%s", err->message);
1487                 g_error_free(err);
1488         }
1489
1490         return io;
1491 }
1492
1493 int avctp_register(struct btd_adapter *adapter, gboolean master)
1494 {
1495         struct avctp_server *server;
1496         const bdaddr_t *src = btd_adapter_get_address(adapter);
1497
1498         server = g_new0(struct avctp_server, 1);
1499
1500         server->control_io = avctp_server_socket(src, master, L2CAP_MODE_BASIC,
1501                                                         AVCTP_CONTROL_PSM);
1502         if (!server->control_io) {
1503                 g_free(server);
1504                 return -1;
1505         }
1506         server->browsing_io = avctp_server_socket(src, master, L2CAP_MODE_ERTM,
1507                                                         AVCTP_BROWSING_PSM);
1508         if (!server->browsing_io) {
1509                 if (server->control_io) {
1510                         g_io_channel_shutdown(server->control_io, TRUE, NULL);
1511                         g_io_channel_unref(server->control_io);
1512                         server->control_io = NULL;
1513                 }
1514                 g_free(server);
1515                 return -1;
1516         }
1517
1518         server->adapter = btd_adapter_ref(adapter);
1519
1520         servers = g_slist_append(servers, server);
1521
1522         return 0;
1523 }
1524
1525 void avctp_unregister(struct btd_adapter *adapter)
1526 {
1527         struct avctp_server *server;
1528
1529         server = find_server(servers, adapter);
1530         if (!server)
1531                 return;
1532
1533         while (server->sessions)
1534                 avctp_disconnected(server->sessions->data);
1535
1536         servers = g_slist_remove(servers, server);
1537
1538         g_io_channel_shutdown(server->browsing_io, TRUE, NULL);
1539         g_io_channel_unref(server->browsing_io);
1540         server->browsing_io = NULL;
1541
1542         g_io_channel_shutdown(server->control_io, TRUE, NULL);
1543         g_io_channel_unref(server->control_io);
1544         btd_adapter_unref(server->adapter);
1545         g_free(server);
1546 }
1547
1548 static struct avctp_pending_req *pending_create(struct avctp_channel *chan,
1549                                                 avctp_process_cb process,
1550                                                 void *data,
1551                                                 GDestroyNotify destroy)
1552 {
1553         struct avctp_pending_req *p;
1554         GSList *l, *tmp;
1555
1556         if (!chan->processed)
1557                 goto done;
1558
1559         tmp = g_slist_copy(chan->processed);
1560
1561         /* Find first unused transaction id */
1562         for (l = tmp; l; l = g_slist_next(l)) {
1563                 struct avctp_pending_req *req = l->data;
1564
1565                 if (req->transaction == chan->transaction) {
1566                         chan->transaction++;
1567                         chan->transaction %= 16;
1568                         tmp = g_slist_delete_link(tmp, l);
1569                         l = tmp;
1570                 }
1571         }
1572
1573         g_slist_free(tmp);
1574
1575 done:
1576         p = g_new0(struct avctp_pending_req, 1);
1577         p->chan = chan;
1578         p->transaction = chan->transaction;
1579         p->process = process;
1580         p->data = data;
1581         p->destroy = destroy;
1582
1583         chan->transaction++;
1584         chan->transaction %= 16;
1585
1586         return p;
1587 }
1588
1589 static int avctp_send_req(struct avctp *session, uint8_t code,
1590                                 uint8_t subunit, uint8_t opcode,
1591                                 uint8_t *operands, size_t operand_count,
1592                                 avctp_rsp_cb func, void *user_data)
1593 {
1594         struct avctp_channel *control = session->control;
1595         struct avctp_pending_req *p;
1596         struct avctp_control_req *req;
1597
1598         if (control == NULL)
1599                 return -ENOTCONN;
1600
1601         req = g_new0(struct avctp_control_req, 1);
1602         req->code = code;
1603         req->subunit = subunit;
1604         req->op = opcode;
1605         req->func = func;
1606         req->operands = g_memdup(operands, operand_count);
1607         req->operand_count = operand_count;
1608         req->user_data = user_data;
1609
1610         p = pending_create(control, process_control, req, control_req_destroy);
1611
1612         req->p = p;
1613
1614         g_queue_push_tail(control->queue, p);
1615
1616         if (control->process_id == 0)
1617                 control->process_id = g_idle_add(process_queue, control);
1618
1619         return 0;
1620 }
1621
1622 int avctp_send_browsing_req(struct avctp *session,
1623                                 uint8_t *operands, size_t operand_count,
1624                                 avctp_browsing_rsp_cb func, void *user_data)
1625 {
1626         struct avctp_channel *browsing = session->browsing;
1627         struct avctp_pending_req *p;
1628         struct avctp_browsing_req *req;
1629
1630         if (browsing == NULL)
1631                 return -ENOTCONN;
1632
1633         req = g_new0(struct avctp_browsing_req, 1);
1634         req->func = func;
1635         req->operands = g_memdup(operands, operand_count);
1636         req->operand_count = operand_count;
1637         req->user_data = user_data;
1638
1639         p = pending_create(browsing, process_browsing, req,
1640                         browsing_req_destroy);
1641
1642         req->p = p;
1643
1644         g_queue_push_tail(browsing->queue, p);
1645
1646         /* Connection did not complete, delay process of the request */
1647         if (browsing->watch == 0)
1648                 return 0;
1649
1650         if (browsing->process_id == 0)
1651                 browsing->process_id = g_idle_add(process_queue, browsing);
1652
1653         return 0;
1654 }
1655
1656 static const char *op2str(uint8_t op)
1657 {
1658         int i;
1659
1660         for (i = 0; key_map[i].name != NULL; i++) {
1661                 if ((op & 0x7F) == key_map[i].avc)
1662                         return key_map[i].name;
1663         }
1664
1665         return "UNKNOWN";
1666 }
1667
1668 static int avctp_passthrough_press(struct avctp *session, uint8_t op)
1669 {
1670         uint8_t operands[2];
1671
1672         DBG("%s", op2str(op));
1673
1674         /* Button pressed */
1675         operands[0] = op & 0x7f;
1676         operands[1] = 0;
1677
1678         return avctp_send_req(session, AVC_CTYPE_CONTROL,
1679                                 AVC_SUBUNIT_PANEL, AVC_OP_PASSTHROUGH,
1680                                 operands, sizeof(operands),
1681                                 avctp_passthrough_rsp, NULL);
1682 }
1683
1684 static int avctp_passthrough_release(struct avctp *session, uint8_t op)
1685 {
1686         uint8_t operands[2];
1687
1688         DBG("%s", op2str(op));
1689
1690         /* Button released */
1691         operands[0] = op | 0x80;
1692         operands[1] = 0;
1693
1694         return avctp_send_req(session, AVC_CTYPE_CONTROL,
1695                                 AVC_SUBUNIT_PANEL, AVC_OP_PASSTHROUGH,
1696                                 operands, sizeof(operands),
1697                                 NULL, NULL);
1698 }
1699
1700 static gboolean repeat_timeout(gpointer user_data)
1701 {
1702         struct avctp *session = user_data;
1703
1704         avctp_passthrough_release(session, session->key.op);
1705         avctp_passthrough_press(session, session->key.op);
1706
1707         return TRUE;
1708 }
1709
1710 static void release_pressed(struct avctp *session)
1711 {
1712         avctp_passthrough_release(session, session->key.op);
1713
1714         if (session->key.timer > 0)
1715                 g_source_remove(session->key.timer);
1716
1717         session->key.timer = 0;
1718 }
1719
1720 static bool set_pressed(struct avctp *session, uint8_t op)
1721 {
1722         if (session->key.timer > 0) {
1723                 if (session->key.op == op)
1724                         return TRUE;
1725                 release_pressed(session);
1726         }
1727
1728         if (op != AVC_FAST_FORWARD && op != AVC_REWIND)
1729                 return FALSE;
1730
1731         session->key.op = op;
1732         session->key.timer = g_timeout_add_seconds(AVC_PRESS_TIMEOUT,
1733                                                         repeat_timeout,
1734                                                         session);
1735
1736         return TRUE;
1737 }
1738
1739 static gboolean avctp_passthrough_rsp(struct avctp *session, uint8_t code,
1740                                         uint8_t subunit, uint8_t *operands,
1741                                         size_t operand_count, void *user_data)
1742 {
1743         if (code != AVC_CTYPE_ACCEPTED)
1744                 return FALSE;
1745
1746         if (set_pressed(session, operands[0]))
1747                 return FALSE;
1748
1749         avctp_passthrough_release(session, operands[0]);
1750
1751         return FALSE;
1752 }
1753
1754 int avctp_send_passthrough(struct avctp *session, uint8_t op)
1755 {
1756         /* Auto release if key pressed */
1757         if (session->key.timer > 0)
1758                 release_pressed(session);
1759
1760         return avctp_passthrough_press(session, op);
1761 }
1762
1763 int avctp_send_vendordep(struct avctp *session, uint8_t transaction,
1764                                 uint8_t code, uint8_t subunit,
1765                                 uint8_t *operands, size_t operand_count)
1766 {
1767         struct avctp_channel *control = session->control;
1768
1769         if (control == NULL)
1770                 return -ENOTCONN;
1771
1772         return avctp_send(control, transaction, AVCTP_RESPONSE, code, subunit,
1773                                         AVC_OP_VENDORDEP, operands, operand_count);
1774 }
1775
1776 int avctp_send_vendordep_req(struct avctp *session, uint8_t code,
1777                                         uint8_t subunit, uint8_t *operands,
1778                                         size_t operand_count,
1779                                         avctp_rsp_cb func, void *user_data)
1780 {
1781         return avctp_send_req(session, code, subunit, AVC_OP_VENDORDEP,
1782                                                 operands, operand_count,
1783                                                 func, user_data);
1784 }
1785
1786 unsigned int avctp_add_state_cb(struct btd_device *dev, avctp_state_cb cb,
1787                                                         void *user_data)
1788 {
1789         struct avctp_state_callback *state_cb;
1790         static unsigned int id = 0;
1791
1792         state_cb = g_new(struct avctp_state_callback, 1);
1793         state_cb->cb = cb;
1794         state_cb->dev = dev;
1795         state_cb->id = ++id;
1796         state_cb->user_data = user_data;
1797
1798         callbacks = g_slist_append(callbacks, state_cb);
1799
1800         return state_cb->id;
1801 }
1802
1803 gboolean avctp_remove_state_cb(unsigned int id)
1804 {
1805         GSList *l;
1806
1807         for (l = callbacks; l != NULL; l = l->next) {
1808                 struct avctp_state_callback *cb = l->data;
1809                 if (cb && cb->id == id) {
1810                         callbacks = g_slist_remove(callbacks, cb);
1811                         g_free(cb);
1812                         return TRUE;
1813                 }
1814         }
1815
1816         return FALSE;
1817 }
1818
1819 unsigned int avctp_register_passthrough_handler(struct avctp *session,
1820                                                 avctp_passthrough_cb cb,
1821                                                 void *user_data)
1822 {
1823         struct avctp_channel *control = session->control;
1824         struct avctp_passthrough_handler *handler;
1825         static unsigned int id = 0;
1826
1827         if (control == NULL || session->handler != NULL)
1828                 return 0;
1829
1830         handler = g_new(struct avctp_passthrough_handler, 1);
1831         handler->cb = cb;
1832         handler->user_data = user_data;
1833         handler->id = ++id;
1834
1835         session->handler = handler;
1836
1837         return handler->id;
1838 }
1839
1840 bool avctp_unregister_passthrough_handler(unsigned int id)
1841 {
1842         GSList *l;
1843
1844         for (l = servers; l; l = l->next) {
1845                 struct avctp_server *server = l->data;
1846                 GSList *s;
1847
1848                 for (s = server->sessions; s; s = s->next) {
1849                         struct avctp *session = s->data;
1850
1851                         if (session->handler == NULL)
1852                                 continue;
1853
1854                         if (session->handler->id == id) {
1855                                 g_free(session->handler);
1856                                 session->handler = NULL;
1857                                 return true;
1858                         }
1859                 }
1860         }
1861
1862         return false;
1863 }
1864
1865 unsigned int avctp_register_pdu_handler(struct avctp *session, uint8_t opcode,
1866                                                 avctp_control_pdu_cb cb,
1867                                                 void *user_data)
1868 {
1869         struct avctp_channel *control = session->control;
1870         struct avctp_pdu_handler *handler;
1871         static unsigned int id = 0;
1872
1873         if (control == NULL)
1874                 return 0;
1875
1876         handler = find_handler(control->handlers, opcode);
1877         if (handler)
1878                 return 0;
1879
1880         handler = g_new(struct avctp_pdu_handler, 1);
1881         handler->opcode = opcode;
1882         handler->cb = cb;
1883         handler->user_data = user_data;
1884         handler->id = ++id;
1885
1886         control->handlers = g_slist_append(control->handlers, handler);
1887
1888         return handler->id;
1889 }
1890
1891 unsigned int avctp_register_browsing_pdu_handler(struct avctp *session,
1892                                                 avctp_browsing_pdu_cb cb,
1893                                                 void *user_data,
1894                                                 GDestroyNotify destroy)
1895 {
1896         struct avctp_channel *browsing = session->browsing;
1897         struct avctp_browsing_pdu_handler *handler;
1898         static unsigned int id = 0;
1899
1900         if (browsing == NULL)
1901                 return 0;
1902
1903         if (browsing->handlers != NULL)
1904                 return 0;
1905
1906         handler = g_new(struct avctp_browsing_pdu_handler, 1);
1907         handler->cb = cb;
1908         handler->user_data = user_data;
1909         handler->id = ++id;
1910         handler->destroy = destroy;
1911
1912         browsing->handlers = g_slist_append(browsing->handlers, handler);
1913
1914         return handler->id;
1915 }
1916
1917 gboolean avctp_unregister_pdu_handler(unsigned int id)
1918 {
1919         GSList *l;
1920
1921         for (l = servers; l; l = l->next) {
1922                 struct avctp_server *server = l->data;
1923                 GSList *s;
1924
1925                 for (s = server->sessions; s; s = s->next) {
1926                         struct avctp *session = s->data;
1927                         struct avctp_channel *control = session->control;
1928                         GSList *h;
1929
1930                         if (control == NULL)
1931                                 continue;
1932
1933                         for (h = control->handlers; h; h = h->next) {
1934                                 struct avctp_pdu_handler *handler = h->data;
1935
1936                                 if (handler->id != id)
1937                                         continue;
1938
1939                                 control->handlers = g_slist_remove(
1940                                                         control->handlers,
1941                                                         handler);
1942                                 g_free(handler);
1943                                 return TRUE;
1944                         }
1945                 }
1946         }
1947
1948         return FALSE;
1949 }
1950
1951 gboolean avctp_unregister_browsing_pdu_handler(unsigned int id)
1952 {
1953         GSList *l;
1954
1955         for (l = servers; l; l = l->next) {
1956                 struct avctp_server *server = l->data;
1957                 GSList *s;
1958
1959                 for (s = server->sessions; s; s = s->next) {
1960                         struct avctp *session = s->data;
1961                         struct avctp_channel *browsing = session->browsing;
1962                         GSList *h;
1963
1964                         if (browsing == NULL)
1965                                 continue;
1966
1967                         for (h = browsing->handlers; h; h = h->next) {
1968                                 struct avctp_browsing_pdu_handler *handler =
1969                                                                 h->data;
1970
1971                                 if (handler->id != id)
1972                                         continue;
1973
1974                                 browsing->handlers = g_slist_remove(
1975                                                         browsing->handlers,
1976                                                         handler);
1977                                 g_free(handler);
1978                                 return TRUE;
1979                         }
1980                 }
1981         }
1982
1983         return FALSE;
1984 }
1985
1986 struct avctp *avctp_connect(struct btd_device *device)
1987 {
1988         struct avctp *session;
1989         GError *err = NULL;
1990         GIOChannel *io;
1991         const bdaddr_t *src;
1992
1993         session = avctp_get_internal(device);
1994         if (!session)
1995                 return NULL;
1996
1997         if (session->state > AVCTP_STATE_DISCONNECTED)
1998                 return session;
1999
2000         avctp_set_state(session, AVCTP_STATE_CONNECTING, 0);
2001
2002         src = btd_adapter_get_address(session->server->adapter);
2003
2004         io = bt_io_connect(avctp_connect_cb, session, NULL, &err,
2005                                 BT_IO_OPT_SOURCE_BDADDR, src,
2006                                 BT_IO_OPT_DEST_BDADDR,
2007                                 device_get_address(session->device),
2008                                 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
2009                                 BT_IO_OPT_PSM, AVCTP_CONTROL_PSM,
2010                                 BT_IO_OPT_INVALID);
2011         if (err) {
2012                 avctp_set_state(session, AVCTP_STATE_DISCONNECTED, -EIO);
2013                 error("%s", err->message);
2014                 g_error_free(err);
2015                 return NULL;
2016         }
2017
2018         session->control = avctp_channel_create(session, io, NULL);
2019         session->initiator = true;
2020         g_io_channel_unref(io);
2021
2022         return session;
2023 }
2024
2025 int avctp_connect_browsing(struct avctp *session)
2026 {
2027         const bdaddr_t *src;
2028         GError *err = NULL;
2029         GIOChannel *io;
2030
2031         if (session->state != AVCTP_STATE_CONNECTED)
2032                 return -ENOTCONN;
2033
2034         if (session->browsing != NULL)
2035                 return 0;
2036
2037         avctp_set_state(session, AVCTP_STATE_BROWSING_CONNECTING, 0);
2038
2039         src = btd_adapter_get_address(session->server->adapter);
2040
2041         io = bt_io_connect(avctp_connect_browsing_cb, session, NULL, &err,
2042                                 BT_IO_OPT_SOURCE_BDADDR, src,
2043                                 BT_IO_OPT_DEST_BDADDR,
2044                                 device_get_address(session->device),
2045                                 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
2046                                 BT_IO_OPT_PSM, AVCTP_BROWSING_PSM,
2047                                 BT_IO_OPT_MODE, L2CAP_MODE_ERTM,
2048                                 BT_IO_OPT_INVALID);
2049         if (err) {
2050                 error("%s", err->message);
2051                 g_error_free(err);
2052                 return -EIO;
2053         }
2054
2055         session->browsing = avctp_channel_create(session, io,
2056                                                 avctp_destroy_browsing);
2057         g_io_channel_unref(io);
2058
2059         return 0;
2060 }
2061
2062 void avctp_disconnect(struct avctp *session)
2063 {
2064         if (session->state == AVCTP_STATE_DISCONNECTED)
2065                 return;
2066
2067         avctp_set_state(session, AVCTP_STATE_DISCONNECTED, -EIO);
2068 }
2069
2070 struct avctp *avctp_get(struct btd_device *device)
2071 {
2072         return avctp_get_internal(device);
2073 }
2074
2075 bool avctp_is_initiator(struct avctp *session)
2076 {
2077         return session->initiator;
2078 }