File: create.c

package info (click to toggle)
libguestfs 1%3A1.44.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 118,932 kB
  • sloc: ansic: 458,017; ml: 51,424; sh: 13,191; java: 9,578; makefile: 7,931; cs: 6,328; haskell: 5,674; python: 3,871; perl: 3,528; erlang: 2,446; xml: 1,347; ruby: 350; pascal: 257; javascript: 157; lex: 135; yacc: 128; cpp: 10
file content (352 lines) | stat: -rw-r--r-- 10,586 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/* libguestfs
 * Copyright (C) 2012-2020 Red Hat Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
 * APIs for creating empty disks.
 *
 * Mostly this consists of wrappers around the L<qemu-img(1)> program.
 */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <string.h>
#include <libintl.h>

#ifdef HAVE_LINUX_FS_H
#include <linux/fs.h>
#endif

#include "guestfs.h"
#include "guestfs-internal.h"
#include "guestfs-internal-actions.h"

static int disk_create_raw (guestfs_h *g, const char *filename, int64_t size, const struct guestfs_disk_create_argv *optargs);
static int disk_create_qcow2 (guestfs_h *g, const char *filename, int64_t size, const char *backingfile, const struct guestfs_disk_create_argv *optargs);

int
guestfs_impl_disk_create (guestfs_h *g, const char *filename,
			  const char *format, int64_t size,
			  const struct guestfs_disk_create_argv *optargs)
{
  const char *backingfile;

  backingfile = optargs->bitmask & GUESTFS_DISK_CREATE_BACKINGFILE_BITMASK ?
    optargs->backingfile : NULL;

  /* Ensure size is valid. */
  if (backingfile) {
    if (size != -1) {
      error (g, _("if using a backing file, size must be passed as -1"));
      return -1;
    }
  } else {
    /* XXX Actually size == 0 could be valid, although not useful and
     * it causes qemu to break.
     */
    if (size <= 0) {
      error (g, _("invalid size: %" PRIi64), size);
      return -1;
    }
  }

  /* Now the format-specific code. */
  if (STREQ (format, "raw")) {
    if (backingfile) {
      error (g, _("backingfile cannot be used for raw format disks"));
      return -1;
    }
    if (disk_create_raw (g, filename, size, optargs) == -1)
      return -1;
  }
  else if (STREQ (format, "qcow2")) {
    if (disk_create_qcow2 (g, filename, size, backingfile, optargs) == -1)
      return -1;
  }
  else {
    /* Be conservative about what formats we support, since we don't
     * want to make unlimited promises through the API.  We can always
     * add more later.
     */
    error (g, _("unsupported format ‘%s’"), format);
    return -1;
  }

  return 0;
}

static int
disk_create_raw_block (guestfs_h *g, const char *filename)
{
  int fd;

  fd = open (filename, O_WRONLY|O_NOCTTY|O_CLOEXEC, 0666);
  if (fd == -1) {
    perrorf (g, _("cannot open block device: %s"), filename);
    return -1;
  }

  /* Just discard blocks, if possible.  However don't try too hard. */
#if defined(BLKGETSIZE64) && defined(BLKDISCARD)
  uint64_t size;
  uint64_t range[2];

  if (ioctl (fd, BLKGETSIZE64, &size) == 0) {
    range[0] = 0;
    range[1] = size;
    if (ioctl (fd, BLKDISCARD, range) == 0)
      debug (g, "disk_create: %s: BLKDISCARD failed on this device: %m",
             filename);
  }
#endif

  close (fd);

  return 0;
}

