2 * Copyright (C) 2009 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #include <sys/types.h>
32 #include <sys/socket.h>
35 #define UNIX_PATH_MAX 108
37 #include <apr_general.h>
38 #include <apr_network_io.h>
39 #include <apr_getopt.h>
40 #include <apr_strings.h>
41 #include <apr_thread_proc.h>
44 #include <apr_portable.h>
46 #include "hostinfod.h"
48 static void main_loop (void);
49 static void set_reread_socket_dir (const apr_pollfd_t *, void *);
50 static void do_reread_socket_dir (void);
51 static struct guest_description *guest_added (const char *sock_path, const char *name);
52 static void guest_removed (struct guest_description *);
53 static void guest_event (const apr_pollfd_t *, void *);
55 const char *conf_file = DEFAULT_CONF_FILE;
56 char *socket_dir = NULL;
57 char *guests_file = NULL;
60 int verbose_set_on_cmdline = 0;
62 int foreground_set_on_cmdline = 0;
64 int messages_to_stderr = 1;
66 static int reread_socket_dir = 1;
69 apr_pool_t *pool = NULL;
70 static apr_pollset_t *set = NULL;
72 static apr_hash_t *guests = NULL; /* Hash "driver-name" -> guest_description */
74 typedef void (*poll_callback) (const apr_pollfd_t *, void *data);
75 struct callback_data {
76 poll_callback callback;
83 printf ("hostinfod (virt-hostinfo daemon)\n"
84 "Copyright (C) 2009 Red Hat Inc.\n"
87 " hostinfod [--options]\n"
90 " --help Display full usage\n"
91 " -c file | --config file\n"
92 " Configuration file (default: %s)\n"
93 " -f | --foreground\n"
94 " Run in the foreground (don't fork)\n"
95 " -v Enable verbose messages (sent to syslog)\n",
100 main (int argc, char *argv[])
102 static const apr_getopt_option_t options[] = {
103 { "config", 'c', TRUE, "configuration file" },
104 { "foreground", 'f', FALSE, "run in foreground (don't fork)" },
105 { "verbose", 'v', FALSE, "enable verbose messages" },
106 { "help", '?', FALSE, "display help" },
107 { NULL, 0, 0, NULL },
115 apr_pool_create (&pool, NULL);
117 apr_getopt_init (&opt, pool, argc, argv);
121 socket_dir = apr_pstrdup (pool, DEFAULT_SOCKET_DIR);
122 guests_file = apr_pstrdup (pool, DEFAULT_GUESTS_FILE);
125 while ((r = apr_getopt_long (opt, options, &c, &optarg)) == APR_SUCCESS) {
129 /* If the user is specifying this on the command line, then
130 * it should exist. They may have typo'd the name.
132 if (access (conf_file, R_OK) == -1) {
133 perrorf ("%s", conf_file);
139 foreground_set_on_cmdline = 1;
143 verbose_set_on_cmdline = 1;
153 fprintf (stderr, "%s: unknown command line option\n", argv[0]);
157 /* Read the config file. */
158 read_main_conf_file ();
160 /* Monitor the socket directory. */
161 monitor_socket_dir ();
163 /* Create the guests hash. */
164 guests = apr_hash_make (pool);
166 /* Create the initial pollset, just containing inotify socket. */
167 r = apr_pollset_create (&set, 1024 /* ? */, pool, 0);
168 if (r != APR_SUCCESS) {
169 paprerror (r, "apr_pollset_create");
173 r = apr_os_sock_put (&tsock, &sockets_inotify_fd, pool);
174 if (r != APR_SUCCESS) {
175 paprerror (r, "apr_os_sock_put");
178 apr_pollfd_t *tpollfd = apr_palloc (pool, sizeof *tpollfd);
180 tpollfd->desc_type = APR_POLL_SOCKET;
181 tpollfd->reqevents = APR_POLLIN;
182 tpollfd->rtnevents = 0;
183 tpollfd->desc.s = tsock;
185 struct callback_data *callback_data =
186 apr_palloc (pool, sizeof *callback_data);
187 callback_data->callback = set_reread_socket_dir;
188 callback_data->data = NULL;
189 tpollfd->client_data = callback_data;
191 r = apr_pollset_add (set, tpollfd);
192 if (r != APR_SUCCESS) {
193 paprerror (r, "apr_pollset_add");
202 /* After we detach from the terminal, all further messages
203 * should just go to syslog.
205 messages_to_stderr = 0;
208 message ("%s started", PACKAGE_STRING);
210 message ("%s exiting", PACKAGE_STRING);
220 apr_int32_t numdescs;
221 const apr_pollfd_t *descs;
225 /* A socket has appeared or disappeared from the socket directory. */
226 if (reread_socket_dir) {
227 do_reread_socket_dir ();
228 reread_socket_dir = 0;
232 r = apr_pollset_poll (set, -1, &numdescs, &descs);
233 if (r != APR_SUCCESS) {
234 paprerror (r, "apr_pollset_poll");
238 /* Perform the callbacks. */
239 for (i = 0; i < numdescs; ++i) {
240 struct callback_data *callback_data;
242 callback_data = descs[i].client_data;
243 callback_data->callback (&descs[i], callback_data->data);
249 set_reread_socket_dir (const apr_pollfd_t *ignored1, void *ignored2)
251 reread_socket_dir = 1;
255 do_reread_socket_dir (void)
257 static int count = 0;
258 int added = 0, removed = 0;
264 struct guest_description *hval;
265 apr_hash_index_t *hi;
268 debug ("reading socket directory (counter = %d)", count);
270 /* Discard anything which appears on the inotify socket. We will
271 * reread the whole directory each time.
274 r = read (sockets_inotify_fd, buf, sizeof buf);
276 if (errno != EAGAIN && errno != EWOULDBLOCK) {
277 perrorf ("inotify socket: read");
283 dir = opendir (socket_dir);
285 perrorf ("%s: failed to open socket directory", socket_dir);
289 while (errno = 0, (d = readdir (dir)) != NULL) {
290 /* We expect the name to be "<driver>-<name>" (where <driver>
291 * is the libvirt driver name, and <name> is the name of the
292 * domain). Skip any dot-entries and anything that doesn't have
295 if (d->d_name[0] == '.')
297 if (strlen (d->d_name) < 3 || strchr (&d->d_name[1], '-') == NULL)
300 /* It must be a Unix domain socket - skip anything else. */
301 snprintf (buf, sizeof buf, "%s/%s", socket_dir, d->d_name);
302 if (stat (buf, &statbuf) == -1) {
303 perrorf ("stat: %s", buf);
306 if (!S_ISSOCK (statbuf.st_mode))
309 /* See if we have an entry matching this already. */
310 hval = (struct guest_description *)
311 apr_hash_get (guests, d->d_name, APR_HASH_KEY_STRING);
313 hval = guest_added (buf, d->d_name);
317 /* NB. It's not well documented, but the hash table
318 * implementation DOES NOT copy the key internally. Therefore
319 * we have to use hval->name (ie. our copy) as the key, NOT
320 * d->d_name, even though they are the same string.
322 apr_hash_set (guests, hval->name, APR_HASH_KEY_STRING, hval);
326 hval->counter = count;
329 perrorf ("%s: error reading socket directory", socket_dir);
333 if (closedir (dir) == -1) {
334 perrorf ("%s: error closing socket directory", socket_dir);
338 /* Iterate over the hash and look for any guests which have
339 * gone away. The guest_description.counter field won't have
342 for (hi = apr_hash_first (pool, guests); hi; hi = apr_hash_next (hi)) {
343 apr_hash_this(hi, NULL, NULL, (void **) &hval);
344 if (hval->counter != count) {
345 /* This hash table implementation allows you to delete the
346 * current entry safely.
348 apr_hash_set (guests, hval->name, APR_HASH_KEY_STRING, NULL);
350 /* guest_removed frees hval but does not unregister it from the
353 guest_removed (hval);
358 debug ("finished reading socket directory, added %d, removed %d, guests %d",
359 added, removed, apr_hash_count (guests));
362 /* This is called whenever we detect that a guest socket has been
363 * created in the socket directory.
365 static struct guest_description *
366 guest_added (const char *sock_path, const char *name)
368 struct guest_description *hval = NULL;
371 unsigned retries = 0, tns;
372 enum guest_state state;
373 apr_pool_t *guest_pool;
374 struct sockaddr_un addr;
377 sock = socket (AF_UNIX, SOCK_STREAM, 0);
383 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
384 perrorf ("fcntl: O_NONBLOCK");
388 if (fcntl (sock, F_SETFD, FD_CLOEXEC) == -1) {
389 perrorf ("fcntl: FD_CLOEXEC");
394 addr.sun_family = AF_UNIX;
395 strncpy (addr.sun_path, sock_path, UNIX_PATH_MAX);
396 addr.sun_path[UNIX_PATH_MAX-1] = '\0';
399 r = connect (sock, (struct sockaddr *) &addr, sizeof addr);
401 /* Nasty race condition: The moment the listener binds the socket,
402 * we see it in the directory and can try to connect to it.
403 * However the listener might not have called listen(2) yet, which
404 * means if we are faster than the other end, we will get
405 * ECONNREFUSED. If this happens, sleep a bit and try again a few
408 if (errno == ECONNREFUSED) {
411 ts.tv_sec = tns / 1000000000;
412 ts.tv_nsec = tns % 1000000000;
413 nanosleep (&ts, NULL);
419 if (errno != EINPROGRESS) {
420 /* Dead socket - cull these dead sockets from the directory. */
421 perrorf ("connect: %s", sock_path);
426 state = guest_state_connecting;
429 state = guest_state_request;
431 /* Create a pool which can be used for allocations
432 * during the lifetime of this guest connection.
434 apr_pool_create (&guest_pool, pool);
436 hval = apr_pcalloc (guest_pool, sizeof *hval);
437 hval->pool = guest_pool;
439 /* Create the remaining hash fields. */
441 hval->name = apr_pstrdup (hval->pool, name);
442 hval->sock_path = apr_pstrdup (hval->pool, sock_path);
444 hval->request_max = 4096;
445 hval->request = apr_palloc (hval->pool, hval->request_max);
447 /* Convert Unix fd into APR socket type. */
448 r = apr_os_sock_put (&hval->aprsock, &sock, hval->pool);
449 if (r != APR_SUCCESS) {
450 paprerror (r, "apr_os_sock_put: %s", sock_path);
454 /* Register the socket in the pollset. */
455 hval->pollfd.p = hval->pool;
456 hval->pollfd.desc_type = APR_POLL_SOCKET;
457 if (hval->state == guest_state_connecting)
458 hval->pollfd.reqevents = APR_POLLOUT;
460 hval->pollfd.reqevents = APR_POLLIN;
461 hval->pollfd.rtnevents = 0;
462 hval->pollfd.desc.s = hval->aprsock;
464 struct callback_data *callback_data =
465 apr_palloc (hval->pool, sizeof *callback_data);
466 callback_data->callback = guest_event;
467 callback_data->data = hval;
468 hval->pollfd.client_data = callback_data;
470 r = apr_pollset_add (set, &hval->pollfd);
471 if (r != APR_SUCCESS) {
472 paprerror (r, "apr_pollset_add: %s", sock_path);
476 message ("new guest added: %s", hval->name);
480 /* This is called whenever we detect that a guest socket has been
481 * removed from the socket directory. The guest_description parameter
482 * is freed after this call and must not be used again.
485 guest_removed (struct guest_description *hval)
489 message ("guest removed: %s", hval->name);
491 /* Unregister the socket from the pollset. */
492 r = apr_pollset_remove (set, &hval->pollfd);
493 if (r != APR_SUCCESS)
494 paprerror (r, "apr_pollset_remove for %s", hval->name);
496 if (close (hval->sock) == -1)
497 pwarningf ("close: %s", hval->sock_path);
499 /* This also frees hval and all related data. */
500 apr_pool_destroy (hval->pool);
503 /* Forcibly remove a guest, removing the socket from the
504 * socket directory and cleaning up any resources used in
505 * the daemon. The guest_description parameter is freed
506 * after this call and must not be used again.
509 guest_force_close (struct guest_description *hval)
511 debug ("forcibly closing guest: %s", hval->name);
513 apr_hash_set (guests, hval->name, APR_HASH_KEY_STRING, NULL);
514 unlink (hval->sock_path);
515 guest_removed (hval);
518 /* Difference between two timespec structures (r = a - b) */
519 static struct timespec *
520 diff_timespec (struct timespec *r,
521 const struct timespec *a, const struct timespec *b)
523 if (a->tv_nsec - b->tv_nsec < 0) {
524 r->tv_sec = a->tv_sec - b->tv_sec - 1;
525 r->tv_nsec = 1000000000 + a->tv_nsec - b->tv_nsec;
527 r->tv_sec = a->tv_sec - b->tv_sec;
528 r->tv_nsec = a->tv_nsec - b->tv_nsec;
534 /* This is called when there is some event from the guest, eg.
535 * connection finished, read, write or closed.
538 guest_event (const apr_pollfd_t *pollfd, void *hvalv)
540 struct guest_description *hval = hvalv;
541 int err, max, r, extra;
546 #ifdef HAVE_CLOCK_GETTIME
547 clock_gettime (CLOCK_MONOTONIC, &now);
550 gettimeofday (&tv, NULL);
551 now.tv_sec = tv.tv_sec;
552 now.tv_nsec = tv.tv_usec * 1000;
555 /* If the guest keeps doing bad stuff, eventually lose patience with it. */
556 if (hval->penalty >= 100) {
557 error ("%s: guest did too much bad stuff, so we stopped talking to it",
559 guest_force_close (hval);
563 /* Decrement the penalty once a minute, so the guest can recover. */
564 if (hval->penalty > 0) {
565 struct timespec diff;
567 diff_timespec (&diff, &now, &hval->last_penalty_decr);
569 if (diff.tv_sec >= 60) {
571 hval->last_penalty_decr = now;
575 switch (hval->state) {
576 case guest_state_connecting:
577 /* Once we get a write event, we know the socket has
578 * connected, or there is an error.
582 getsockopt (hval->sock, SOL_SOCKET, SO_ERROR, &err, &len);
584 hval->state = guest_state_request;
587 perrorf ("connect: %s", hval->sock_path);
588 guest_force_close (hval);
593 case guest_state_request:
594 /* Reading the guest's request, a single line terminated by \r?\n */
595 max = hval->request_max - hval->request_posn;
596 if (max <= 0) { /* Request too long w/o termination. */
598 hval->request_posn = 0;
601 r = read (hval->sock, &hval->request[hval->request_posn], max);
602 if (r == 0) { /* Socket closed. */
603 guest_force_close (hval);
607 if (errno != EAGAIN && errno != EWOULDBLOCK) {
608 perrorf ("read: %s", hval->sock_path);
609 guest_force_close (hval);
615 hval->request_posn += r;
617 /* Have we got a terminating \n character in the buffer yet? Note
618 * the buffer is not NUL-terminated which is why we use memchr.
621 p = memchr (hval->request, '\n', hval->request_posn);
625 /* Is there more after the \n char? Normal guests shouldn't do
626 * this, but it can be an attempt to reestablish synchronization.
627 * It's documented that we throw away all but the last command sent,
630 extra = &hval->request[hval->request_posn]-(p+1);
633 memmove (hval->request, p+1, extra);
634 hval->request_posn = extra;
638 /* Looks like we've got ourselves a command. Remove trailing
639 * \r?\n char(s) and NUL-terminate the command string.
642 assert (hval->request_posn >= 1);
643 assert (p == &hval->request[hval->request_posn-1]);
644 hval->request_posn--;
647 if (hval->request_posn > 0 && *p == '\r') {
648 hval->request_posn--;
654 execute_command (&now, hval, hval->request);
656 hval->request_posn = 0;
659 case guest_state_reply:
660 /* Keep writing out the reply buffer until we've sent
663 max = hval->reply_size - hval->reply_posn;
665 hval->state = guest_state_request;
669 r = write (hval->sock, &hval->reply[hval->reply_posn], max);
671 if (errno != EAGAIN && errno != EWOULDBLOCK) {
672 perrorf ("write: %s", hval->sock_path);
673 guest_force_close (hval);
679 hval->reply_posn += r;
680 if (hval->reply_posn >= hval->reply_size)
681 hval->state = guest_state_request;
685 case guest_state_dead:
686 /* We shouldn't get an event here. */
690 /* Depending on the (new) state we want to set the
691 * events that we would like poll to give us next time.
693 switch (hval->state) {
694 case guest_state_connecting:
695 hval->pollfd.reqevents = APR_POLLOUT;
697 case guest_state_request:
698 hval->pollfd.reqevents = APR_POLLIN;
700 case guest_state_reply:
701 hval->pollfd.reqevents = APR_POLLOUT;
703 case guest_state_dead:
704 hval->pollfd.reqevents = 0;