499d19db9c33857ff74e7c4e9d75dbb1c61a31d9
[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 char *
31 do_checksum (const char *csumtype, const char *path)
32 {
33   const char *program;
34   char *buf;
35   char *out, *err;
36   int r;
37   int len;
38
39   if (STRCASEEQ (csumtype, "crc"))
40     program = "cksum";
41   else if (STRCASEEQ (csumtype, "md5"))
42     program = "md5sum";
43   else if (STRCASEEQ (csumtype, "sha1"))
44     program = "sha1sum";
45   else if (STRCASEEQ (csumtype, "sha224"))
46     program = "sha224sum";
47   else if (STRCASEEQ (csumtype, "sha256"))
48     program = "sha256sum";
49   else if (STRCASEEQ (csumtype, "sha384"))
50     program = "sha384sum";
51   else if (STRCASEEQ (csumtype, "sha512"))
52     program = "sha512sum";
53   else {
54     reply_with_error ("unknown checksum type, expecting crc|md5|sha1|sha224|sha256|sha384|sha512");
55     return NULL;
56   }
57
58   /* Make the path relative to /sysroot. */
59   buf = sysroot_path (path);
60   if (!buf) {
61     reply_with_perror ("malloc");
62     return NULL;
63   }
64
65   r = command (&out, &err, program, buf, NULL);
66   free (buf);
67   if (r == -1) {
68     reply_with_error ("%s: %s", program, err);
69     free (out);
70     free (err);
71     return NULL;
72   }
73
74   free (err);
75
76   /* Split it at the first whitespace. */
77   len = strcspn (out, " \t\n");
78   out[len] = '\0';
79
80   return out;                   /* Caller frees. */
81 }