static int
disk_create_raw (guestfs_h *g, const char *filename, int64_t size,
                 const struct guestfs_disk_create_argv *optargs)
{
  int allocated = 0;
  int fd;
  struct stat statbuf;

  /* backingfile parameter not present checked above */

  if (optargs->bitmask & GUESTFS_DISK_CREATE_BACKINGFORMAT_BITMASK) {
    error (g, _("backingformat parameter cannot be used with raw format"));
    return -1;
  }
  if (optargs->bitmask & GUESTFS_DISK_CREATE_PREALLOCATION_BITMASK) {
    if (STREQ (optargs->preallocation, "off") ||
        STREQ (optargs->preallocation, "sparse"))
      allocated = 0;
    else if (STREQ (optargs->preallocation, "full"))
      allocated = 1;
    else {
      error (g, _("invalid value for preallocation parameter ‘%s’"),
             optargs->preallocation);
      return -1;
    }
  }
  if (optargs->bitmask & GUESTFS_DISK_CREATE_COMPAT_BITMASK) {
    error (g, _("compat parameter cannot be used with raw format"));
    return -1;
  }
  if (optargs->bitmask & GUESTFS_DISK_CREATE_CLUSTERSIZE_BITMASK) {
    error (g, _("clustersize parameter cannot be used with raw format"));
    return -1;
  }

  if (stat (filename, &statbuf) == 0) {
    /* Refuse to overwrite char devices. */
    if (S_ISCHR (statbuf.st_mode)) {
      error (g, _("refusing to overwrite char device ‘%s’"), filename);
      return -1;
    }
    /* Block devices have to be handled specially. */
    if (S_ISBLK (statbuf.st_mode))
      return disk_create_raw_block (g, filename);
  }

  fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_TRUNC|O_CLOEXEC, 0666);
  if (fd == -1) {
    perrorf (g, _("cannot create raw file: %s"), filename);
    return -1;
  }

  if (!allocated) {             /* Sparse file. */
    if (ftruncate (fd, size) == -1) {
      perrorf (g, _("%s: truncate"), filename);
      close (fd);
      unlink (filename);
      return -1;
    }
  }
  else {                        /* Allocated file. */
#ifdef HAVE_POSIX_FALLOCATE
    int err;

    err = posix_fallocate (fd, 0, size);
    if (err != 0) {
      errno = err;
      perrorf (g, _("%s: fallocate"), filename);
      close (fd);
      unlink (filename);
      return -1;
    }
#else
    /* Slow emulation of posix_fallocate on platforms which don't have it. */
    char buffer[BUFSIZ];
    size_t remaining = size;
    size_t n;
    ssize_t r;

    memset (buffer, 0, sizeof buffer);

    while (remaining > 0) {
      n = remaining > sizeof buffer ? sizeof buffer : remaining;
      r = write (fd, buffer, n);
      if (r == -1) {
        perrorf (g, _("%s: write"), filename);
        close (fd);
        unlink (filename);
        return -1;
      }
      remaining -= r;
    }
#endif
  }

  if (close (fd) == -1) {
    perrorf (g, _("%s: close"), filename);
    unlink (filename);
    return -1;
  }

  return 0;
}

/* http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 */
static int
is_power_of_2 (unsigned v)
{
  return v && ((v & (v - 1)) == 0);
}

/**
 * Check for valid backing format.  Allow any C<^[[:alnum]]+$>
 * (in C locale), but limit the length to something reasonable.
 */
#define VALID_FORMAT(format) \
  guestfs_int_string_is_valid ((format), 1, 16, \
                               VALID_FLAG_ALPHA|VALID_FLAG_DIGIT, "")

