a9185bad5ace0268bb5c1800d1912e4565cce557
[iec.git] / src / type3_AndroidCloud / anbox-master / android / qemud / qemud.c
1 #include <stdint.h>
2 #include <stdarg.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <fcntl.h>
6 #include <errno.h>
7 #include <string.h>
8 #include <sys/socket.h>
9 #include <termios.h>
10 #include <unistd.h>
11 #include <cutils/sockets.h>
12 #include <sys/un.h>
13
14 /*
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:
18  *
19  *    - qemud is started by init following instructions in
20  *      /system/etc/init.goldfish.rc (i.e. it is never started on real devices)
21  *
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)
25  *
26  *    - qemud binds one unix local stream socket (/dev/socket/qemud, created
27  *      by init through /system/etc/init.goldfish.rc).
28  *
29  *
30  *      emulator <==serial==> qemud <---> /dev/socket/qemud <-+--> client1
31  *                                                            |
32  *                                                            +--> client2
33  *
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:
37  *
38  *     * the client connects to /dev/socket/qemud
39  *
40  *     * the client sends the service name through the socket, as
41  *            <service-name>
42  *
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):
46  *
47  *           connect:<id>:<name>
48  *
49  *       where <name> is the service name, and <id> is a 2-hexchar
50  *       number corresponding to the channel number.
51  *
52  *     * in case of success, the emulator responds through channel 0
53  *       with:
54  *
55  *           ok:connect:<id>
56  *
57  *       after this, all messages between the client and the emulator
58  *       are passed in pass-through mode.
59  *
60  *     * if the emulator refuses the service connection, it will
61  *       send the following through channel 0:
62  *
63  *           ko:connect:<id>:reason-for-failure
64  *
65  *     * If the client closes the connection, qemud sends the following
66  *       to the emulator:
67  *
68  *           disconnect:<id>
69  *
70  *       The same message is the opposite direction if the emulator
71  *       chooses to close the connection.
72  *
73  *     * any command sent through channel 0 to the emulator that is
74  *       not properly recognized will be answered by:
75  *
76  *           ko:unknown command
77  *
78  *
79  *  Internally, the daemon maintains a "Client" object for each client
80  *  connection (i.e. accepting socket connection).
81  */
82
83 /* name of the single control socket used by the daemon */
84 #define CONTROL_SOCKET_NAME  "qemud"
85
86 #define  DEBUG     0
87 #define  T_ACTIVE  0  /* set to 1 to dump traffic */
88
89 #if DEBUG
90 #  define LOG_TAG  "qemud"
91 #  include <cutils/log.h>
92 #  define  D(...)   ALOGD(__VA_ARGS__)
93 #else
94 #  define  D(...)  ((void)0)
95 #  define  T(...)  ((void)0)
96 #endif
97
98 #if T_ACTIVE
99 #  define  T(...)   D(__VA_ARGS__)
100 #else
101 #  define  T(...)   ((void)0)
102 #endif
103
104 /** UTILITIES
105  **/
106
107 static void
108 fatal( const char*  fmt, ... )
109 {
110     va_list  args;
111     va_start(args, fmt);
112     fprintf(stderr, "PANIC: ");
113     vfprintf(stderr, fmt, args);
114     fprintf(stderr, "\n" );
115     va_end(args);
116     exit(1);
117 }
118
119 static void*
120 xalloc( size_t   sz )
121 {
122     void*  p;
123
124     if (sz == 0)
125         return NULL;
126
127     p = malloc(sz);
128     if (p == NULL)
129         fatal( "not enough memory" );
130
131     return p;
132 }
133
134 #define  xnew(p)   (p) = xalloc(sizeof(*(p)))
135
136 static void*
137 xalloc0( size_t  sz )
138 {
139     void*  p = xalloc(sz);
140     memset( p, 0, sz );
141     return p;
142 }
143
144 #define  xnew0(p)   (p) = xalloc0(sizeof(*(p)))
145
146 #define  xfree(p)    (free((p)), (p) = NULL)
147
148 static void*
149 xrealloc( void*  block, size_t  size )
150 {
151     void*  p = realloc( block, size );
152
153     if (p == NULL && size > 0)
154         fatal( "not enough memory" );
155
156     return p;
157 }
158
159 #define  xrenew(p,count)  (p) = xrealloc((p),sizeof(*(p))*(count))
160
161 static int
162 hex2int( const uint8_t*  data, int  len )
163 {
164     int  result = 0;
165     while (len > 0) {
166         int       c = *data++;
167         unsigned  d;
168
169         result <<= 4;
170         do {
171             d = (unsigned)(c - '0');
172             if (d < 10)
173                 break;
174
175             d = (unsigned)(c - 'a');
176             if (d < 6) {
177                 d += 10;
178                 break;
179             }
180
181             d = (unsigned)(c - 'A');
182             if (d < 6) {
183                 d += 10;
184                 break;
185             }
186
187             return -1;
188         }
189         while (0);
190
191         result |= d;
192         len    -= 1;
193     }
194     return  result;
195 }
196
197
198 static void
199 int2hex( int  value, uint8_t*  to, int  width )
200 {
201     int  nn = 0;
202     static const char hexchars[16] = "0123456789abcdef";
203
204     for ( --width; width >= 0; width--, nn++ ) {
205         to[nn] = hexchars[(value >> (width*4)) & 15];
206     }
207 }
208
209 static int
210 fd_read(int  fd, void*  to, int  len)
211 {
212     int  ret;
213
214     do {
215         ret = read(fd, to, len);
216     } while (ret < 0 && errno == EINTR);
217
218     return ret;
219 }
220
221 static int
222 fd_write(int  fd, const void*  from, int  len)
223 {
224     int  ret;
225
226     do {
227         ret = write(fd, from, len);
228     } while (ret < 0 && errno == EINTR);
229
230     return ret;
231 }
232
233 static void
234 fd_setnonblock(int  fd)
235 {
236     int  ret, flags;
237
238     do {
239         flags = fcntl(fd, F_GETFD);
240     } while (flags < 0 && errno == EINTR);
241
242     if (flags < 0) {
243         fatal( "%s: could not get flags for fd %d: %s",
244                __FUNCTION__, fd, strerror(errno) );
245     }
246
247     do {
248         ret = fcntl(fd, F_SETFD, flags | O_NONBLOCK);
249     } while (ret < 0 && errno == EINTR);
250
251     if (ret < 0) {
252         fatal( "%s: could not set fd %d to non-blocking: %s",
253                __FUNCTION__, fd, strerror(errno) );
254     }
255 }
256
257
258 static int
259 fd_accept(int  fd)
260 {
261     struct sockaddr  from;
262     socklen_t        fromlen = sizeof(from);
263     int              ret;
264
265     do {
266         ret = accept(fd, &from, &fromlen);
267     } while (ret < 0 && errno == EINTR);
268
269     return ret;
270 }
271
272 /** FD EVENT LOOP
273  **/
274
275 /* A Looper object is used to monitor activity on one or more
276  * file descriptors (e.g sockets).
277  *
278  * - call looper_add() to register a function that will be
279  *   called when events happen on the file descriptor.
280  *
281  * - call looper_enable() or looper_disable() to enable/disable
282  *   the set of monitored events for a given file descriptor.
283  *
284  * - call looper_del() to unregister a file descriptor.
285  *   this does *not* close the file descriptor.
286  *
287  * Note that you can only provide a single function to handle
288  * all events related to a given file descriptor.
289
290  * You can call looper_enable/_disable/_del within a function
291  * callback.
292  */
293
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
297  */
298 #include <sys/epoll.h>
299
300 #define  MAX_CHANNELS  16
301 #define  MAX_EVENTS    (MAX_CHANNELS+1)  /* each channel + the serial fd */
302
303 /* the event handler function type, 'user' is a user-specific
304  * opaque pointer passed to looper_add().
305  */
306 typedef void (*EventFunc)( void*  user, int  events );
307
308 /* bit flags for the LoopHook structure.
309  *
310  * HOOK_PENDING means that an event happened on the
311  * corresponding file descriptor.
312  *
313  * HOOK_CLOSING is used to delay-close monitored
314  * file descriptors.
315  */
316 enum {
317     HOOK_PENDING = (1 << 0),
318     HOOK_CLOSING = (1 << 1),
319 };
320
321 /* A LoopHook structure is used to monitor a given
322  * file descriptor and record its event handler.
323  */
324 typedef struct {
325     int        fd;
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 */
331 } LoopHook;
332
333 /* Looper is the main object modeling a looper object
334  */
335 typedef struct {
336     int                  epoll_fd;
337     int                  num_fds;
338     int                  max_fds;
339     struct epoll_event*  events;
340     LoopHook*            hooks;
341 } Looper;
342
343 /* initialize a looper object */
344 static void
345 looper_init( Looper*  l )
346 {
347     l->epoll_fd = epoll_create(4);
348     l->num_fds  = 0;
349     l->max_fds  = 0;
350     l->events   = NULL;
351     l->hooks    = NULL;
352 }
353
354 /* finalize a looper object */
355 static void
356 looper_done( Looper*  l )
357 {
358     xfree(l->events);
359     xfree(l->hooks);
360     l->max_fds = 0;
361     l->num_fds = 0;
362
363     close(l->epoll_fd);
364     l->epoll_fd  = -1;
365 }
366
367 /* return the LoopHook corresponding to a given
368  * monitored file descriptor, or NULL if not found
369  */
370 static LoopHook*
371 looper_find( Looper*  l, int  fd )
372 {
373     LoopHook*  hook = l->hooks;
374     LoopHook*  end  = hook + l->num_fds;
375
376     for ( ; hook < end; hook++ ) {
377         if (hook->fd == fd)
378             return hook;
379     }
380     return NULL;
381 }
382
383 /* grow the arrays in the looper object */
384 static void
385 looper_grow( Looper*  l )
386 {
387     int  old_max = l->max_fds;
388     int  new_max = old_max + (old_max >> 1) + 4;
389     int  n;
390
391     xrenew( l->events, new_max );
392     xrenew( l->hooks,  new_max );
393     l->max_fds = new_max;
394
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;
399
400         ev.events   = hook->wanted;
401         ev.data.ptr = hook;
402         epoll_ctl( l->epoll_fd, EPOLL_CTL_MOD, hook->fd, &ev );
403     }
404 }
405
406 /* register a file descriptor and its event handler.
407  * no event mask will be enabled
408  */
409 static void
410 looper_add( Looper*  l, int  fd, EventFunc  func, void*  user )
411 {
412     struct epoll_event  ev;
413     LoopHook*           hook;
414
415     if (l->num_fds >= l->max_fds)
416         looper_grow(l);
417
418     hook = l->hooks + l->num_fds;
419
420     hook->fd      = fd;
421     hook->ev_user = user;
422     hook->ev_func = func;
423     hook->state   = 0;
424     hook->wanted  = 0;
425     hook->events  = 0;
426
427     fd_setnonblock(fd);
428
429     ev.events   = 0;
430     ev.data.ptr = hook;
431     epoll_ctl( l->epoll_fd, EPOLL_CTL_ADD, fd, &ev );
432
433     l->num_fds += 1;
434 }
435
436 /* unregister a file descriptor and its event handler
437  */
438 static void
439 looper_del( Looper*  l, int  fd )
440 {
441     LoopHook*  hook = looper_find( l, fd );
442
443     if (!hook) {
444         D( "%s: invalid fd: %d", __FUNCTION__, fd );
445         return;
446     }
447     /* don't remove the hook yet */
448     hook->state |= HOOK_CLOSING;
449
450     epoll_ctl( l->epoll_fd, EPOLL_CTL_DEL, fd, NULL );
451 }
452
453 /* enable monitoring of certain events for a file
454  * descriptor. This adds 'events' to the current
455  * event mask
456  */
457 static void
458 looper_enable( Looper*  l, int  fd, int  events )
459 {
460     LoopHook*  hook = looper_find( l, fd );
461
462     if (!hook) {
463         D("%s: invalid fd: %d", __FUNCTION__, fd );
464         return;
465     }
466
467     if (events & ~hook->wanted) {
468         struct epoll_event  ev;
469
470         hook->wanted |= events;
471         ev.events   = hook->wanted;
472         ev.data.ptr = hook;
473
474         epoll_ctl( l->epoll_fd, EPOLL_CTL_MOD, fd, &ev );
475     }
476 }
477
478 /* disable monitoring of certain events for a file
479  * descriptor. This ignores events that are not
480  * currently enabled.
481  */
482 static void
483 looper_disable( Looper*  l, int  fd, int  events )
484 {
485     LoopHook*  hook = looper_find( l, fd );
486
487     if (!hook) {
488         D("%s: invalid fd: %d", __FUNCTION__, fd );
489         return;
490     }
491
492     if (events & hook->wanted) {
493         struct epoll_event  ev;
494
495         hook->wanted &= ~events;
496         ev.events   = hook->wanted;
497         ev.data.ptr = hook;
498
499         epoll_ctl( l->epoll_fd, EPOLL_CTL_MOD, fd, &ev );
500     }
501 }
502
503 /* wait until an event occurs on one of the registered file
504  * descriptors. Only returns in case of error !!
505  */
506 static void
507 looper_loop( Looper*  l )
508 {
509     for (;;) {
510         int  n, count;
511
512         do {
513             count = epoll_wait( l->epoll_fd, l->events, l->num_fds, -1 );
514         } while (count < 0 && errno == EINTR);
515
516         if (count < 0) {
517             D("%s: error: %s", __FUNCTION__, strerror(errno) );
518             return;
519         }
520
521         if (count == 0) {
522             D("%s: huh ? epoll returned count=0", __FUNCTION__);
523             continue;
524         }
525
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;
531         }
532
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 );
540             }
541         }
542
543         /* now remove all the hooks that were closed by
544          * the callbacks */
545         for (n = 0; n < l->num_fds;) {
546             struct epoll_event ev;
547             LoopHook*  hook = l->hooks + n;
548
549             if (!(hook->state & HOOK_CLOSING)) {
550                 n++;
551                 continue;
552             }
553
554             hook[0]     = l->hooks[l->num_fds-1];
555             l->num_fds -= 1;
556             ev.events   = hook->wanted;
557             ev.data.ptr = hook;
558             epoll_ctl( l->epoll_fd, EPOLL_CTL_MOD, hook->fd, &ev );
559         }
560     }
561 }
562
563 #if T_ACTIVE
564 char*
565 quote( const void*  data, int  len )
566 {
567     const char*  p   = data;
568     const char*  end = p + len;
569     int          count = 0;
570     int          phase = 0;
571     static char*  buff = NULL;
572
573     for (phase = 0; phase < 2; phase++) {
574         if (phase != 0) {
575             xfree(buff);
576             buff = xalloc(count+1);
577         }
578         count = 0;
579         for (p = data; p < end; p++) {
580             int  c = *p;
581
582             if (c == '\\') {
583                 if (phase != 0) {
584                     buff[count] = buff[count+1] = '\\';
585                 }
586                 count += 2;
587                 continue;
588             }
589
590             if (c >= 32 && c < 127) {
591                 if (phase != 0)
592                     buff[count] = c;
593                 count += 1;
594                 continue;
595             }
596
597
598             if (c == '\t') {
599                 if (phase != 0) {
600                     memcpy(buff+count, "<TAB>", 5);
601                 }
602                 count += 5;
603                 continue;
604             }
605             if (c == '\n') {
606                 if (phase != 0) {
607                     memcpy(buff+count, "<LN>", 4);
608                 }
609                 count += 4;
610                 continue;
611             }
612             if (c == '\r') {
613                 if (phase != 0) {
614                     memcpy(buff+count, "<CR>", 4);
615                 }
616                 count += 4;
617                 continue;
618             }
619
620             if (phase != 0) {
621                 buff[count+0] = '\\';
622                 buff[count+1] = 'x';
623                 buff[count+2] = "0123456789abcdef"[(c >> 4) & 15];
624                 buff[count+3] = "0123456789abcdef"[     (c) & 15];
625             }
626             count += 4;
627         }
628     }
629     buff[count] = 0;
630     return buff;
631 }
632 #endif /* T_ACTIVE */
633
634 /** PACKETS
635  **
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.
639  **/
640
641 typedef struct Packet   Packet;
642
643 #define  MAX_PAYLOAD  4000
644
645 struct Packet {
646     Packet*   next;
647     int       len;
648     int       channel;
649     uint8_t   data[ MAX_PAYLOAD ];
650 };
651
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.
655  */
656 static Packet*   _free_packets;
657
658 /* Allocate a packet */
659 static Packet*
660 packet_alloc(void)
661 {
662     Packet*  p = _free_packets;
663     if (p != NULL) {
664         _free_packets = p->next;
665     } else {
666         xnew(p);
667     }
668     p->next    = NULL;
669     p->len     = 0;
670     p->channel = -1;
671     return p;
672 }
673
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)
677  */
678 static void
679 packet_free( Packet*  *ppacket )
680 {
681     Packet*  p = *ppacket;
682     if (p) {
683         p->next       = _free_packets;
684         _free_packets = p;
685         *ppacket = NULL;
686     }
687 }
688
689 /** PACKET RECEIVER
690  **
691  ** Simple abstraction for something that can receive a packet
692  ** from a FDHandler (see below) or something else.
693  **
694  ** Send a packet to it with 'receiver_post'
695  **
696  ** Call 'receiver_close' to indicate that the corresponding
697  ** packet source was closed.
698  **/
699
700 typedef void (*PostFunc) ( void*  user, Packet*  p );
701 typedef void (*CloseFunc)( void*  user );
702
703 typedef struct {
704     PostFunc   post;
705     CloseFunc  close;
706     void*      user;
707 } Receiver;
708
709 /* post a packet to a receiver. Note that this transfers
710  * ownership of the packet to the receiver.
711  */
712 static __inline__ void
713 receiver_post( Receiver*  r, Packet*  p )
714 {
715     if (r->post)
716         r->post( r->user, p );
717     else
718         packet_free(&p);
719 }
720
721 /* tell a receiver the packet source was closed.
722  * this will also prevent further posting to the
723  * receiver.
724  */
725 static __inline__ void
726 receiver_close( Receiver*  r )
727 {
728     if (r->close) {
729         r->close( r->user );
730         r->close = NULL;
731     }
732     r->post  = NULL;
733 }
734
735
736 /** FD HANDLERS
737  **
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.
741  **
742  ** note that we support clean shutdown of file descriptors,
743  ** i.e. we try to send all outgoing packets before destroying
744  ** the FDHandler.
745  **/
746
747 typedef struct FDHandler      FDHandler;
748 typedef struct FDHandlerList  FDHandlerList;
749
750 struct FDHandler {
751     int             fd;
752     FDHandlerList*  list;
753     char            closing;
754     Receiver        receiver[1];
755
756     /* queue of outgoing packets */
757     int             out_pos;
758     Packet*         out_first;
759     Packet**        out_ptail;
760
761     FDHandler*      next;
762     FDHandler**     pref;
763
764 };
765
766 struct FDHandlerList {
767     /* the looper that manages the fds */
768     Looper*      looper;
769
770     /* list of active FDHandler objects */
771     FDHandler*   active;
772
773     /* list of closing FDHandler objects.
774      * these are waiting to push their
775      * queued packets to the fd before
776      * freeing themselves.
777      */
778     FDHandler*   closing;
779
780 };
781
782 /* remove a FDHandler from its current list */
783 static void
784 fdhandler_remove( FDHandler*  f )
785 {
786     f->pref[0] = f->next;
787     if (f->next)
788         f->next->pref = f->pref;
789 }
790
791 /* add a FDHandler to a given list */
792 static void
793 fdhandler_prepend( FDHandler*  f, FDHandler**  list )
794 {
795     f->next = list[0];
796     f->pref = list;
797     list[0] = f;
798     if (f->next)
799         f->next->pref = &f->next;
800 }
801
802 /* initialize a FDHandler list */
803 static void
804 fdhandler_list_init( FDHandlerList*  list, Looper*  looper )
805 {
806     list->looper  = looper;
807     list->active  = NULL;
808     list->closing = NULL;
809 }
810
811
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.
815  *
816  * this *will* notify the receiver that the file descriptor
817  * was closed.
818  *
819  * you should call fdhandler_shutdown() if you want to
820  * notify the FDHandler that its packet source is closed.
821  */
822 static void
823 fdhandler_close( FDHandler*  f )
824 {
825     /* notify receiver */
826     receiver_close(f->receiver);
827
828     /* remove the handler from its list */
829     fdhandler_remove(f);
830
831     /* get rid of outgoing packet queue */
832     if (f->out_first != NULL) {
833         Packet*  p;
834         while ((p = f->out_first) != NULL) {
835             f->out_first = p->next;
836             packet_free(&p);
837         }
838     }
839
840     /* get rid of file descriptor */
841     if (f->fd >= 0) {
842         looper_del( f->list->looper, f->fd );
843         close(f->fd);
844         f->fd = -1;
845     }
846
847     f->list = NULL;
848     xfree(f);
849 }
850
851 /* Ask the FDHandler to cleanly shutdown the connection,
852  * i.e. send any pending outgoing packets then auto-free
853  * itself.
854  */
855 static void
856 fdhandler_shutdown( FDHandler*  f )
857 {
858     /* prevent later fdhandler_close() to
859      * call the receiver's close.
860      */
861     f->receiver->close = NULL;
862
863     if (f->out_first != NULL && !f->closing)
864     {
865         /* move the handler to the 'closing' list */
866         f->closing = 1;
867         fdhandler_remove(f);
868         fdhandler_prepend(f, &f->list->closing);
869         return;
870     }
871
872     fdhandler_close(f);
873 }
874
875 /* Enqueue a new packet that the FDHandler will
876  * send through its file descriptor.
877  */
878 static void
879 fdhandler_enqueue( FDHandler*  f, Packet*  p )
880 {
881     Packet*  first = f->out_first;
882
883     p->next         = NULL;
884     f->out_ptail[0] = p;
885     f->out_ptail    = &p->next;
886
887     if (first == NULL) {
888         f->out_pos = 0;
889         looper_enable( f->list->looper, f->fd, EPOLLOUT );
890     }
891 }
892
893
894 /* FDHandler file descriptor event callback for read/write ops */
895 static void
896 fdhandler_event( FDHandler*  f, int  events )
897 {
898    int  len;
899
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.
905      */
906
907     if (events & EPOLLIN) {
908         Packet*  p = packet_alloc();
909         int      len;
910
911         if ((len = fd_read(f->fd, p->data, MAX_PAYLOAD)) < 0) {
912             D("%s: can't recv: %s", __FUNCTION__, strerror(errno));
913             packet_free(&p);
914         } else if (len > 0) {
915             p->len     = len;
916             p->channel = -101;  /* special debug value, not used */
917             receiver_post( f->receiver, p );
918         }
919     }
920
921     if (events & (EPOLLHUP|EPOLLERR)) {
922         /* disconnection */
923         D("%s: disconnect on fd %d", __FUNCTION__, f->fd);
924         fdhandler_close(f);
925         return;
926     }
927
928     if (events & EPOLLOUT && f->out_first) {
929         Packet*  p = f->out_first;
930         int      avail, len;
931
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));
935         } else {
936             f->out_pos += len;
937             if (f->out_pos >= p->len) {
938                 f->out_pos   = 0;
939                 f->out_first = p->next;
940                 packet_free(&p);
941                 if (f->out_first == NULL) {
942                     f->out_ptail = &f->out_first;
943                     looper_disable( f->list->looper, f->fd, EPOLLOUT );
944                 }
945             }
946         }
947     }
948 }
949
950
951 /* Create a new FDHandler that monitors read/writes */
952 static FDHandler*
953 fdhandler_new( int             fd,
954                FDHandlerList*  list,
955                Receiver*       receiver )
956 {
957     FDHandler*  f = xalloc0(sizeof(*f));
958
959     f->fd          = fd;
960     f->list        = list;
961     f->receiver[0] = receiver[0];
962     f->out_first   = NULL;
963     f->out_ptail   = &f->out_first;
964     f->out_pos     = 0;
965
966     fdhandler_prepend(f, &list->active);
967
968     looper_add( list->looper, fd, (EventFunc) fdhandler_event, f );
969     looper_enable( list->looper, fd, EPOLLIN );
970
971     return f;
972 }
973
974
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
978  */
979 static void
980 fdhandler_accept_event( FDHandler*  f, int  events )
981 {
982     if (events & EPOLLIN) {
983         /* this is an accept - send a dummy packet to the receiver */
984         Packet*  p = packet_alloc();
985
986         D("%s: accepting on fd %d", __FUNCTION__, f->fd);
987         p->data[0] = 1;
988         p->len     = 1;
989         p->channel = fd_accept(f->fd);
990         if (p->channel < 0) {
991             D("%s: accept failed ?: %s", __FUNCTION__, strerror(errno));
992             packet_free(&p);
993             return;
994         }
995         receiver_post( f->receiver, p );
996     }
997
998     if (events & (EPOLLHUP|EPOLLERR)) {
999         /* disconnecting !! */
1000         D("%s: closing accept fd %d", __FUNCTION__, f->fd);
1001         fdhandler_close(f);
1002         return;
1003     }
1004 }
1005
1006
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.
1010  */
1011 static FDHandler*
1012 fdhandler_new_accept( int             fd,
1013                       FDHandlerList*  list,
1014                       Receiver*       receiver )
1015 {
1016     FDHandler*  f = xalloc0(sizeof(*f));
1017
1018     f->fd          = fd;
1019     f->list        = list;
1020     f->receiver[0] = receiver[0];
1021
1022     fdhandler_prepend(f, &list->active);
1023
1024     looper_add( list->looper, fd, (EventFunc) fdhandler_accept_event, f );
1025     looper_enable( list->looper, fd, EPOLLIN );
1026     listen( fd, 5 );
1027
1028     return f;
1029 }
1030
1031 /** SERIAL CONNECTION STATE
1032  **
1033  ** The following is used to handle the framing protocol
1034  ** used on the serial port connection.
1035  **/
1036
1037 /* each packet is made of a 6 byte header followed by a payload
1038  * the header looks like:
1039  *
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
1044  */
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
1050
1051 #define  CHANNEL_CONTROL  0
1052
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.
1056  *
1057  * You can also use serial_send to send a packet through
1058  * the serial port.
1059  */
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 */
1067 } Serial;
1068
1069
1070 /* a callback called when the serial port's fd is closed */
1071 static void
1072 serial_fd_close( Serial*  s )
1073 {
1074     fatal("unexpected serial port close !!");
1075 }
1076
1077 static void
1078 serial_dump( Packet*  p, const char*  funcname )
1079 {
1080     T("%s: %03d bytes: '%s'",
1081       funcname, p->len, quote(p->data, p->len));
1082 }
1083
1084 /* a callback called when a packet arrives from the serial port's FDHandler.
1085  *
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'.
1088  *
1089  * After that, the payload is sent to the receiver once completed.
1090  */
1091 static void
1092 serial_fd_receive( Serial*  s, Packet*  p )
1093 {
1094     int      rpos  = 0, rcount = p->len;
1095     Packet*  inp   = s->in_packet;
1096     int      inpos = s->in_len;
1097
1098     serial_dump( p, __FUNCTION__ );
1099
1100     while (rpos < rcount)
1101     {
1102         int  avail = rcount - rpos;
1103
1104         /* first, try to read the header */
1105         if (s->in_datalen == 0) {
1106             int  wanted = HEADER_SIZE - inpos;
1107             if (avail > wanted)
1108                 avail = wanted;
1109
1110             memcpy( inp->data + inpos, p->data + rpos, avail );
1111             inpos += avail;
1112             rpos  += avail;
1113
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 );
1117
1118                 if (s->in_datalen <= 0) {
1119                     D("ignoring %s packet from serial port",
1120                       s->in_datalen ? "empty" : "malformed");
1121                     s->in_datalen = 0;
1122                 }
1123
1124                 //D("received %d bytes packet for channel %d", s->in_datalen, s->in_channel);
1125                 inpos = 0;
1126             }
1127         }
1128         else /* then, populate the packet itself */
1129         {
1130             int   wanted = s->in_datalen - inpos;
1131
1132             if (avail > wanted)
1133                 avail = wanted;
1134
1135             memcpy( inp->data + inpos, p->data + rpos, avail );
1136             inpos += avail;
1137             rpos  += avail;
1138
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);
1143                 } else {
1144                     inp->len     = inpos;
1145                     inp->channel = s->in_channel;
1146                     receiver_post( s->receiver, inp );
1147                     s->in_packet  = inp = packet_alloc();
1148                 }
1149                 s->in_datalen = 0;
1150                 inpos         = 0;
1151             }
1152         }
1153     }
1154     s->in_len = inpos;
1155     packet_free(&p);
1156 }
1157
1158
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.
1162  */
1163 static void
1164 serial_send( Serial*  s, Packet*  p )
1165 {
1166     Packet*  h = packet_alloc();
1167
1168     //D("sending to serial %d bytes from channel %d: '%.*s'", p->len, p->channel, p->len, p->data);
1169
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 );
1174
1175     serial_dump( h, __FUNCTION__ );
1176     serial_dump( p, __FUNCTION__ );
1177
1178     fdhandler_enqueue( s->fdhandler, h );
1179     fdhandler_enqueue( s->fdhandler, p );
1180 }
1181
1182
1183 /* initialize serial reader */
1184 static void
1185 serial_init( Serial*         s,
1186              int             fd,
1187              FDHandlerList*  list,
1188              Receiver*       receiver )
1189 {
1190     Receiver  recv;
1191
1192     recv.user  = s;
1193     recv.post  = (PostFunc)  serial_fd_receive;
1194     recv.close = (CloseFunc) serial_fd_close;
1195
1196     s->receiver[0] = receiver[0];
1197
1198     s->fdhandler = fdhandler_new( fd, list, &recv );
1199     s->in_len     = 0;
1200     s->in_datalen = 0;
1201     s->in_channel = 0;
1202     s->in_packet  = packet_alloc();
1203 }
1204
1205
1206 /** CLIENTS
1207  **/
1208
1209 typedef struct Client       Client;
1210 typedef struct Multiplexer  Multiplexer;
1211
1212 /* A Client object models a single qemud client socket
1213  * connection in the emulated system.
1214  *
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.
1218  *
1219  * the answer is either "OK" or "KO" to indicate
1220  * success or failure.
1221  *
1222  * In case of success, the client can send messages
1223  * to the service.
1224  *
1225  * In case of failure, it can disconnect or try sending
1226  * the name of another service.
1227  */
1228 struct Client {
1229     Client*       next;
1230     Client**      pref;
1231     int           channel;
1232     char          registered;
1233     FDHandler*    fdhandler;
1234     Multiplexer*  multiplexer;
1235 };
1236
1237 struct Multiplexer {
1238     Client*        clients;
1239     int            last_channel;
1240     Serial         serial[1];
1241     Looper         looper[1];
1242     FDHandlerList  fdhandlers[1];
1243 };
1244
1245
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 );
1249
1250 static void
1251 client_dump( Client*  c, Packet*  p, const char*  funcname )
1252 {
1253     T("%s: client %p (%d): %3d bytes: '%s'",
1254       funcname, c, c->fdhandler->fd,
1255       p->len, quote(p->data, p->len));
1256 }
1257
1258 /* destroy a client */
1259 static void
1260 client_free( Client*  c )
1261 {
1262     /* remove from list */
1263     c->pref[0] = c->next;
1264     if (c->next)
1265         c->next->pref = c->pref;
1266
1267     c->channel    = -1;
1268     c->registered = 0;
1269
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;
1275     }
1276
1277     xfree(c);
1278 }
1279
1280
1281 /* a function called when a client socket receives data */
1282 static void
1283 client_fd_receive( Client*  c, Packet*  p )
1284 {
1285     client_dump(c, p, __FUNCTION__);
1286
1287     if (c->registered) {
1288         /* the client is registered, just send the
1289          * data through the serial port
1290          */
1291         multiplexer_serial_send(c->multiplexer, c->channel, p);
1292         return;
1293     }
1294
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.
1300          */
1301          D("%s: bad client sending data before end of registration",
1302            __FUNCTION__);
1303      BAD_CLIENT:
1304          packet_free(&p);
1305          client_free(c);
1306          return;
1307     }
1308
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
1312      * it.
1313      */
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__);
1319         goto BAD_CLIENT;
1320     }
1321     D("%s:    -> received channel id %d", __FUNCTION__, c->channel);
1322     packet_free(&p);
1323 }
1324
1325
1326 /* a function called when the client socket is closed. */
1327 static void
1328 client_fd_close( Client*  c )
1329 {
1330     T("%s: client %p (%d)", __FUNCTION__, c, c->fdhandler->fd);
1331
1332     /* no need to shutdown the FDHandler */
1333     c->fdhandler = NULL;
1334
1335     /* tell the emulator we're out */
1336     if (c->channel > 0)
1337         multiplexer_close_channel(c->multiplexer, c->channel);
1338
1339     /* free the client */
1340     client_free(c);
1341 }
1342
1343 /* a function called when the multiplexer received a registration
1344  * response from the emulator for a given client.
1345  */
1346 static void
1347 client_registration( Client*  c, int  registered )
1348 {
1349     Packet*  p = packet_alloc();
1350
1351     /* sends registration status to client */
1352     if (!registered) {
1353         D("%s: registration failed for client %d", __FUNCTION__, c->channel);
1354         memcpy( p->data, "KO", 2 );
1355         p->len = 2;
1356     } else {
1357         D("%s: registration succeeded for client %d", __FUNCTION__, c->channel);
1358         memcpy( p->data, "OK", 2 );
1359         p->len = 2;
1360     }
1361     client_dump(c, p, __FUNCTION__);
1362     fdhandler_enqueue(c->fdhandler, p);
1363
1364     /* now save registration state
1365      */
1366     c->registered = registered;
1367     if (!registered) {
1368         /* allow the client to try registering another service */
1369         c->channel = -1;
1370     }
1371 }
1372
1373 /* send data to a client */
1374 static void
1375 client_send( Client*  c, Packet*  p )
1376 {
1377     client_dump(c, p, __FUNCTION__);
1378     fdhandler_enqueue(c->fdhandler, p);
1379 }
1380
1381
1382 /* Create new client socket handler */
1383 static Client*
1384 client_new( Multiplexer*    mult,
1385             int             fd,
1386             FDHandlerList*  pfdhandlers,
1387             Client**        pclients )
1388 {
1389     Client*   c;
1390     Receiver  recv;
1391
1392     xnew(c);
1393
1394     c->multiplexer = mult;
1395     c->next        = NULL;
1396     c->pref        = &c->next;
1397     c->channel     = -1;
1398     c->registered  = 0;
1399
1400     recv.user  = c;
1401     recv.post  = (PostFunc)  client_fd_receive;
1402     recv.close = (CloseFunc) client_fd_close;
1403
1404     c->fdhandler = fdhandler_new( fd, pfdhandlers, &recv );
1405
1406     /* add to client list */
1407     c->next   = *pclients;
1408     c->pref   = pclients;
1409     *pclients = c;
1410     if (c->next)
1411         c->next->pref = &c->next;
1412
1413     return c;
1414 }
1415
1416 /**  GLOBAL MULTIPLEXER
1417  **/
1418
1419 /* find a client by its channel */
1420 static Client*
1421 multiplexer_find_client( Multiplexer*  mult, int  channel )
1422 {
1423     Client* c = mult->clients;
1424
1425     for ( ; c != NULL; c = c->next ) {
1426         if (c->channel == channel)
1427             return c;
1428     }
1429     return NULL;
1430 }
1431
1432 /* handle control messages coming from the serial port
1433  * on CONTROL_CHANNEL.
1434  */
1435 static void
1436 multiplexer_handle_control( Multiplexer*  mult, Packet*  p )
1437 {
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);
1442
1443         /* note that 'client' can be NULL if the corresponding
1444          * socket was closed before the emulator response arrived.
1445          */
1446         if (client != NULL) {
1447             client_registration(client, 1);
1448         } else {
1449             D("%s: NULL client: '%.*s'", __FUNCTION__, p->len, p->data+11);
1450         }
1451         goto EXIT;
1452     }
1453
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);
1458
1459         if (client != NULL)
1460             client_registration(client, 0);
1461
1462         goto EXIT;
1463     }
1464
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);
1469
1470         if (client != NULL)
1471             client_free(client);
1472
1473         goto EXIT;
1474     }
1475
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
1480      * message.
1481      */
1482     if (p->len >= 3 && !memcmp(p->data,"X00",3)) {
1483         goto EXIT;
1484     }
1485
1486     D("%s: unknown control message (%d bytes): '%.*s'",
1487       __FUNCTION__, p->len, p->len, p->data);
1488
1489 EXIT:
1490     packet_free(&p);
1491 }
1492
1493 /* a function called when an incoming packet comes from the serial port */
1494 static void
1495 multiplexer_serial_receive( Multiplexer*  mult, Packet*  p )
1496 {
1497     Client*  client;
1498
1499     T("%s: channel=%d '%.*s'", __FUNCTION__, p->channel, p->len, p->data);
1500
1501     if (p->channel == CHANNEL_CONTROL) {
1502         multiplexer_handle_control(mult, p);
1503         return;
1504     }
1505
1506     client = multiplexer_find_client(mult, p->channel);
1507     if (client != NULL) {
1508         client_send(client, p);
1509         return;
1510     }
1511
1512     D("%s: discarding packet for unknown channel %d", __FUNCTION__, p->channel);
1513     packet_free(&p);
1514 }
1515
1516 /* a function called when the serial reader closes */
1517 static void
1518 multiplexer_serial_close( Multiplexer*  mult )
1519 {
1520     fatal("unexpected close of serial reader");
1521 }
1522
1523 /* a function called to send a packet to the serial port */
1524 static void
1525 multiplexer_serial_send( Multiplexer*  mult, int  channel, Packet*  p )
1526 {
1527     p->channel = channel;
1528     serial_send( mult->serial, p );
1529 }
1530
1531
1532
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.
1536  *
1537  * returns -1 if the service name is too long.
1538  *
1539  * notice that client_registration() will be called later when
1540  * the answer arrives.
1541  */
1542 static int
1543 multiplexer_open_channel( Multiplexer*  mult, Packet*  service )
1544 {
1545     Packet*   p = packet_alloc();
1546     int       len, channel;
1547
1548     /* find a free channel number, assume we don't have many
1549      * clients here. */
1550     {
1551         Client*  c;
1552     TRY_AGAIN:
1553         channel = (++mult->last_channel) & 0xff;
1554
1555         for (c = mult->clients; c != NULL; c = c->next)
1556             if (c->channel == channel)
1557                 goto TRY_AGAIN;
1558     }
1559
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));
1563         packet_free(&p);
1564         return -1;
1565     }
1566     p->channel = CHANNEL_CONTROL;
1567     p->len     = len;
1568
1569     serial_send(mult->serial, p);
1570     return channel;
1571 }
1572
1573 /* used to tell the emulator a channel was closed by a client */
1574 static void
1575 multiplexer_close_channel( Multiplexer*  mult, int  channel )
1576 {
1577     Packet*  p   = packet_alloc();
1578     int      len = snprintf((char*)p->data, sizeof(p->data), "disconnect:%02x", channel);
1579
1580     if (len > (int)sizeof(p->data)) {
1581         /* should not happen */
1582         return;
1583     }
1584
1585     p->channel = CHANNEL_CONTROL;
1586     p->len     = len;
1587
1588     serial_send(mult->serial, p);
1589 }
1590
1591 /* this function is used when a new connection happens on the control
1592  * socket.
1593  */
1594 static void
1595 multiplexer_control_accept( Multiplexer*  m, Packet*  p )
1596 {
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 );
1601
1602     D("created client %p listening on fd %d", client, fd);
1603
1604     /* free dummy packet */
1605     packet_free(&p);
1606 }
1607
1608 static void
1609 multiplexer_control_close( Multiplexer*  m )
1610 {
1611     fatal("unexpected multiplexer control close");
1612 }
1613
1614 static void
1615 multiplexer_init( Multiplexer*  m, const char*  serial_dev )
1616 {
1617     int       fd, control_fd;
1618     Receiver  recv;
1619
1620     /* initialize looper and fdhandlers list */
1621     looper_init( m->looper );
1622     fdhandler_list_init( m->fdhandlers, m->looper );
1623
1624     /* open the serial port */
1625     do {
1626         fd = socket(AF_LOCAL, SOCK_STREAM, 0);
1627     } while (fd < 0 && errno == EINTR);
1628
1629     struct sockaddr_un addr;
1630
1631     memset(&addr, 0, sizeof(addr));
1632     addr.sun_family = AF_UNIX;
1633     strncpy(addr.sun_path, serial_dev, sizeof(addr.sun_path));
1634
1635     if (connect(fd, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
1636         close(fd);
1637         fd = -1;
1638     }
1639
1640     if (fd < 0) {
1641         fatal( "%s: could not open '%s': %s", __FUNCTION__, serial_dev,
1642                strerror(errno) );
1643     }
1644
1645     /* initialize the serial reader/writer */
1646     recv.user  = m;
1647     recv.post  = (PostFunc)  multiplexer_serial_receive;
1648     recv.close = (CloseFunc) multiplexer_serial_close;
1649
1650     serial_init( m->serial, fd, m->fdhandlers, &recv );
1651
1652     /* open the qemud control socket */
1653     recv.user  = m;
1654     recv.post  = (PostFunc)  multiplexer_control_accept;
1655     recv.close = (CloseFunc) multiplexer_control_close;
1656
1657     fd = android_get_control_socket(CONTROL_SOCKET_NAME);
1658     if (fd < 0) {
1659         fatal("couldn't get fd for control socket '%s'", CONTROL_SOCKET_NAME);
1660     }
1661
1662     fdhandler_new_accept( fd, m->fdhandlers, &recv );
1663
1664     /* initialize clients list */
1665     m->clients = NULL;
1666 }
1667
1668 /** MAIN LOOP
1669  **/
1670
1671 static Multiplexer  _multiplexer[1];
1672
1673 int  main( void )
1674 {
1675     Multiplexer*  m = _multiplexer;
1676
1677     multiplexer_init(m, "/dev/qemud");
1678
1679     D( "entering main loop");
1680     looper_loop( m->looper );
1681     D( "unexpected termination !!" );
1682     return 0;
1683 }