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