static int
disk_create_qcow2 (guestfs_h *g, const char *filename, int64_t size,
                   const char *backingfile,
                   const struct guestfs_disk_create_argv *optargs)
{
  const char *backingformat = NULL;
  const char *preallocation = NULL;
  const char *compat = NULL;
  int clustersize = -1;
  CLEANUP_FREE_STRINGSBUF DECLARE_STRINGSBUF (optionsv);
  CLEANUP_CMD_CLOSE struct command *cmd = guestfs_int_new_command (g);
  int r;

  if (optargs->bitmask & GUESTFS_DISK_CREATE_BACKINGFORMAT_BITMASK) {
    backingformat = optargs->backingformat;
    if (!VALID_FORMAT (backingformat)) {
      error (g, _("invalid value for backingformat parameter ‘%s’"),
             backingformat);
      return -1;
    }
  }
  if (optargs->bitmask & GUESTFS_DISK_CREATE_PREALLOCATION_BITMASK) {
    if (STREQ (optargs->preallocation, "off") ||
        STREQ (optargs->preallocation, "sparse"))
      preallocation = "off";
    else if (STREQ (optargs->preallocation, "metadata"))
      preallocation = "metadata";
    else if (STREQ (optargs->preallocation, "full"))
      /* Ugh: https://lists.gnu.org/archive/html/qemu-devel/2014-08/msg03863.html */
      preallocation = "falloc";
    else {
      error (g, _("invalid value for preallocation parameter ‘%s’"),
             preallocation);
      return -1;
    }
  }
  if (optargs->bitmask & GUESTFS_DISK_CREATE_COMPAT_BITMASK) {
    compat = optargs->compat;
    if (STRNEQ (compat, "0.10") && STRNEQ (compat, "1.1")) {
      error (g, _("invalid value for compat parameter ‘%s’"), compat);
      return -1;
    }
  }
  if (optargs->bitmask & GUESTFS_DISK_CREATE_CLUSTERSIZE_BITMASK) {
    clustersize = optargs->clustersize;
    if (clustersize < 512 || clustersize > 2097152 ||
        !is_power_of_2 ((unsigned) clustersize)) {
      error (g, _("invalid value for clustersize parameter ‘%d’"),
             clustersize);
      return -1;
    }
  }

  /* Assemble the qemu-img command line. */
  guestfs_int_cmd_add_arg (cmd, "qemu-img");
  guestfs_int_cmd_add_arg (cmd, "create");
  guestfs_int_cmd_add_arg (cmd, "-f");
  guestfs_int_cmd_add_arg (cmd, "qcow2");

  /* -o parameter. */
  if (backingfile) {
    CLEANUP_FREE char *p = guestfs_int_qemu_escape_param (g, backingfile);
    guestfs_int_add_sprintf (g, &optionsv, "backing_file=%s", p);
  }
  if (backingformat)
    guestfs_int_add_sprintf (g, &optionsv, "backing_fmt=%s", backingformat);
  if (preallocation)
    guestfs_int_add_sprintf (g, &optionsv, "preallocation=%s", preallocation);
  if (compat)
    guestfs_int_add_sprintf (g, &optionsv, "compat=%s", compat);
  if (clustersize >= 0)
    guestfs_int_add_sprintf (g, &optionsv, "cluster_size=%d", clustersize);
  guestfs_int_end_stringsbuf (g, &optionsv);

  if (optionsv.size > 1) {
    CLEANUP_FREE char *options = guestfs_int_join_strings (",", optionsv.argv);
    guestfs_int_cmd_add_arg (cmd, "-o");
    guestfs_int_cmd_add_arg (cmd, options);
  }

  /* Complete the command line. */
  /* If the filename is something like "file:foo" then qemu-img will
   * try to interpret that as "foo" in the file:/// protocol.  To
   * avoid that, if the path is relative prefix it with "./" since
   * qemu-img won't try to interpret such a path.
   */
  if (filename[0] == '/')
    guestfs_int_cmd_add_arg (cmd, filename);
  else
    guestfs_int_cmd_add_arg_format (cmd, "./%s", filename);
  if (size >= 0)
    guestfs_int_cmd_add_arg_format (cmd, "%" PRIi64, size);

  r = guestfs_int_cmd_run (cmd);
  if (!WIFEXITED (r) || WEXITSTATUS (r) != 0) {
    guestfs_int_external_command_failed (g, r, "qemu-img", filename);
    return -1;
  }

  return 0;
}