daemon: gnulib module 'error' is used directly by the daemon.
[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 <unistd.h>
26 #include <errno.h>
27 #include <sys/param.h>          /* defines MIN */
28 #include <sys/select.h>
29 #include <rpc/types.h>
30 #include <rpc/xdr.h>
31
32 #ifdef HAVE_WINDOWS_H
33 #include <windows.h>
34 #endif
35
36 #include "c-ctype.h"
37 #include "ignore-value.h"
38
39 #include "daemon.h"
40 #include "../src/guestfs_protocol.h"
41
42 /* The message currently being processed. */
43 int proc_nr;
44 int serial;
45
46 /* The daemon communications socket. */
47 static int sock;
48
49 void
50 main_loop (int _sock)
51 {
52   XDR xdr;
53   char *buf;
54   char lenbuf[4];
55   uint32_t len;
56   struct guestfs_message_header hdr;
57   struct timeval start_t, end_t;
58   int64_t start_us, end_us, elapsed_us;
59
60   sock = _sock;
61
62   for (;;) {
63     /* Most common errors are leaked memory and leaked file descriptors,
64      * so run this between each command:
65      */
66     if (verbose && 0)
67       ignore_value (system ("ls -l /proc/self/fd"));
68
69     /* Read the length word. */
70     if (xread (sock, lenbuf, 4) == -1)
71       exit (EXIT_FAILURE);
72
73     xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
74     xdr_u_int (&xdr, &len);
75     xdr_destroy (&xdr);
76
77     if (len > GUESTFS_MESSAGE_MAX) {
78       fprintf (stderr, "guestfsd: incoming message is too long (%u bytes)\n",
79                len);
80       exit (EXIT_FAILURE);
81     }
82
83     buf = malloc (len);
84     if (!buf) {
85       reply_with_perror ("malloc");
86       continue;
87     }
88
89     if (xread (sock, buf, len) == -1)
90       exit (EXIT_FAILURE);
91
92 #ifdef ENABLE_PACKET_DUMP
93     if (verbose) {
94       size_t i, j;
95
96       for (i = 0; i < len; i += 16) {
97         printf ("%04zx: ", i);
98         for (j = i; j < MIN (i+16, len); ++j)
99           printf ("%02x ", (unsigned char) buf[j]);
100         for (; j < i+16; ++j)
101           printf ("   ");
102         printf ("|");
103         for (j = i; j < MIN (i+16, len); ++j)
104           if (c_isprint (buf[j]))
105             printf ("%c", buf[j]);
106           else
107             printf (".");
108         for (; j < i+16; ++j)
109           printf (" ");
110         printf ("|\n");
111       }
112     }
113 #endif
114
115     /* In verbose mode, display the time taken to run each command. */
116     if (verbose)
117       gettimeofday (&start_t, NULL);
118
119     /* Decode the message header. */
120     xdrmem_create (&xdr, buf, len, XDR_DECODE);
121     if (!xdr_guestfs_message_header (&xdr, &hdr)) {
122       fprintf (stderr, "guestfsd: could not decode message header\n");
123       exit (EXIT_FAILURE);
124     }
125
126     /* Check the version etc. */
127     if (hdr.prog != GUESTFS_PROGRAM) {
128       reply_with_error ("wrong program (%d)", hdr.prog);
129       goto cont;
130     }
131     if (hdr.vers != GUESTFS_PROTOCOL_VERSION) {
132       reply_with_error ("wrong protocol version (%d)", hdr.vers);
133       goto cont;
134     }
135     if (hdr.direction != GUESTFS_DIRECTION_CALL) {
136       reply_with_error ("unexpected message direction (%d)", hdr.direction);
137       goto cont;
138     }
139     if (hdr.status != GUESTFS_STATUS_OK) {
140       reply_with_error ("unexpected message status (%d)", hdr.status);
141       goto cont;
142     }
143
144     proc_nr = hdr.proc;
145     serial = hdr.serial;
146
147     /* Clear errors before we call the stub functions.  This is just
148      * to ensure that we can accurately report errors in cases where
149      * error handling paths don't set errno correctly.
150      */
151     errno = 0;
152 #ifdef WIN32
153     SetLastError (0);
154     WSASetLastError (0);
155 #endif
156
157     /* Now start to process this message. */
158     dispatch_incoming_message (&xdr);
159     /* Note that dispatch_incoming_message will also send a reply. */
160
161     /* In verbose mode, display the time taken to run each command. */
162     if (verbose) {
163       gettimeofday (&end_t, NULL);
164
165       start_us = (int64_t) start_t.tv_sec * 1000000 + start_t.tv_usec;
166       end_us = (int64_t) end_t.tv_sec * 1000000 + end_t.tv_usec;
167       elapsed_us = end_us - start_us;
168       fprintf (stderr, "proc %d (%s) took %d.%02d seconds\n",
169                proc_nr,
170                proc_nr >= 0 && proc_nr < GUESTFS_PROC_NR_PROCS
171                ? function_names[proc_nr] : "UNKNOWN PROCEDURE",
172                (int) (elapsed_us / 1000000),
173                (int) ((elapsed_us / 10000) % 100));
174     }
175
176   cont:
177     xdr_destroy (&xdr);
178     free (buf);
179   }
180 }
181
182 static void send_error (const char *msg);
183
184 void
185 reply_with_error (const char *fs, ...)
186 {
187   char err[GUESTFS_ERROR_LEN];
188   va_list args;
189
190   va_start (args, fs);
191   vsnprintf (err, sizeof err, fs, args);
192   va_end (args);
193
194   send_error (err);
195 }
196
197 void
198 reply_with_perror_errno (int err, const char *fs, ...)
199 {
200   char buf1[GUESTFS_ERROR_LEN];
201   char buf2[GUESTFS_ERROR_LEN];
202   va_list args;
203
204   va_start (args, fs);
205   vsnprintf (buf1, sizeof buf1, fs, args);
206   va_end (args);
207
208   snprintf (buf2, sizeof buf2, "%s: %s", buf1, strerror (err));
209
210   send_error (buf2);
211 }
212
213 static void
214 send_error (const char *msg)
215 {
216   XDR xdr;
217   char buf[GUESTFS_ERROR_LEN + 200];
218   char lenbuf[4];
219   struct guestfs_message_header hdr;
220   struct guestfs_message_error err;
221   unsigned len;
222
223   fprintf (stderr, "guestfsd: error: %s\n", msg);
224
225   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
226
227   hdr.prog = GUESTFS_PROGRAM;
228   hdr.vers = GUESTFS_PROTOCOL_VERSION;
229   hdr.direction = GUESTFS_DIRECTION_REPLY;
230   hdr.status = GUESTFS_STATUS_ERROR;
231   hdr.proc = proc_nr;
232   hdr.serial = serial;
233
234   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
235     fprintf (stderr, "guestfsd: failed to encode error message header\n");
236     exit (EXIT_FAILURE);
237   }
238
239   err.error_message = (char *) msg;
240
241   if (!xdr_guestfs_message_error (&xdr, &err)) {
242     fprintf (stderr, "guestfsd: failed to encode error message body\n");
243     exit (EXIT_FAILURE);
244   }
245
246   len = xdr_getpos (&xdr);
247   xdr_destroy (&xdr);
248
249   xdrmem_create (&xdr, lenbuf, 4, XDR_ENCODE);
250   xdr_u_int (&xdr, &len);
251   xdr_destroy (&xdr);
252
253   if (xwrite (sock, lenbuf, 4) == -1) {
254     fprintf (stderr, "xwrite failed\n");
255     exit (EXIT_FAILURE);
256   }
257   if (xwrite (sock, buf, len) == -1) {
258     fprintf (stderr, "xwrite failed\n");
259     exit (EXIT_FAILURE);
260   }
261 }
262
263 void
264 reply (xdrproc_t xdrp, char *ret)
265 {
266   XDR xdr;
267   char buf[GUESTFS_MESSAGE_MAX];
268   char lenbuf[4];
269   struct guestfs_message_header hdr;
270   unsigned len;
271
272   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
273
274   hdr.prog = GUESTFS_PROGRAM;
275   hdr.vers = GUESTFS_PROTOCOL_VERSION;
276   hdr.direction = GUESTFS_DIRECTION_REPLY;
277   hdr.status = GUESTFS_STATUS_OK;
278   hdr.proc = proc_nr;
279   hdr.serial = serial;
280
281   if (!xdr_guestfs_message_header (&xdr, &hdr)) {
282     fprintf (stderr, "guestfsd: failed to encode reply header\n");
283     exit (EXIT_FAILURE);
284   }
285
286   if (xdrp) {
287     /* This can fail if the reply body is too large, for example
288      * if it exceeds the maximum message size.  In that case
289      * we want to return an error message instead. (RHBZ#509597).
290      */
291     if (!(*xdrp) (&xdr, ret)) {
292       reply_with_error ("guestfsd: failed to encode reply body\n(maybe the reply exceeds the maximum message size in the protocol?)");
293       xdr_destroy (&xdr);
294       return;
295     }
296   }
297
298   len = xdr_getpos (&xdr);
299   xdr_destroy (&xdr);
300
301   xdrmem_create (&xdr, lenbuf, 4, XDR_ENCODE);
302   xdr_u_int (&xdr, &len);
303   xdr_destroy (&xdr);
304
305   if (xwrite (sock, lenbuf, 4) == -1) {
306     fprintf (stderr, "xwrite failed\n");
307     exit (EXIT_FAILURE);
308   }
309   if (xwrite (sock, buf, len) == -1) {
310     fprintf (stderr, "xwrite failed\n");
311     exit (EXIT_FAILURE);
312   }
313 }
314
315 /* Receive file chunks, repeatedly calling 'cb'. */
316 int
317 receive_file (receive_cb cb, void *opaque)
318 {
319   guestfs_chunk chunk;
320   char lenbuf[4];
321   char *buf;
322   XDR xdr;
323   int r;
324   uint32_t len;
325
326   for (;;) {
327     if (verbose)
328       fprintf (stderr, "receive_file: reading length word\n");
329
330     /* Read the length word. */
331     if (xread (sock, lenbuf, 4) == -1)
332       exit (EXIT_FAILURE);
333
334     xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
335     xdr_u_int (&xdr, &len);
336     xdr_destroy (&xdr);
337
338     if (len == GUESTFS_CANCEL_FLAG)
339       continue;                 /* Just ignore it. */
340
341     if (len > GUESTFS_MESSAGE_MAX) {
342       fprintf (stderr, "guestfsd: incoming message is too long (%u bytes)\n",
343                len);
344       exit (EXIT_FAILURE);
345     }
346
347     buf = malloc (len);
348     if (!buf) {
349       perror ("malloc");
350       return -1;
351     }
352
353     if (xread (sock, buf, len) == -1)
354       exit (EXIT_FAILURE);
355
356     xdrmem_create (&xdr, buf, len, XDR_DECODE);
357     memset (&chunk, 0, sizeof chunk);
358     if (!xdr_guestfs_chunk (&xdr, &chunk)) {
359       xdr_destroy (&xdr);
360       free (buf);
361       return -1;
362     }
363     xdr_destroy (&xdr);
364     free (buf);
365
366     if (verbose)
367       fprintf (stderr, "receive_file: got chunk: cancel = %d, len = %d, buf = %p\n",
368                chunk.cancel, chunk.data.data_len, chunk.data.data_val);
369
370     if (chunk.cancel) {
371       if (verbose)
372         fprintf (stderr, "receive_file: received cancellation from library\n");
373       xdr_free ((xdrproc_t) xdr_guestfs_chunk, (char *) &chunk);
374       return -2;
375     }
376     if (chunk.data.data_len == 0) {
377       if (verbose)
378         fprintf (stderr, "receive_file: end of file, leaving function\n");
379       xdr_free ((xdrproc_t) xdr_guestfs_chunk, (char *) &chunk);
380       return 0;                 /* end of file */
381     }
382
383     if (cb)
384       r = cb (opaque, chunk.data.data_val, chunk.data.data_len);
385     else
386       r = 0;
387
388     xdr_free ((xdrproc_t) xdr_guestfs_chunk, (char *) &chunk);
389     if (r == -1) {              /* write error */
390       if (verbose)
391         fprintf (stderr, "receive_file: write error\n");
392       return -1;
393     }
394   }
395 }
396
397 /* Send a cancellation flag back to the library. */
398 void
399 cancel_receive (void)
400 {
401   XDR xdr;
402   char fbuf[4];
403   uint32_t flag = GUESTFS_CANCEL_FLAG;
404
405   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
406   xdr_u_int (&xdr, &flag);
407   xdr_destroy (&xdr);
408
409   if (xwrite (sock, fbuf, sizeof fbuf) == -1) {
410     perror ("write to socket");
411     return;
412   }
413
414   /* Keep receiving chunks and discarding, until library sees cancel. */
415   (void) receive_file (NULL, NULL);
416 }
417
418 static int check_for_library_cancellation (void);
419 static int send_chunk (const guestfs_chunk *);
420
421 /* Also check if the library sends us a cancellation message. */
422 int
423 send_file_write (const void *buf, int len)
424 {
425   guestfs_chunk chunk;
426   int cancel;
427
428   if (len > GUESTFS_MAX_CHUNK_SIZE) {
429     fprintf (stderr, "send_file_write: len (%d) > GUESTFS_MAX_CHUNK_SIZE (%d)\n",
430              len, GUESTFS_MAX_CHUNK_SIZE);
431     return -1;
432   }
433
434   cancel = check_for_library_cancellation ();
435
436   if (cancel) {
437     chunk.cancel = 1;
438     chunk.data.data_len = 0;
439     chunk.data.data_val = NULL;
440   } else {
441     chunk.cancel = 0;
442     chunk.data.data_len = len;
443     chunk.data.data_val = (char *) buf;
444   }
445
446   if (send_chunk (&chunk) == -1)
447     return -1;
448
449   if (cancel) return -2;
450   return 0;
451 }
452
453 static int
454 check_for_library_cancellation (void)
455 {
456   fd_set rset;
457   struct timeval tv;
458   int r;
459   char buf[4];
460   uint32_t flag;
461   XDR xdr;
462
463   FD_ZERO (&rset);
464   FD_SET (sock, &rset);
465   tv.tv_sec = 0;
466   tv.tv_usec = 0;
467   r = select (sock+1, &rset, NULL, NULL, &tv);
468   if (r == -1) {
469     perror ("select");
470     return 0;
471   }
472   if (r == 0)
473     return 0;
474
475   /* Read the message from the daemon. */
476   r = xread (sock, buf, sizeof buf);
477   if (r == -1)
478     return 0;
479
480   xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
481   xdr_u_int (&xdr, &flag);
482   xdr_destroy (&xdr);
483
484   if (flag != GUESTFS_CANCEL_FLAG) {
485     fprintf (stderr, "check_for_library_cancellation: read 0x%x from library, expected 0x%x\n",
486              flag, GUESTFS_CANCEL_FLAG);
487     return 0;
488   }
489
490   return 1;
491 }
492
493 int
494 send_file_end (int cancel)
495 {
496   guestfs_chunk chunk;
497
498   chunk.cancel = cancel;
499   chunk.data.data_len = 0;
500   chunk.data.data_val = NULL;
501   return send_chunk (&chunk);
502 }
503
504 static int
505 send_chunk (const guestfs_chunk *chunk)
506 {
507   char buf[GUESTFS_MAX_CHUNK_SIZE + 48];
508   char lenbuf[4];
509   XDR xdr;
510   uint32_t len;
511
512   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
513   if (!xdr_guestfs_chunk (&xdr, (guestfs_chunk *) chunk)) {
514     fprintf (stderr, "send_chunk: failed to encode chunk\n");
515     xdr_destroy (&xdr);
516     return -1;
517   }
518
519   len = xdr_getpos (&xdr);
520   xdr_destroy (&xdr);
521
522   xdrmem_create (&xdr, lenbuf, 4, XDR_ENCODE);
523   xdr_u_int (&xdr, &len);
524   xdr_destroy (&xdr);
525
526   int err = (xwrite (sock, lenbuf, 4) == 0
527              && xwrite (sock, buf, len) == 0 ? 0 : -1);
528   if (err) {
529     fprintf (stderr, "send_chunk: write failed\n");
530     exit (EXIT_FAILURE);
531   }
532
533   return err;
534 }