8 #include <sys/socket.h>
11 #include <cutils/sockets.h>
15 * the qemud daemon program is only used within Android as a bridge
16 * between the emulator program and the emulated system. it really works as
17 * a simple stream multiplexer that works as follows:
19 * - qemud is started by init following instructions in
20 * /system/etc/init.goldfish.rc (i.e. it is never started on real devices)
22 * - qemud communicates with the emulator program through a single serial
23 * port, whose name is passed through a kernel boot parameter
24 * (e.g. android.qemud=ttyS1)
26 * - qemud binds one unix local stream socket (/dev/socket/qemud, created
27 * by init through /system/etc/init.goldfish.rc).
30 * emulator <==serial==> qemud <---> /dev/socket/qemud <-+--> client1
34 * - the special channel index 0 is used by the emulator and qemud only.
35 * other channel numbers correspond to clients. More specifically,
36 * connection are created like this:
38 * * the client connects to /dev/socket/qemud
40 * * the client sends the service name through the socket, as
43 * * qemud creates a "Client" object internally, assigns it an
44 * internal unique channel number > 0, then sends a connection
45 * initiation request to the emulator (i.e. through channel 0):
49 * where <name> is the service name, and <id> is a 2-hexchar
50 * number corresponding to the channel number.
52 * * in case of success, the emulator responds through channel 0
57 * after this, all messages between the client and the emulator
58 * are passed in pass-through mode.
60 * * if the emulator refuses the service connection, it will
61 * send the following through channel 0:
63 * ko:connect:<id>:reason-for-failure
65 * * If the client closes the connection, qemud sends the following
70 * The same message is the opposite direction if the emulator
71 * chooses to close the connection.
73 * * any command sent through channel 0 to the emulator that is
74 * not properly recognized will be answered by:
79 * Internally, the daemon maintains a "Client" object for each client
80 * connection (i.e. accepting socket connection).
83 /* name of the single control socket used by the daemon */
84 #define CONTROL_SOCKET_NAME "qemud"
87 #define T_ACTIVE 0 /* set to 1 to dump traffic */
90 # define LOG_TAG "qemud"
91 # include <cutils/log.h>
92 # define D(...) ALOGD(__VA_ARGS__)
94 # define D(...) ((void)0)
95 # define T(...) ((void)0)
99 # define T(...) D(__VA_ARGS__)
101 # define T(...) ((void)0)
108 fatal( const char* fmt, ... )
112 fprintf(stderr, "PANIC: ");
113 vfprintf(stderr, fmt, args);
114 fprintf(stderr, "\n" );
129 fatal( "not enough memory" );
134 #define xnew(p) (p) = xalloc(sizeof(*(p)))
139 void* p = xalloc(sz);
144 #define xnew0(p) (p) = xalloc0(sizeof(*(p)))
146 #define xfree(p) (free((p)), (p) = NULL)
149 xrealloc( void* block, size_t size )
151 void* p = realloc( block, size );
153 if (p == NULL && size > 0)
154 fatal( "not enough memory" );
159 #define xrenew(p,count) (p) = xrealloc((p),sizeof(*(p))*(count))
162 hex2int( const uint8_t* data, int len )
171 d = (unsigned)(c - '0');
175 d = (unsigned)(c - 'a');
181 d = (unsigned)(c - 'A');
199 int2hex( int value, uint8_t* to, int width )
202 static const char hexchars[16] = "0123456789abcdef";
204 for ( --width; width >= 0; width--, nn++ ) {
205 to[nn] = hexchars[(value >> (width*4)) & 15];
210 fd_read(int fd, void* to, int len)
215 ret = read(fd, to, len);
216 } while (ret < 0 && errno == EINTR);
222 fd_write(int fd, const void* from, int len)
227 ret = write(fd, from, len);
228 } while (ret < 0 && errno == EINTR);
234 fd_setnonblock(int fd)
239 flags = fcntl(fd, F_GETFD);
240 } while (flags < 0 && errno == EINTR);
243 fatal( "%s: could not get flags for fd %d: %s",
244 __FUNCTION__, fd, strerror(errno) );
248 ret = fcntl(fd, F_SETFD, flags | O_NONBLOCK);
249 } while (ret < 0 && errno == EINTR);
252 fatal( "%s: could not set fd %d to non-blocking: %s",
253 __FUNCTION__, fd, strerror(errno) );
261 struct sockaddr from;
262 socklen_t fromlen = sizeof(from);
266 ret = accept(fd, &from, &fromlen);
267 } while (ret < 0 && errno == EINTR);
275 /* A Looper object is used to monitor activity on one or more
276 * file descriptors (e.g sockets).
278 * - call looper_add() to register a function that will be
279 * called when events happen on the file descriptor.
281 * - call looper_enable() or looper_disable() to enable/disable
282 * the set of monitored events for a given file descriptor.
284 * - call looper_del() to unregister a file descriptor.
285 * this does *not* close the file descriptor.
287 * Note that you can only provide a single function to handle
288 * all events related to a given file descriptor.
290 * You can call looper_enable/_disable/_del within a function
294 /* the current implementation uses Linux's epoll facility
295 * the event mask we use are simply combinations of EPOLLIN
296 * EPOLLOUT, EPOLLHUP and EPOLLERR
298 #include <sys/epoll.h>
300 #define MAX_CHANNELS 16
301 #define MAX_EVENTS (MAX_CHANNELS+1) /* each channel + the serial fd */
303 /* the event handler function type, 'user' is a user-specific
304 * opaque pointer passed to looper_add().
306 typedef void (*EventFunc)( void* user, int events );
308 /* bit flags for the LoopHook structure.
310 * HOOK_PENDING means that an event happened on the
311 * corresponding file descriptor.
313 * HOOK_CLOSING is used to delay-close monitored
317 HOOK_PENDING = (1 << 0),
318 HOOK_CLOSING = (1 << 1),
321 /* A LoopHook structure is used to monitor a given
322 * file descriptor and record its event handler.
326 int wanted; /* events we are monitoring */
327 int events; /* events that occured */
328 int state; /* see HOOK_XXX constants */
329 void* ev_user; /* user-provided handler parameter */
330 EventFunc ev_func; /* event handler callback */
333 /* Looper is the main object modeling a looper object
339 struct epoll_event* events;
343 /* initialize a looper object */
345 looper_init( Looper* l )
347 l->epoll_fd = epoll_create(4);
354 /* finalize a looper object */
356 looper_done( Looper* l )
367 /* return the LoopHook corresponding to a given
368 * monitored file descriptor, or NULL if not found
371 looper_find( Looper* l, int fd )
373 LoopHook* hook = l->hooks;
374 LoopHook* end = hook + l->num_fds;
376 for ( ; hook < end; hook++ ) {
383 /* grow the arrays in the looper object */
385 looper_grow( Looper* l )
387 int old_max = l->max_fds;
388 int new_max = old_max + (old_max >> 1) + 4;
391 xrenew( l->events, new_max );
392 xrenew( l->hooks, new_max );
393 l->max_fds = new_max;
395 /* now change the handles to all events */
396 for (n = 0; n < l->num_fds; n++) {
397 struct epoll_event ev;
398 LoopHook* hook = l->hooks + n;
400 ev.events = hook->wanted;
402 epoll_ctl( l->epoll_fd, EPOLL_CTL_MOD, hook->fd, &ev );
406 /* register a file descriptor and its event handler.
407 * no event mask will be enabled
410 looper_add( Looper* l, int fd, EventFunc func, void* user )
412 struct epoll_event ev;
415 if (l->num_fds >= l->max_fds)
418 hook = l->hooks + l->num_fds;
421 hook->ev_user = user;
422 hook->ev_func = func;
431 epoll_ctl( l->epoll_fd, EPOLL_CTL_ADD, fd, &ev );
436 /* unregister a file descriptor and its event handler
439 looper_del( Looper* l, int fd )
441 LoopHook* hook = looper_find( l, fd );
444 D( "%s: invalid fd: %d", __FUNCTION__, fd );
447 /* don't remove the hook yet */
448 hook->state |= HOOK_CLOSING;
450 epoll_ctl( l->epoll_fd, EPOLL_CTL_DEL, fd, NULL );
453 /* enable monitoring of certain events for a file
454 * descriptor. This adds 'events' to the current
458 looper_enable( Looper* l, int fd, int events )
460 LoopHook* hook = looper_find( l, fd );
463 D("%s: invalid fd: %d", __FUNCTION__, fd );
467 if (events & ~hook->wanted) {
468 struct epoll_event ev;
470 hook->wanted |= events;
471 ev.events = hook->wanted;
474 epoll_ctl( l->epoll_fd, EPOLL_CTL_MOD, fd, &ev );
478 /* disable monitoring of certain events for a file
479 * descriptor. This ignores events that are not
483 looper_disable( Looper* l, int fd, int events )
485 LoopHook* hook = looper_find( l, fd );
488 D("%s: invalid fd: %d", __FUNCTION__, fd );
492 if (events & hook->wanted) {
493 struct epoll_event ev;
495 hook->wanted &= ~events;
496 ev.events = hook->wanted;
499 epoll_ctl( l->epoll_fd, EPOLL_CTL_MOD, fd, &ev );
503 /* wait until an event occurs on one of the registered file
504 * descriptors. Only returns in case of error !!
507 looper_loop( Looper* l )
513 count = epoll_wait( l->epoll_fd, l->events, l->num_fds, -1 );
514 } while (count < 0 && errno == EINTR);
517 D("%s: error: %s", __FUNCTION__, strerror(errno) );
522 D("%s: huh ? epoll returned count=0", __FUNCTION__);
526 /* mark all pending hooks */
527 for (n = 0; n < count; n++) {
528 LoopHook* hook = l->events[n].data.ptr;
529 hook->state = HOOK_PENDING;
530 hook->events = l->events[n].events;
533 /* execute hook callbacks. this may change the 'hooks'
534 * and 'events' array, as well as l->num_fds, so be careful */
535 for (n = 0; n < l->num_fds; n++) {
536 LoopHook* hook = l->hooks + n;
537 if (hook->state & HOOK_PENDING) {
538 hook->state &= ~HOOK_PENDING;
539 hook->ev_func( hook->ev_user, hook->events );
543 /* now remove all the hooks that were closed by
545 for (n = 0; n < l->num_fds;) {
546 struct epoll_event ev;
547 LoopHook* hook = l->hooks + n;
549 if (!(hook->state & HOOK_CLOSING)) {
554 hook[0] = l->hooks[l->num_fds-1];
556 ev.events = hook->wanted;
558 epoll_ctl( l->epoll_fd, EPOLL_CTL_MOD, hook->fd, &ev );
565 quote( const void* data, int len )
567 const char* p = data;
568 const char* end = p + len;
571 static char* buff = NULL;
573 for (phase = 0; phase < 2; phase++) {
576 buff = xalloc(count+1);
579 for (p = data; p < end; p++) {
584 buff[count] = buff[count+1] = '\\';
590 if (c >= 32 && c < 127) {
600 memcpy(buff+count, "<TAB>", 5);
607 memcpy(buff+count, "<LN>", 4);
614 memcpy(buff+count, "<CR>", 4);
621 buff[count+0] = '\\';
623 buff[count+2] = "0123456789abcdef"[(c >> 4) & 15];
624 buff[count+3] = "0123456789abcdef"[ (c) & 15];
632 #endif /* T_ACTIVE */
636 ** We need a way to buffer data before it can be sent to the
637 ** corresponding file descriptor. We use linked list of Packet
638 ** objects to do this.
641 typedef struct Packet Packet;
643 #define MAX_PAYLOAD 4000
649 uint8_t data[ MAX_PAYLOAD ];
652 /* we expect to alloc/free a lot of packets during
653 * operations so use a single linked list of free packets
654 * to keep things speedy and simple.
656 static Packet* _free_packets;
658 /* Allocate a packet */
662 Packet* p = _free_packets;
664 _free_packets = p->next;
674 /* Release a packet. This takes the address of a packet
675 * pointer that will be set to NULL on exit (avoids
676 * referencing dangling pointers in case of bugs)
679 packet_free( Packet* *ppacket )
681 Packet* p = *ppacket;
683 p->next = _free_packets;
691 ** Simple abstraction for something that can receive a packet
692 ** from a FDHandler (see below) or something else.
694 ** Send a packet to it with 'receiver_post'
696 ** Call 'receiver_close' to indicate that the corresponding
697 ** packet source was closed.
700 typedef void (*PostFunc) ( void* user, Packet* p );
701 typedef void (*CloseFunc)( void* user );
709 /* post a packet to a receiver. Note that this transfers
710 * ownership of the packet to the receiver.
712 static __inline__ void
713 receiver_post( Receiver* r, Packet* p )
716 r->post( r->user, p );
721 /* tell a receiver the packet source was closed.
722 * this will also prevent further posting to the
725 static __inline__ void
726 receiver_close( Receiver* r )
738 ** these are smart listeners that send incoming packets to a receiver
739 ** and can queue one or more outgoing packets and send them when
740 ** possible to the FD.
742 ** note that we support clean shutdown of file descriptors,
743 ** i.e. we try to send all outgoing packets before destroying
747 typedef struct FDHandler FDHandler;
748 typedef struct FDHandlerList FDHandlerList;
754 Receiver receiver[1];
756 /* queue of outgoing packets */
766 struct FDHandlerList {
767 /* the looper that manages the fds */
770 /* list of active FDHandler objects */
773 /* list of closing FDHandler objects.
774 * these are waiting to push their
775 * queued packets to the fd before
776 * freeing themselves.
782 /* remove a FDHandler from its current list */
784 fdhandler_remove( FDHandler* f )
786 f->pref[0] = f->next;
788 f->next->pref = f->pref;
791 /* add a FDHandler to a given list */
793 fdhandler_prepend( FDHandler* f, FDHandler** list )
799 f->next->pref = &f->next;
802 /* initialize a FDHandler list */
804 fdhandler_list_init( FDHandlerList* list, Looper* looper )
806 list->looper = looper;
808 list->closing = NULL;
812 /* close a FDHandler (and free it). Note that this will not
813 * perform a graceful shutdown, i.e. all packets in the
814 * outgoing queue will be immediately free.
816 * this *will* notify the receiver that the file descriptor
819 * you should call fdhandler_shutdown() if you want to
820 * notify the FDHandler that its packet source is closed.
823 fdhandler_close( FDHandler* f )
825 /* notify receiver */
826 receiver_close(f->receiver);
828 /* remove the handler from its list */
831 /* get rid of outgoing packet queue */
832 if (f->out_first != NULL) {
834 while ((p = f->out_first) != NULL) {
835 f->out_first = p->next;
840 /* get rid of file descriptor */
842 looper_del( f->list->looper, f->fd );
851 /* Ask the FDHandler to cleanly shutdown the connection,
852 * i.e. send any pending outgoing packets then auto-free
856 fdhandler_shutdown( FDHandler* f )
858 /* prevent later fdhandler_close() to
859 * call the receiver's close.
861 f->receiver->close = NULL;
863 if (f->out_first != NULL && !f->closing)
865 /* move the handler to the 'closing' list */
868 fdhandler_prepend(f, &f->list->closing);
875 /* Enqueue a new packet that the FDHandler will
876 * send through its file descriptor.
879 fdhandler_enqueue( FDHandler* f, Packet* p )
881 Packet* first = f->out_first;
885 f->out_ptail = &p->next;
889 looper_enable( f->list->looper, f->fd, EPOLLOUT );
894 /* FDHandler file descriptor event callback for read/write ops */
896 fdhandler_event( FDHandler* f, int events )
900 /* in certain cases, it's possible to have both EPOLLIN and
901 * EPOLLHUP at the same time. This indicates that there is incoming
902 * data to read, but that the connection was nonetheless closed
903 * by the sender. Be sure to read the data before closing
904 * the receiver to avoid packet loss.
907 if (events & EPOLLIN) {
908 Packet* p = packet_alloc();
911 if ((len = fd_read(f->fd, p->data, MAX_PAYLOAD)) < 0) {
912 D("%s: can't recv: %s", __FUNCTION__, strerror(errno));
914 } else if (len > 0) {
916 p->channel = -101; /* special debug value, not used */
917 receiver_post( f->receiver, p );
921 if (events & (EPOLLHUP|EPOLLERR)) {
923 D("%s: disconnect on fd %d", __FUNCTION__, f->fd);
928 if (events & EPOLLOUT && f->out_first) {
929 Packet* p = f->out_first;
932 avail = p->len - f->out_pos;
933 if ((len = fd_write(f->fd, p->data + f->out_pos, avail)) < 0) {
934 D("%s: can't send: %s", __FUNCTION__, strerror(errno));
937 if (f->out_pos >= p->len) {
939 f->out_first = p->next;
941 if (f->out_first == NULL) {
942 f->out_ptail = &f->out_first;
943 looper_disable( f->list->looper, f->fd, EPOLLOUT );
951 /* Create a new FDHandler that monitors read/writes */
953 fdhandler_new( int fd,
957 FDHandler* f = xalloc0(sizeof(*f));
961 f->receiver[0] = receiver[0];
963 f->out_ptail = &f->out_first;
966 fdhandler_prepend(f, &list->active);
968 looper_add( list->looper, fd, (EventFunc) fdhandler_event, f );
969 looper_enable( list->looper, fd, EPOLLIN );
975 /* event callback function to monitor accepts() on server sockets.
976 * the convention used here is that the receiver will receive a
977 * dummy packet with the new client socket in p->channel
980 fdhandler_accept_event( FDHandler* f, int events )
982 if (events & EPOLLIN) {
983 /* this is an accept - send a dummy packet to the receiver */
984 Packet* p = packet_alloc();
986 D("%s: accepting on fd %d", __FUNCTION__, f->fd);
989 p->channel = fd_accept(f->fd);
990 if (p->channel < 0) {
991 D("%s: accept failed ?: %s", __FUNCTION__, strerror(errno));
995 receiver_post( f->receiver, p );
998 if (events & (EPOLLHUP|EPOLLERR)) {
999 /* disconnecting !! */
1000 D("%s: closing accept fd %d", __FUNCTION__, f->fd);
1007 /* Create a new FDHandler used to monitor new connections on a
1008 * server socket. The receiver must expect the new connection
1009 * fd in the 'channel' field of a dummy packet.
1012 fdhandler_new_accept( int fd,
1013 FDHandlerList* list,
1014 Receiver* receiver )
1016 FDHandler* f = xalloc0(sizeof(*f));
1020 f->receiver[0] = receiver[0];
1022 fdhandler_prepend(f, &list->active);
1024 looper_add( list->looper, fd, (EventFunc) fdhandler_accept_event, f );
1025 looper_enable( list->looper, fd, EPOLLIN );
1031 /** SERIAL CONNECTION STATE
1033 ** The following is used to handle the framing protocol
1034 ** used on the serial port connection.
1037 /* each packet is made of a 6 byte header followed by a payload
1038 * the header looks like:
1040 * offset size description
1041 * 0 2 a 2-byte hex string for the channel number
1042 * 4 4 a 4-char hex string for the size of the payload
1043 * 6 n the payload itself
1045 #define HEADER_SIZE 6
1046 #define CHANNEL_OFFSET 0
1047 #define LENGTH_OFFSET 2
1048 #define CHANNEL_SIZE 2
1049 #define LENGTH_SIZE 4
1051 #define CHANNEL_CONTROL 0
1053 /* The Serial object receives data from the serial port,
1054 * extracts the payload size and channel index, then sends
1055 * the resulting messages as a packet to a generic receiver.
1057 * You can also use serial_send to send a packet through
1060 typedef struct Serial {
1061 FDHandler* fdhandler; /* used to monitor serial port fd */
1062 Receiver receiver[1]; /* send payload there */
1063 int in_len; /* current bytes in input packet */
1064 int in_datalen; /* payload size, or 0 when reading header */
1065 int in_channel; /* extracted channel number */
1066 Packet* in_packet; /* used to read incoming packets */
1070 /* a callback called when the serial port's fd is closed */
1072 serial_fd_close( Serial* s )
1074 fatal("unexpected serial port close !!");
1078 serial_dump( Packet* p, const char* funcname )
1080 T("%s: %03d bytes: '%s'",
1081 funcname, p->len, quote(p->data, p->len));
1084 /* a callback called when a packet arrives from the serial port's FDHandler.
1086 * This will essentially parse the header, extract the channel number and
1087 * the payload size and store them in 'in_datalen' and 'in_channel'.
1089 * After that, the payload is sent to the receiver once completed.
1092 serial_fd_receive( Serial* s, Packet* p )
1094 int rpos = 0, rcount = p->len;
1095 Packet* inp = s->in_packet;
1096 int inpos = s->in_len;
1098 serial_dump( p, __FUNCTION__ );
1100 while (rpos < rcount)
1102 int avail = rcount - rpos;
1104 /* first, try to read the header */
1105 if (s->in_datalen == 0) {
1106 int wanted = HEADER_SIZE - inpos;
1110 memcpy( inp->data + inpos, p->data + rpos, avail );
1114 if (inpos == HEADER_SIZE) {
1115 s->in_datalen = hex2int( inp->data + LENGTH_OFFSET, LENGTH_SIZE );
1116 s->in_channel = hex2int( inp->data + CHANNEL_OFFSET, CHANNEL_SIZE );
1118 if (s->in_datalen <= 0) {
1119 D("ignoring %s packet from serial port",
1120 s->in_datalen ? "empty" : "malformed");
1124 //D("received %d bytes packet for channel %d", s->in_datalen, s->in_channel);
1128 else /* then, populate the packet itself */
1130 int wanted = s->in_datalen - inpos;
1135 memcpy( inp->data + inpos, p->data + rpos, avail );
1139 if (inpos == s->in_datalen) {
1140 if (s->in_channel < 0) {
1141 D("ignoring %d bytes addressed to channel %d",
1142 inpos, s->in_channel);
1145 inp->channel = s->in_channel;
1146 receiver_post( s->receiver, inp );
1147 s->in_packet = inp = packet_alloc();
1159 /* send a packet to the serial port.
1160 * this assumes that p->len and p->channel contain the payload's
1161 * size and channel and will add the appropriate header.
1164 serial_send( Serial* s, Packet* p )
1166 Packet* h = packet_alloc();
1168 //D("sending to serial %d bytes from channel %d: '%.*s'", p->len, p->channel, p->len, p->data);
1170 /* insert a small header before this packet */
1171 h->len = HEADER_SIZE;
1172 int2hex( p->len, h->data + LENGTH_OFFSET, LENGTH_SIZE );
1173 int2hex( p->channel, h->data + CHANNEL_OFFSET, CHANNEL_SIZE );
1175 serial_dump( h, __FUNCTION__ );
1176 serial_dump( p, __FUNCTION__ );
1178 fdhandler_enqueue( s->fdhandler, h );
1179 fdhandler_enqueue( s->fdhandler, p );
1183 /* initialize serial reader */
1185 serial_init( Serial* s,
1187 FDHandlerList* list,
1188 Receiver* receiver )
1193 recv.post = (PostFunc) serial_fd_receive;
1194 recv.close = (CloseFunc) serial_fd_close;
1196 s->receiver[0] = receiver[0];
1198 s->fdhandler = fdhandler_new( fd, list, &recv );
1202 s->in_packet = packet_alloc();
1209 typedef struct Client Client;
1210 typedef struct Multiplexer Multiplexer;
1212 /* A Client object models a single qemud client socket
1213 * connection in the emulated system.
1215 * the client first sends the name of the system service
1216 * it wants to contact (no framing), then waits for a 2
1217 * byte answer from qemud.
1219 * the answer is either "OK" or "KO" to indicate
1220 * success or failure.
1222 * In case of success, the client can send messages
1225 * In case of failure, it can disconnect or try sending
1226 * the name of another service.
1233 FDHandler* fdhandler;
1234 Multiplexer* multiplexer;
1237 struct Multiplexer {
1242 FDHandlerList fdhandlers[1];
1246 static int multiplexer_open_channel( Multiplexer* mult, Packet* p );
1247 static void multiplexer_close_channel( Multiplexer* mult, int channel );
1248 static void multiplexer_serial_send( Multiplexer* mult, int channel, Packet* p );
1251 client_dump( Client* c, Packet* p, const char* funcname )
1253 T("%s: client %p (%d): %3d bytes: '%s'",
1254 funcname, c, c->fdhandler->fd,
1255 p->len, quote(p->data, p->len));
1258 /* destroy a client */
1260 client_free( Client* c )
1262 /* remove from list */
1263 c->pref[0] = c->next;
1265 c->next->pref = c->pref;
1270 /* gently ask the FDHandler to shutdown to
1271 * avoid losing queued outgoing packets */
1272 if (c->fdhandler != NULL) {
1273 fdhandler_shutdown(c->fdhandler);
1274 c->fdhandler = NULL;
1281 /* a function called when a client socket receives data */
1283 client_fd_receive( Client* c, Packet* p )
1285 client_dump(c, p, __FUNCTION__);
1287 if (c->registered) {
1288 /* the client is registered, just send the
1289 * data through the serial port
1291 multiplexer_serial_send(c->multiplexer, c->channel, p);
1295 if (c->channel > 0) {
1296 /* the client is waiting registration results.
1297 * this should not happen because the client
1298 * should wait for our 'ok' or 'ko'.
1299 * close the connection.
1301 D("%s: bad client sending data before end of registration",
1309 /* the client hasn't registered a service yet,
1310 * so this must be the name of a service, call
1311 * the multiplexer to start registration for
1314 D("%s: attempting registration for service '%.*s'",
1315 __FUNCTION__, p->len, p->data);
1316 c->channel = multiplexer_open_channel(c->multiplexer, p);
1317 if (c->channel < 0) {
1318 D("%s: service name too long", __FUNCTION__);
1321 D("%s: -> received channel id %d", __FUNCTION__, c->channel);
1326 /* a function called when the client socket is closed. */
1328 client_fd_close( Client* c )
1330 T("%s: client %p (%d)", __FUNCTION__, c, c->fdhandler->fd);
1332 /* no need to shutdown the FDHandler */
1333 c->fdhandler = NULL;
1335 /* tell the emulator we're out */
1337 multiplexer_close_channel(c->multiplexer, c->channel);
1339 /* free the client */
1343 /* a function called when the multiplexer received a registration
1344 * response from the emulator for a given client.
1347 client_registration( Client* c, int registered )
1349 Packet* p = packet_alloc();
1351 /* sends registration status to client */
1353 D("%s: registration failed for client %d", __FUNCTION__, c->channel);
1354 memcpy( p->data, "KO", 2 );
1357 D("%s: registration succeeded for client %d", __FUNCTION__, c->channel);
1358 memcpy( p->data, "OK", 2 );
1361 client_dump(c, p, __FUNCTION__);
1362 fdhandler_enqueue(c->fdhandler, p);
1364 /* now save registration state
1366 c->registered = registered;
1368 /* allow the client to try registering another service */
1373 /* send data to a client */
1375 client_send( Client* c, Packet* p )
1377 client_dump(c, p, __FUNCTION__);
1378 fdhandler_enqueue(c->fdhandler, p);
1382 /* Create new client socket handler */
1384 client_new( Multiplexer* mult,
1386 FDHandlerList* pfdhandlers,
1394 c->multiplexer = mult;
1401 recv.post = (PostFunc) client_fd_receive;
1402 recv.close = (CloseFunc) client_fd_close;
1404 c->fdhandler = fdhandler_new( fd, pfdhandlers, &recv );
1406 /* add to client list */
1407 c->next = *pclients;
1411 c->next->pref = &c->next;
1416 /** GLOBAL MULTIPLEXER
1419 /* find a client by its channel */
1421 multiplexer_find_client( Multiplexer* mult, int channel )
1423 Client* c = mult->clients;
1425 for ( ; c != NULL; c = c->next ) {
1426 if (c->channel == channel)
1432 /* handle control messages coming from the serial port
1433 * on CONTROL_CHANNEL.
1436 multiplexer_handle_control( Multiplexer* mult, Packet* p )
1438 /* connection registration success */
1439 if (p->len == 13 && !memcmp(p->data, "ok:connect:", 11)) {
1440 int channel = hex2int(p->data+11, 2);
1441 Client* client = multiplexer_find_client(mult, channel);
1443 /* note that 'client' can be NULL if the corresponding
1444 * socket was closed before the emulator response arrived.
1446 if (client != NULL) {
1447 client_registration(client, 1);
1449 D("%s: NULL client: '%.*s'", __FUNCTION__, p->len, p->data+11);
1454 /* connection registration failure */
1455 if (p->len == 13 && !memcmp(p->data, "ko:connect:",11)) {
1456 int channel = hex2int(p->data+11, 2);
1457 Client* client = multiplexer_find_client(mult, channel);
1460 client_registration(client, 0);
1465 /* emulator-induced client disconnection */
1466 if (p->len == 13 && !memcmp(p->data, "disconnect:",11)) {
1467 int channel = hex2int(p->data+11, 2);
1468 Client* client = multiplexer_find_client(mult, channel);
1471 client_free(client);
1476 /* A message that begins with "X00" is a probe sent by
1477 * the emulator used to detect which version of qemud it runs
1478 * against (in order to detect 1.0/1.1 system images. Just
1479 * silently ignore it there instead of printing an error
1482 if (p->len >= 3 && !memcmp(p->data,"X00",3)) {
1486 D("%s: unknown control message (%d bytes): '%.*s'",
1487 __FUNCTION__, p->len, p->len, p->data);
1493 /* a function called when an incoming packet comes from the serial port */
1495 multiplexer_serial_receive( Multiplexer* mult, Packet* p )
1499 T("%s: channel=%d '%.*s'", __FUNCTION__, p->channel, p->len, p->data);
1501 if (p->channel == CHANNEL_CONTROL) {
1502 multiplexer_handle_control(mult, p);
1506 client = multiplexer_find_client(mult, p->channel);
1507 if (client != NULL) {
1508 client_send(client, p);
1512 D("%s: discarding packet for unknown channel %d", __FUNCTION__, p->channel);
1516 /* a function called when the serial reader closes */
1518 multiplexer_serial_close( Multiplexer* mult )
1520 fatal("unexpected close of serial reader");
1523 /* a function called to send a packet to the serial port */
1525 multiplexer_serial_send( Multiplexer* mult, int channel, Packet* p )
1527 p->channel = channel;
1528 serial_send( mult->serial, p );
1533 /* a function used by a client to allocate a new channel id and
1534 * ask the emulator to open it. 'service' must be a packet containing
1535 * the name of the service in its payload.
1537 * returns -1 if the service name is too long.
1539 * notice that client_registration() will be called later when
1540 * the answer arrives.
1543 multiplexer_open_channel( Multiplexer* mult, Packet* service )
1545 Packet* p = packet_alloc();
1548 /* find a free channel number, assume we don't have many
1553 channel = (++mult->last_channel) & 0xff;
1555 for (c = mult->clients; c != NULL; c = c->next)
1556 if (c->channel == channel)
1560 len = snprintf((char*)p->data, sizeof p->data, "connect:%.*s:%02x", service->len, service->data, channel);
1561 if (len >= (int)sizeof(p->data)) {
1562 D("%s: weird, service name too long (%d > %d)", __FUNCTION__, len, sizeof(p->data));
1566 p->channel = CHANNEL_CONTROL;
1569 serial_send(mult->serial, p);
1573 /* used to tell the emulator a channel was closed by a client */
1575 multiplexer_close_channel( Multiplexer* mult, int channel )
1577 Packet* p = packet_alloc();
1578 int len = snprintf((char*)p->data, sizeof(p->data), "disconnect:%02x", channel);
1580 if (len > (int)sizeof(p->data)) {
1581 /* should not happen */
1585 p->channel = CHANNEL_CONTROL;
1588 serial_send(mult->serial, p);
1591 /* this function is used when a new connection happens on the control
1595 multiplexer_control_accept( Multiplexer* m, Packet* p )
1597 /* the file descriptor for the new socket connection is
1598 * in p->channel. See fdhandler_accept_event() */
1599 int fd = p->channel;
1600 Client* client = client_new( m, fd, m->fdhandlers, &m->clients );
1602 D("created client %p listening on fd %d", client, fd);
1604 /* free dummy packet */
1609 multiplexer_control_close( Multiplexer* m )
1611 fatal("unexpected multiplexer control close");
1615 multiplexer_init( Multiplexer* m, const char* serial_dev )
1620 /* initialize looper and fdhandlers list */
1621 looper_init( m->looper );
1622 fdhandler_list_init( m->fdhandlers, m->looper );
1624 /* open the serial port */
1626 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
1627 } while (fd < 0 && errno == EINTR);
1629 struct sockaddr_un addr;
1631 memset(&addr, 0, sizeof(addr));
1632 addr.sun_family = AF_UNIX;
1633 strncpy(addr.sun_path, serial_dev, sizeof(addr.sun_path));
1635 if (connect(fd, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
1641 fatal( "%s: could not open '%s': %s", __FUNCTION__, serial_dev,
1645 /* initialize the serial reader/writer */
1647 recv.post = (PostFunc) multiplexer_serial_receive;
1648 recv.close = (CloseFunc) multiplexer_serial_close;
1650 serial_init( m->serial, fd, m->fdhandlers, &recv );
1652 /* open the qemud control socket */
1654 recv.post = (PostFunc) multiplexer_control_accept;
1655 recv.close = (CloseFunc) multiplexer_control_close;
1657 fd = android_get_control_socket(CONTROL_SOCKET_NAME);
1659 fatal("couldn't get fd for control socket '%s'", CONTROL_SOCKET_NAME);
1662 fdhandler_new_accept( fd, m->fdhandlers, &recv );
1664 /* initialize clients list */
1671 static Multiplexer _multiplexer[1];
1675 Multiplexer* m = _multiplexer;
1677 multiplexer_init(m, "/dev/qemud");
1679 D( "entering main loop");
1680 looper_loop( m->looper );
1681 D( "unexpected termination !!" );