hivex: Reimplement hivexget as a simple shell script.
[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_perror ("guestfsd: failed to encode reply body\n");
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     /* Read the length word. */
328     if (xread (sock, lenbuf, 4) == -1)
329       exit (EXIT_FAILURE);
330
331     xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
332     xdr_u_int (&xdr, &len);
333     xdr_destroy (&xdr);
334
335     if (len == GUESTFS_CANCEL_FLAG)
336       continue;                 /* Just ignore it. */
337
338     if (len > GUESTFS_MESSAGE_MAX) {
339       fprintf (stderr, "guestfsd: incoming message is too long (%u bytes)\n",
340                len);
341       exit (EXIT_FAILURE);
342     }
343
344     buf = malloc (len);
345     if (!buf) {
346       perror ("malloc");
347       return -1;
348     }
349
350     if (xread (sock, buf, len) == -1)
351       exit (EXIT_FAILURE);
352
353     xdrmem_create (&xdr, buf, len, XDR_DECODE);
354     memset (&chunk, 0, sizeof chunk);
355     if (!xdr_guestfs_chunk (&xdr, &chunk)) {
356       xdr_destroy (&xdr);
357       free (buf);
358       return -1;
359     }
360     xdr_destroy (&xdr);
361     free (buf);
362
363     if (verbose)
364       printf ("receive_file: got chunk: cancel = %d, len = %d, buf = %p\n",
365               chunk.cancel, chunk.data.data_len, chunk.data.data_val);
366
367     if (chunk.cancel) {
368       fprintf (stderr, "receive_file: received cancellation from library\n");
369       xdr_free ((xdrproc_t) xdr_guestfs_chunk, (char *) &chunk);
370       return -2;
371     }
372     if (chunk.data.data_len == 0) {
373       xdr_free ((xdrproc_t) xdr_guestfs_chunk, (char *) &chunk);
374       return 0;                 /* end of file */
375     }
376
377     if (cb)
378       r = cb (opaque, chunk.data.data_val, chunk.data.data_len);
379     else
380       r = 0;
381
382     xdr_free ((xdrproc_t) xdr_guestfs_chunk, (char *) &chunk);
383     if (r == -1)                /* write error */
384       return -1;
385   }
386 }
387
388 /* Send a cancellation flag back to the library. */
389 void
390 cancel_receive (void)
391 {
392   XDR xdr;
393   char fbuf[4];
394   uint32_t flag = GUESTFS_CANCEL_FLAG;
395
396   xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE);
397   xdr_u_int (&xdr, &flag);
398   xdr_destroy (&xdr);
399
400   if (xwrite (sock, fbuf, sizeof fbuf) == -1) {
401     perror ("write to socket");
402     return;
403   }
404
405   /* Keep receiving chunks and discarding, until library sees cancel. */
406   (void) receive_file (NULL, NULL);
407 }
408
409 static int check_for_library_cancellation (void);
410 static int send_chunk (const guestfs_chunk *);
411
412 /* Also check if the library sends us a cancellation message. */
413 int
414 send_file_write (const void *buf, int len)
415 {
416   guestfs_chunk chunk;
417   int cancel;
418
419   if (len > GUESTFS_MAX_CHUNK_SIZE) {
420     fprintf (stderr, "send_file_write: len (%d) > GUESTFS_MAX_CHUNK_SIZE (%d)\n",
421              len, GUESTFS_MAX_CHUNK_SIZE);
422     return -1;
423   }
424
425   cancel = check_for_library_cancellation ();
426
427   if (cancel) {
428     chunk.cancel = 1;
429     chunk.data.data_len = 0;
430     chunk.data.data_val = NULL;
431   } else {
432     chunk.cancel = 0;
433     chunk.data.data_len = len;
434     chunk.data.data_val = (char *) buf;
435   }
436
437   if (send_chunk (&chunk) == -1)
438     return -1;
439
440   if (cancel) return -2;
441   return 0;
442 }
443
444 static int
445 check_for_library_cancellation (void)
446 {
447   fd_set rset;
448   struct timeval tv;
449   int r;
450   char buf[4];
451   uint32_t flag;
452   XDR xdr;
453
454   FD_ZERO (&rset);
455   FD_SET (sock, &rset);
456   tv.tv_sec = 0;
457   tv.tv_usec = 0;
458   r = select (sock+1, &rset, NULL, NULL, &tv);
459   if (r == -1) {
460     perror ("select");
461     return 0;
462   }
463   if (r == 0)
464     return 0;
465
466   /* Read the message from the daemon. */
467   r = xread (sock, buf, sizeof buf);
468   if (r == -1)
469     return 0;
470
471   xdrmem_create (&xdr, buf, sizeof buf, XDR_DECODE);
472   xdr_u_int (&xdr, &flag);
473   xdr_destroy (&xdr);
474
475   if (flag != GUESTFS_CANCEL_FLAG) {
476     fprintf (stderr, "check_for_library_cancellation: read 0x%x from library, expected 0x%x\n",
477              flag, GUESTFS_CANCEL_FLAG);
478     return 0;
479   }
480
481   return 1;
482 }
483
484 int
485 send_file_end (int cancel)
486 {
487   guestfs_chunk chunk;
488
489   chunk.cancel = cancel;
490   chunk.data.data_len = 0;
491   chunk.data.data_val = NULL;
492   return send_chunk (&chunk);
493 }
494
495 static int
496 send_chunk (const guestfs_chunk *chunk)
497 {
498   char buf[GUESTFS_MAX_CHUNK_SIZE + 48];
499   char lenbuf[4];
500   XDR xdr;
501   uint32_t len;
502
503   xdrmem_create (&xdr, buf, sizeof buf, XDR_ENCODE);
504   if (!xdr_guestfs_chunk (&xdr, (guestfs_chunk *) chunk)) {
505     fprintf (stderr, "send_chunk: failed to encode chunk\n");
506     xdr_destroy (&xdr);
507     return -1;
508   }
509
510   len = xdr_getpos (&xdr);
511   xdr_destroy (&xdr);
512
513   xdrmem_create (&xdr, lenbuf, 4, XDR_ENCODE);
514   xdr_u_int (&xdr, &len);
515   xdr_destroy (&xdr);
516
517   int err = (xwrite (sock, lenbuf, 4) == 0
518              && xwrite (sock, buf, len) == 0 ? 0 : -1);
519   if (err) {
520     fprintf (stderr, "send_chunk: write failed\n");
521     exit (EXIT_FAILURE);
522   }
523
524   return err;
525 }