Clarify sparse behaviour of truncate-size command.
[libguestfs.git] / daemon / checksum.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 <string.h>
24 #include <unistd.h>
25
26 #include "../src/guestfs_protocol.h"
27 #include "daemon.h"
28 #include "actions.h"
29
30 static const char *
31 program_of_csum (const char *csumtype)
32 {
33   if (STRCASEEQ (csumtype, "crc"))
34     return "cksum";
35   else if (STRCASEEQ (csumtype, "md5"))
36     return "md5sum";
37   else if (STRCASEEQ (csumtype, "sha1"))
38     return "sha1sum";
39   else if (STRCASEEQ (csumtype, "sha224"))
40     return "sha224sum";
41   else if (STRCASEEQ (csumtype, "sha256"))
42     return "sha256sum";
43   else if (STRCASEEQ (csumtype, "sha384"))
44     return "sha384sum";
45   else if (STRCASEEQ (csumtype, "sha512"))
46     return "sha512sum";
47   else {
48     reply_with_error ("unknown checksum type, expecting crc|md5|sha1|sha224|sha256|sha384|sha512");
49     return NULL;
50   }
51 }
52
53 char *
54 do_checksum (const char *csumtype, const char *path)
55 {
56   const char *program;
57   char *buf;
58   char *out, *err;
59   int r;
60   int len;
61
62   program = program_of_csum (csumtype);
63   if (program == NULL)
64     return NULL;
65
66   /* Make the path relative to /sysroot. */
67   buf = sysroot_path (path);
68   if (!buf) {
69     reply_with_perror ("malloc");
70     return NULL;
71   }
72
73   r = command (&out, &err, program, buf, NULL);
74   free (buf);
75   if (r == -1) {
76     reply_with_error ("%s: %s", program, err);
77     free (out);
78     free (err);
79     return NULL;
80   }
81
82   free (err);
83
84   /* Split it at the first whitespace. */
85   len = strcspn (out, " \t\n");
86   out[len] = '\0';
87
88   return out;                   /* Caller frees. */
89 }