daemon: Remove -f (don't fork) option.
[libguestfs.git] / daemon / proto.c
1 /* libguestfs - the guestfsd daemon
2  * Copyright (C) 2009 Red Hat Inc.
3  *
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.
8  *
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.
13  *
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.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <string.h>
25 #include <inttypes.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <sys/param.h>          /* defines MIN */
29 #include <sys/select.h>
30 #include <sys/time.h>
31 #include <rpc/types.h>
32 #include <rpc/xdr.h>
33
34 #ifdef HAVE_WINDOWS_H
35 #include <windows.h>
36 #endif
37
38 #include "c-ctype.h"
39 #include "ignore-value.h"
40
41 #include "daemon.h"
42 #include "guestfs_protocol.h"
43 #include "errnostring.h"
44
45 /* The message currently being processed. */
46 int proc_nr;
47 int serial;
48
49 /* Hint for implementing progress messages for uploaded/incoming data.
50  * The caller sets this to a value > 0 if it knows or can estimate how
51  * much data will be sent (this is not always known, eg. for uploads
52  * coming from a pipe).  If this is known then we can emit progress
53  * messages as we write the data.
54  */
55 uint64_t progress_hint;
56
57 /* Optional arguments bitmask.  Caller sets this to indicate which
58  * optional arguments in the guestfs_<foo>_args structure are
59  * meaningful.  Optional arguments not covered by the bitmask are set
60  * to arbitrary values and the daemon should ignore them.  If the
61  * bitmask has bits set that the daemon doesn't understand, then the
62  * whole call is rejected early in processing.
63  */
64 uint64_t optargs_bitmask;
65
66 /* Time at which we received the current request. */
67 static struct timeval start_t;
68
69 /* Time at which the last progress notification was sent. */
70 static struct timeval last_progress_t;
71
72 /* Counts the number of progress notifications sent during this call. */
73 static int count_progress;
74
75 /* The daemon communications socket. */
76 static int sock;
77
78 void
79 main_loop (int _sock)
80 {
81   XDR xdr;
82   char *buf;
83   char lenbuf[4];
84   uint32_t len;
85   struct guestfs_message_header hdr;
86
87   sock = _sock;
88
89   for (;;) {
90     /* Most common errors are leaked memory and leaked file descriptors,
91      * so run this between each command:
92      */
93     if (verbose && 0)
94       ignore_value (system ("ls -l /proc/self/fd"));
95
96     /* Read the length word. */
97     if (xread (sock, lenbuf, 4) == -1)
98       exit (EXIT_FAILURE);
99
100     xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
101     xdr_u_int (&xdr, &len);
102     xdr_destroy (&xdr);
103
104     if (len > GUESTFS_MESSAGE_MAX) {
105       fprintf (stderr, "guestfsd: incoming message is too long (%u bytes)\n",
106                len);
107       exit (EXIT_FAILURE);
108     }
109
110     buf = malloc (len);
111     if (!buf) {
112       reply_with_perror ("malloc");
113       continue;
114     }
115
116     if (xread (sock, buf, len) == -1)
117       exit (EXIT_FAILURE);
118
119 #ifdef ENABLE_PACKET_DUMP
120     if (verbose) {
121       size_t i, j;
122
123       for (i = 0; i < len; i += 16) {
124         printf ("%04zx: ", i);
125         for (j = i; j < MIN (i+16, len); ++j)
126           printf ("%02x ", (unsigned char) buf[j]);
127         for (; j < i+16; ++j)
128           printf ("   ");
129         printf ("|");
130         for (j = i; j < MIN (i+16, len); ++j)
131           if (c_isprint (buf[j]))
132             printf ("%c", buf[j]);
133           else
134             printf (".");
135         for (; j < i+16; ++j)
136           printf (" ");
137         printf ("|\n");
138       }
139     }
140 #endif
141
142     gettimeofday (&start_t, NULL);
143     last_progress_t = start_t;
144     count_progress = 0;
145
146     /* Decode the message header. */
147     xdrmem_create (&xdr, buf, len, XDR_DECODE);
148     if (!xdr_guestfs_message_header (&xdr, &hdr)) {
149       fprintf (stderr, "guestfsd: could not decode message header\n");
150       exit (EXIT_FAILURE);
151     }
152
153     /* Check the version etc. */
154     if (hdr.prog != GUESTFS_PROGRAM) {
155       reply_with_error ("wrong program (%d)", hdr.prog);
156       goto cont;
157     }
158     if (hdr.vers != GUESTFS_PROTOCOL_VERSION) {
159       reply_with_error ("wrong protocol version (%d)", hdr.vers);
160       goto cont;
161     }
162     if (hdr.direction != GUESTFS_DIRECTION_CALL) {
163       reply_with_error ("unexpected message direction (%d)", hdr.direction);
164       goto cont;
165     }
166     if (hdr.status != GUESTFS_STATUS_OK) {
167       reply_with_error ("unexpected message status (%d)", hdr.status);
168       goto cont;
169     }
170
171     proc_nr = hdr.proc;
172     serial = hdr.serial;
173     progress_hint = hdr.progress_hint;
174     optargs_bitmask = hdr.optargs_bitmask;
175
176     /* Clear errors before we call the stub functions.  This is just
177      * to ensure that we can accurately report errors in cases where
178      * error handling paths don't set errno correctly.
179      */
180     errno = 0;
181 #ifdef WIN32
182     SetLastError (0);
183     WSASetLastError (0);
184 #endif
185
186     /* Now start to process this message. */
187     dispatch_incoming_message (&xdr);
188     /* Note that dispatch_incoming_message will also send a reply. */
189
190     /* In verbose mode, display the time taken to run each command. */
191     if (verbose) {
192       struct timeval end_t;
193       gettimeofday (&end_t, NULL);
194
195       int64_t start_us, end_us, elapsed_us;
196       start_us = (int64_t) start_t.tv_sec * 1000000 + start_t.tv_usec;
197       end_us = (int64_t) end_t.tv_sec * 1000000 + end_t.tv_usec;
198       elapsed_us = end_us - start_us;
199
200       fprintf (stderr, "proc %d (%s) took %d.%02d seconds\n",
201                proc_nr,
202                proc_nr >= 0 && proc_nr < GUESTFS_PROC_NR_PROCS
203                ? function_names[proc_nr] : "UNKNOWN PROCEDURE",
204                (int) (elapsed_us / 1000000),
205                (int) ((elapsed_us / 10000) % 100));
206     }
207
208   cont:
209     xdr_destroy (&xdr);
210     free (buf);
211   }
212 }
213
214 static void send_error (int errnum, const char *msg);
215
216 void
217 reply_with_error (const char *fs, ...)
218 {
219   char err[GUESTFS_ERROR_LEN];
220   va_list args;
221
222   va_start (args, fs);
223   vsnprintf (err, sizeof err, fs, args);
224   va_end (args);
225
226   send_error (0, err);
227 }
228
229 void
230 reply_with_perror_errno (int err, const char *fs, ...)
231 {
232   char buf1[GUESTFS_ERROR_LEN];
233   char buf2[GUESTFS_ERROR_LEN];
234   va_list args;
235
236   va_start (args, fs);
237   vsnprintf (buf1, sizeof buf1, fs, args);
238   va_end (args);
239
240   snprintf (buf2, sizeof buf2, "%s: %s", buf1, strerror (err));
241
242   send_error (err, buf2);
243 }
244
245 static void
246 send_error (int errnum, const char *msg)
247 {
248   XDR xdr;
249   char buf[GUESTFS_ERROR_LEN + 200];
250   char lenbuf[4];
251   struct guestfs_message_header hdr;
252   struct guestfs_message_error err;
253   unsigned len;
254
255   fprintf (stderr, "guestfsd: error: %s\n", msg);
256
257   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
258
259   hdr.prog = GUESTFS_PROGRAM;
260   hdr.vers = GUESTFS_PROTOCOL_VERSION;
261   hdr.direction = GUESTFS_DIRECTION_REPLY;
262   hdr.status = GUESTFS_STATUS_ERROR;
263   hdr.proc = proc_nr;
264   hdr.serial = serial;
265
266   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
267     fprintf (stderr, "guestfsd: failed to encode error message header\n");
268     exit (EXIT_FAILURE);
269   }
270
271   /* These strings are not going to be freed.  We just cast them
272    * to (char *) because they are defined that way in the XDR structs.
273    */
274   err.errno_string =
275     (char *) (errnum > 0 ? guestfs___errno_to_string (errnum) : "");
276   err.error_message = (char *) msg;
277
278   if (!xdr_guestfs_message_error (&xdr, &err)) {
279     fprintf (stderr, "guestfsd: failed to encode error message body\n");
280     exit (EXIT_FAILURE);
281   }
282
283   len = xdr_getpos (&xdr);
284   xdr_destroy (&xdr);
285
286   xdrmem_create (&xdr, lenbuf, 4, XDR_ENCODE);
287   xdr_u_int (&xdr, &len);
288   xdr_destroy (&xdr);
289
290   if (xwrite (sock, lenbuf, 4) == -1) {
291     fprintf (stderr, "xwrite failed\n");
292     exit (EXIT_FAILURE);
293   }
294   if (xwrite (sock, buf, len) == -1) {
295     fprintf (stderr, "xwrite failed\n");
296     exit (EXIT_FAILURE);
297   }
298 }
299
300 void
301 reply (xdrproc_t xdrp, char *ret)
302 {
303   XDR xdr;
304   char buf[GUESTFS_MESSAGE_MAX];
305   char lenbuf[4];
306   struct guestfs_message_header hdr;
307   unsigned len;
308
309   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
310
311   hdr.prog = GUESTFS_PROGRAM;
312   hdr.vers = GUESTFS_PROTOCOL_VERSION;
313   hdr.direction = GUESTFS_DIRECTION_REPLY;
314   hdr.status = GUESTFS_STATUS_OK;
315   hdr.proc = proc_nr;
316   hdr.serial = serial;
317
318   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
319     fprintf (stderr, "guestfsd: failed to encode reply header\n");
320     exit (EXIT_FAILURE);
321   }
322
323   if (xdrp) {
324     /* This can fail if the reply body is too large, for example
325      * if it exceeds the maximum message size.  In that case
326      * we want to return an error message instead. (RHBZ#509597).
327      */
328     if (!(*xdrp) (&xdr, ret)) {
329       reply_with_error ("guestfsd: failed to encode reply body\n(maybe the reply exceeds the maximum message size in the protocol?)");
330       xdr_destroy (&xdr);
331       return;
332     }
333   }
334
335   len = xdr_getpos (&xdr);
336   xdr_destroy (&xdr);
337
338   xdrmem_create (&xdr, lenbuf, 4, XDR_ENCODE);
339   xdr_u_int (&xdr, &len);
340   xdr_destroy (&xdr);
341
342   if (xwrite (sock, lenbuf, 4) == -1) {
343     fprintf (stderr, "xwrite failed\n");
344     exit (EXIT_FAILURE);
345   }
346   if (xwrite (sock, buf, len) == -1) {
347     fprintf (stderr, "xwrite failed\n");
348     exit (EXIT_FAILURE);
349   }
350 }
351
352 /* Receive file chunks, repeatedly calling 'cb'. */
353 int
354 receive_file (receive_cb cb, void *opaque)
355 {
356   guestfs_chunk chunk;
357   char lenbuf[4];
358   char *buf;
359   XDR xdr;
360   int r;
361   uint32_t len;
362
363   for (;;) {
364     if (verbose)
365       fprintf (stderr, "receive_file: reading length word\n");
366
367     /* Read the length word. */
368     if (xread (sock, lenbuf, 4) == -1)
369       exit (EXIT_FAILURE);
370
371     xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
372     xdr_u_int (&xdr, &len);
373     xdr_destroy (&xdr);
374
375     if (len == GUESTFS_CANCEL_FLAG)
376       continue;                 /* Just ignore it. */
377
378     if (len > GUESTFS_MESSAGE_MAX) {
379       fprintf (stderr, "guestfsd: incoming message is too long (%u bytes)\n",
380                len);
381       exit (EXIT_FAILURE);
382     }
383
384     buf = malloc (len);
385     if (!buf) {
386       perror ("malloc");
387       return -1;
388     }
389
390     if (xread (sock, buf, len) == -1)
391       exit (EXIT_FAILURE);
392
393     xdrmem_create (&xdr, buf, len, XDR_DECODE);
394     memset (&chunk, 0, sizeof chunk);
395     if (!xdr_guestfs_chunk (&xdr, &chunk)) {
396       xdr_destroy (&xdr);
397       free (buf);
398       return -1;
399     }
400     xdr_destroy (&xdr);
401     free (buf);
402
403     if (verbose)
404       fprintf (stderr, "receive_file: got chunk: cancel = %d, len = %d, buf = %p\n",
405                chunk.cancel, chunk.data.data_len, chunk.data.data_val);
406
407     if (chunk.cancel) {
408       if (verbose)
409         fprintf (stderr, "receive_file: received cancellation from library\n");
410       xdr_free ((xdrproc_t) xdr_guestfs_chunk, (char *) &chunk);
411       return -2;
412     }
413     if (chunk.data.data_len == 0) {
414       if (verbose)
415         fprintf (stderr, "receive_file: end of file, leaving function\n");
416       xdr_free ((xdrproc_t) xdr_guestfs_chunk, (char *) &chunk);
417       return 0;                 /* end of file */
418     }
419
420     /* Note that the callback can generate progress messages. */
421     if (cb)
422       r = cb (opaque, chunk.data.data_val, chunk.data.data_len);
423     else
424       r = 0;
425
426     xdr_free ((xdrproc_t) xdr_guestfs_chunk, (char *) &chunk);
427     if (r == -1) {              /* write error */
428       if (verbose)
429         fprintf (stderr, "receive_file: write error\n");
430       return -1;
431     }
432   }
433 }
434
435 /* Send a cancellation flag back to the library. */
436 int
437 cancel_receive (void)
438 {
439   XDR xdr;
440   char fbuf[4];
441   uint32_t flag = GUESTFS_CANCEL_FLAG;
442
443   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
444   xdr_u_int (&xdr, &flag);
445   xdr_destroy (&xdr);
446
447   if (xwrite (sock, fbuf, sizeof fbuf) == -1) {
448     perror ("write to socket");
449     return -1;
450   }
451
452   /* Keep receiving chunks and discarding, until library sees cancel. */
453   return receive_file (NULL, NULL);
454 }
455
456 static int check_for_library_cancellation (void);
457 static int send_chunk (const guestfs_chunk *);
458
459 /* Also check if the library sends us a cancellation message. */
460 int
461 send_file_write (const void *buf, int len)
462 {
463   guestfs_chunk chunk;
464   int cancel;
465
466   if (len > GUESTFS_MAX_CHUNK_SIZE) {
467     fprintf (stderr, "send_file_write: len (%d) > GUESTFS_MAX_CHUNK_SIZE (%d)\n",
468              len, GUESTFS_MAX_CHUNK_SIZE);
469     return -1;
470   }
471
472   cancel = check_for_library_cancellation ();
473
474   if (cancel) {
475     chunk.cancel = 1;
476     chunk.data.data_len = 0;
477     chunk.data.data_val = NULL;
478   } else {
479     chunk.cancel = 0;
480     chunk.data.data_len = len;
481     chunk.data.data_val = (char *) buf;
482   }
483
484   if (send_chunk (&chunk) == -1)
485     return -1;
486
487   if (cancel) return -2;
488   return 0;
489 }
490
491 static int
492 check_for_library_cancellation (void)
493 {
494   fd_set rset;
495   struct timeval tv;
496   int r;
497   char buf[4];
498   uint32_t flag;
499   XDR xdr;
500
501   FD_ZERO (&rset);
502   FD_SET (sock, &rset);
503   tv.tv_sec = 0;
504   tv.tv_usec = 0;
505   r = select (sock+1, &rset, NULL, NULL, &tv);
506   if (r == -1) {
507     perror ("select");
508     return 0;
509   }
510   if (r == 0)
511     return 0;
512
513   /* Read the message from the daemon. */
514   r = xread (sock, buf, sizeof buf);
515   if (r == -1)
516     return 0;
517
518   xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
519   xdr_u_int (&xdr, &flag);
520   xdr_destroy (&xdr);
521
522   if (flag != GUESTFS_CANCEL_FLAG) {
523     fprintf (stderr, "check_for_library_cancellation: read 0x%x from library, expected 0x%x\n",
524              flag, GUESTFS_CANCEL_FLAG);
525     return 0;
526   }
527
528   return 1;
529 }
530
531 int
532 send_file_end (int cancel)
533 {
534   guestfs_chunk chunk;
535
536   chunk.cancel = cancel;
537   chunk.data.data_len = 0;
538   chunk.data.data_val = NULL;
539   return send_chunk (&chunk);
540 }
541
542 static int
543 send_chunk (const guestfs_chunk *chunk)
544 {
545   char buf[GUESTFS_MAX_CHUNK_SIZE + 48];
546   char lenbuf[4];
547   XDR xdr;
548   uint32_t len;
549
550   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
551   if (!xdr_guestfs_chunk (&xdr, (guestfs_chunk *) chunk)) {
552     fprintf (stderr, "send_chunk: failed to encode chunk\n");
553     xdr_destroy (&xdr);
554     return -1;
555   }
556
557   len = xdr_getpos (&xdr);
558   xdr_destroy (&xdr);
559
560   xdrmem_create (&xdr, lenbuf, 4, XDR_ENCODE);
561   xdr_u_int (&xdr, &len);
562   xdr_destroy (&xdr);
563
564   int err = (xwrite (sock, lenbuf, 4) == 0
565              && xwrite (sock, buf, len) == 0 ? 0 : -1);
566   if (err) {
567     fprintf (stderr, "send_chunk: write failed\n");
568     exit (EXIT_FAILURE);
569   }
570
571   return err;
572 }
573
574 /* Initial delay before sending notification messages, and
575  * the period at which we send them thereafter.  These times
576  * are in microseconds.
577  */
578 #define NOTIFICATION_INITIAL_DELAY 2000000
579 #define NOTIFICATION_PERIOD         333333
580
581 void
582 notify_progress (uint64_t position, uint64_t total)
583 {
584   struct timeval now_t;
585   gettimeofday (&now_t, NULL);
586
587   /* Always send a notification at 100%.  This simplifies callers by
588    * allowing them to 'finish' the progress bar at 100% without
589    * needing special code.
590    */
591   if (count_progress > 0 && position == total)
592     goto send;
593
594   /* Calculate time in microseconds since the last progress message
595    * was sent out (or since the start of the call).
596    */
597   int64_t last_us, now_us, elapsed_us;
598   last_us =
599     (int64_t) last_progress_t.tv_sec * 1000000 + last_progress_t.tv_usec;
600   now_us = (int64_t) now_t.tv_sec * 1000000 + now_t.tv_usec;
601   elapsed_us = now_us - last_us;
602
603   /* Rate limit. */
604   if ((count_progress == 0 && elapsed_us < NOTIFICATION_INITIAL_DELAY) ||
605       (count_progress > 0 && elapsed_us < NOTIFICATION_PERIOD))
606     return;
607
608  send:
609   /* We're going to send a message now ... */
610   count_progress++;
611   last_progress_t = now_t;
612
613   /* Send the header word. */
614   XDR xdr;
615   char buf[128];
616   uint32_t i = GUESTFS_PROGRESS_FLAG;
617   size_t len;
618   xdrmem_create (&xdr, buf, 4, XDR_ENCODE);
619   xdr_u_int (&xdr, &i);
620   xdr_destroy (&xdr);
621
622   if (xwrite (sock, buf, 4) == -1) {
623     fprintf (stderr, "xwrite failed\n");
624     exit (EXIT_FAILURE);
625   }
626
627   guestfs_progress message = {
628     .proc = proc_nr,
629     .serial = serial,
630     .position = position,
631     .total = total,
632   };
633
634   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
635   if (!xdr_guestfs_progress (&xdr, &message)) {
636     fprintf (stderr, "xdr_guestfs_progress: failed to encode message\n");
637     xdr_destroy (&xdr);
638     return;
639   }
640   len = xdr_getpos (&xdr);
641   xdr_destroy (&xdr);
642
643   if (xwrite (sock, buf, len) == -1) {
644     fprintf (stderr, "xwrite failed\n");
645     exit (EXIT_FAILURE);
646   }
647 }