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