generator: Update docs for checksum to point to checksum-device.
[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 static char *
54 checksum (const char *csumtype, const char *path)
55 {
56   const char *program;
57   char *out, *err;
58   int r;
59   int len;
60
61   program = program_of_csum (csumtype);
62   if (program == NULL)
63     return NULL;
64
65   r = command (&out, &err, program, path, NULL);
66   if (r == -1) {
67     reply_with_error ("%s: %s", program, err);
68     free (out);
69     free (err);
70     return NULL;
71   }
72
73   free (err);
74
75   /* Split it at the first whitespace. */
76   len = strcspn (out, " \t\n");
77   out[len] = '\0';
78
79   return out;                   /* Caller frees. */
80 }
81
82 char *
83 do_checksum (const char *csumtype, const char *path)
84 {
85   /* Make the path relative to /sysroot. */
86   char *buf = sysroot_path (path);
87   if (!buf) {
88     reply_with_perror ("malloc");
89     return NULL;
90   }
91
92   char *r = checksum (csumtype, buf);
93   free (buf);
94   return r;
95 }
96
97 char *
98 do_checksum_device (const char *csumtype, const char *device)
99 {
100   return checksum (csumtype, device);
101 }