1 /* sh-blockdev.c - Block device functions for g13-syshelp
2 * Copyright (C) 2015 Werner Koch
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <https://www.gnu.org/licenses/>.
29 #include "g13-syshelp.h"
36 # error building this tool requires strtoull(3)
39 # error ULLONG_MAX missing
43 /* Return the size measured in the number of 512 byte sectors for the
46 sh_blockdev_getsz (const char *name, unsigned long long *r_nblocks)
56 err = gnupg_exec_tool ("/sbin/blockdev", argv, NULL, &result, NULL);
59 gpg_err_set_errno (0);
60 *r_nblocks = strtoull (result, NULL, 10);
61 if (*r_nblocks == ULLONG_MAX && errno)
63 err = gpg_error_from_syserror ();
72 /* Return 0 if the device NAME looks like an empty partition. */
74 sh_is_empty_partition (const char *name)
89 err = gnupg_exec_tool ("/sbin/blkid", argv, NULL, &buffer, NULL);
91 return gpg_error (GPG_ERR_FALSE);
94 /* There seems to be an UUID - thus we have a file system. */
96 return gpg_error (GPG_ERR_FALSE);
103 argv[3] = "PARTUUID";
106 err = gnupg_exec_tool ("/sbin/blkid", argv, NULL, &buffer, NULL);
108 return gpg_error (GPG_ERR_FALSE);
111 /* If there is no PARTUUID we assume that name has already a
114 return gpg_error (GPG_ERR_FALSE);
118 /* As a safeguard we require that the first 32k of a partition are
119 all zero before we assume the partition is empty. */
120 buffer = xtrymalloc (32 * 1024);
122 return gpg_error_from_syserror ();
123 fp = es_fopen (name, "rb,samethread");
126 err = gpg_error_from_syserror ();
127 log_error ("error opening '%s': %s\n", name, gpg_strerror (err));
129 return gpg_error (GPG_ERR_FALSE);
131 if (es_read (fp, buffer, 32 * 1024, &nread))
132 err = gpg_error_from_syserror ();
133 else if (nread != 32 *1024)
134 err = gpg_error (GPG_ERR_TOO_SHORT);
140 log_error ("error reading the first 32 KiB from '%s': %s\n",
141 name, gpg_strerror (err));
145 for (p=buffer; nread && !*p; nread--, p++)
149 return gpg_error (GPG_ERR_FALSE); /* No all zeroes. */