-
Notifications
You must be signed in to change notification settings - Fork 664
/
virfile.c
4798 lines (4057 loc) · 125 KB
/
virfile.c
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* virfile.c: safer file handling
*
* Copyright (C) 2010-2014 Red Hat, Inc.
* Copyright (C) 2010 IBM Corporation
* Copyright (C) 2010 Stefan Berger
* Copyright (C) 2010 Eric Blake
*
* 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.1 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, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <config.h>
#include "internal.h"
#include <fcntl.h>
#ifndef WIN32
# include <termios.h>
#endif
#ifdef WITH_PTY_H
/* Linux openpty */
# include <pty.h>
#endif
#ifdef WITH_UTIL_H
/* macOS openpty */
# include <util.h>
#endif
#ifdef WITH_LIBUTIL_H
/* FreeBSD openpty */
# include <libutil.h>
#endif
#include <sys/stat.h>
#if defined(WITH_SYS_MOUNT_H)
# include <sys/mount.h>
#endif
#include <unistd.h>
#include <dirent.h>
#if defined WITH_MNTENT_H && defined WITH_GETMNTENT_R
# include <mntent.h>
#endif
#if WITH_MMAP
# include <sys/mman.h>
#endif
#if WITH_SYS_SYSCALL_H
# include <sys/syscall.h>
#endif
#if WITH_LIBACL
# include <sys/acl.h>
#endif
#include <sys/file.h>
#ifdef __linux__
# if WITH_LINUX_MAGIC_H
# include <linux/magic.h>
# endif
# include <sys/statfs.h>
# if WITH_DECL_LO_FLAGS_AUTOCLEAR
# include <linux/loop.h>
# endif
# include <sys/ioctl.h>
# include <linux/cdrom.h>
/* These come from linux/fs.h, but that header conflicts with
* sys/mount.h on glibc 2.36+ */
# define FS_IOC_GETFLAGS _IOR('f', 1, long)
# define FS_IOC_SETFLAGS _IOW('f', 2, long)
# define FS_NOCOW_FL 0x00800000
#endif
#if WITH_LIBATTR
# include <sys/xattr.h>
#endif
#include "configmake.h"
#include "viralloc.h"
#include "vircommand.h"
#include "virerror.h"
#include "virfile.h"
#include "virkmod.h"
#include "virlog.h"
#include "virprocess.h"
#include "virstring.h"
#include "virutil.h"
#include "virsocket.h"
#define VIR_FROM_THIS VIR_FROM_NONE
VIR_LOG_INIT("util.file");
#ifndef S_ISUID
# define S_ISUID 04000
#endif
#ifndef S_ISGID
# define S_ISGID 02000
#endif
#ifndef S_ISVTX
# define S_ISVTX 01000
#endif
#ifndef O_DIRECT
# define O_DIRECT 0
#endif
int virFileClose(int *fdptr, virFileCloseFlags flags)
{
int saved_errno = 0;
int rc = 0;
if (*fdptr < 0)
return 0;
if (flags & VIR_FILE_CLOSE_PRESERVE_ERRNO)
saved_errno = errno;
rc = close(*fdptr);
if (!(flags & VIR_FILE_CLOSE_DONT_LOG)) {
if (rc < 0) {
if (errno == EBADF) {
if (!(flags & VIR_FILE_CLOSE_IGNORE_EBADF))
VIR_WARN("Tried to close invalid fd %d", *fdptr);
} else {
VIR_DEBUG("Failed to close fd %d: %s",
*fdptr, g_strerror(errno));
}
}
}
*fdptr = -1;
if (flags & VIR_FILE_CLOSE_PRESERVE_ERRNO)
errno = saved_errno;
return rc;
}
int virFileFclose(FILE **file, bool preserve_errno)
{
int saved_errno = 0;
int rc = 0;
if (*file) {
if (preserve_errno)
saved_errno = errno;
rc = fclose(*file);
*file = NULL;
if (preserve_errno)
errno = saved_errno;
}
return rc;
}
FILE *virFileFdopen(int *fdptr, const char *mode)
{
FILE *file = NULL;
if (*fdptr >= 0) {
file = fdopen(*fdptr, mode);
if (file)
*fdptr = -1;
} else {
errno = EBADF;
}
return file;
}
/**
* virFileDirectFdFlag:
*
* Returns 0 if the kernel can avoid file system cache pollution
* without any additional flags, O_DIRECT if the original fd must be
* opened in direct mode, or -1 if there is no support for bypassing
* the file system cache.
*/
int
virFileDirectFdFlag(void)
{
/* XXX For now, Linux posix_fadvise is not powerful enough to
* avoid O_DIRECT. */
return O_DIRECT ? O_DIRECT : -1;
}
/* Opaque type for managing a wrapper around a fd. For now,
* read-write is not supported, just a single direction. */
struct _virFileWrapperFd {
bool closed; /* Whether virFileWrapperFdClose() has been already called */
virCommand *cmd; /* Child iohelper process to do the I/O. */
char *err_msg; /* stderr of @cmd */
};
#ifndef WIN32
# ifdef __linux__
/**
* virFileWrapperSetPipeSize:
* @fd: the fd of the pipe
*
* Set best pipe size on the passed file descriptor for bulk transfers of data.
*
* default pipe size (usually 64K) is generally not suited for large transfers
* to fast devices. A value of 1MB has been measured to improve virsh save
* by 400% in ideal conditions. We retry multiple times with smaller sizes
* on EPERM to account for possible small values of /proc/sys/fs/pipe-max-size.
*
* OS note: only for linux, on other OS this is a no-op.
*/
static int
virFileWrapperSetPipeSize(int fd)
{
int sz;
for (sz = 1024 * 1024; sz >= 64 * 1024; sz /= 2) {
int rv = fcntl(fd, F_SETPIPE_SZ, sz);
if (rv < 0 && errno == EPERM) {
VIR_DEBUG("EPERM trying to set fd %d pipe size to %d", fd, sz);
continue; /* retry with half the size */
}
if (rv < 0) {
virReportSystemError(errno, "%s",
_("unable to set pipe size"));
return -1;
}
VIR_DEBUG("fd %d pipe size adjusted to %d", fd, sz);
return 0;
}
VIR_WARN("unable to set pipe size, data transfer might be slow: %s",
g_strerror(errno));
return 0;
}
# else /* !__linux__ */
static int
virFileWrapperSetPipeSize(int fd G_GNUC_UNUSED)
{
return 0;
}
# endif /* !__linux__ */
/**
* virFileWrapperFdNew:
* @fd: pointer to fd to wrap
* @name: name of fd, for diagnostics
* @flags: bitwise-OR of virFileWrapperFdFlags
*
* Update @fd so that it meets parameters requested by @flags.
*
* If VIR_FILE_WRAPPER_BYPASS_CACHE bit is set in @flags, @fd will be updated
* in a way that all I/O to that file will bypass the system cache. The
* original fd must have been created with virFileDirectFdFlag() among the
* flags to open().
*
* If VIR_FILE_WRAPPER_NON_BLOCKING bit is set in @flags, @fd will be updated
* to ensure it properly supports non-blocking I/O, i.e., it will report
* EAGAIN.
*
* This must be called after open() and optional fchown() or fchmod(), but
* before any seek or I/O, and only on seekable fd. The file must be O_RDONLY
* (to read the entire existing file) or O_WRONLY (to write to an empty file).
* In some cases, @fd is changed to a non-seekable pipe; in this case, the
* caller must not do anything further with the original fd.
*
* On success, the new wrapper object is returned, which must be later
* freed with virFileWrapperFdFree(). On failure, @fd is unchanged, an
* error message is output, and NULL is returned.
*/
virFileWrapperFd *
virFileWrapperFdNew(int *fd, const char *name, unsigned int flags)
{
virFileWrapperFd *ret = NULL;
bool output = false;
int pipefd[2] = { -1, -1 };
int mode = -1;
g_autofree char *iohelper_path = NULL;
if (!flags) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("invalid use with no flags"));
return NULL;
}
/* XXX support posix_fadvise rather than O_DIRECT, if the kernel support
* for that is decent enough. In that case, we will also need to
* explicitly support VIR_FILE_WRAPPER_NON_BLOCKING since
* VIR_FILE_WRAPPER_BYPASS_CACHE alone will no longer require spawning
* iohelper.
*/
if ((flags & VIR_FILE_WRAPPER_BYPASS_CACHE) && !O_DIRECT) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("O_DIRECT unsupported on this platform"));
return NULL;
}
ret = g_new0(virFileWrapperFd, 1);
mode = fcntl(*fd, F_GETFL);
if (mode < 0) {
virReportError(VIR_ERR_INTERNAL_ERROR, _("invalid fd %d for %s"),
*fd, name);
goto error;
} else if ((mode & O_ACCMODE) == O_WRONLY) {
output = true;
} else if ((mode & O_ACCMODE) != O_RDONLY) {
virReportError(VIR_ERR_INTERNAL_ERROR, _("unexpected mode 0x%x for %s"),
mode & O_ACCMODE, name);
goto error;
}
if (virPipe(pipefd) < 0)
goto error;
if (virFileWrapperSetPipeSize(pipefd[output]) < 0)
goto error;
if (!(iohelper_path = virFileFindResource("libvirt_iohelper",
abs_top_builddir "/src",
LIBEXECDIR)))
goto error;
ret->cmd = virCommandNewArgList(iohelper_path, name, NULL);
if (output) {
virCommandSetInputFD(ret->cmd, pipefd[0]);
virCommandSetOutputFD(ret->cmd, fd);
virCommandAddArg(ret->cmd, "1");
} else {
virCommandSetInputFD(ret->cmd, *fd);
virCommandSetOutputFD(ret->cmd, &pipefd[1]);
virCommandAddArg(ret->cmd, "0");
}
/* In order to catch iohelper stderr, we must change
* iohelper's env so virLog functions print to stderr
*/
virCommandAddEnvPair(ret->cmd, "LIBVIRT_LOG_OUTPUTS", "1:stderr");
virCommandSetErrorBuffer(ret->cmd, &ret->err_msg);
virCommandDoAsyncIO(ret->cmd);
if (virCommandRunAsync(ret->cmd, NULL) < 0)
goto error;
if (VIR_CLOSE(pipefd[!output]) < 0) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("unable to close pipe"));
goto error;
}
VIR_FORCE_CLOSE(*fd);
*fd = pipefd[output];
return ret;
error:
VIR_FORCE_CLOSE(pipefd[0]);
VIR_FORCE_CLOSE(pipefd[1]);
virFileWrapperFdFree(ret);
return NULL;
}
#else /* WIN32 */
virFileWrapperFd *
virFileWrapperFdNew(int *fd G_GNUC_UNUSED,
const char *name G_GNUC_UNUSED,
unsigned int fdflags G_GNUC_UNUSED)
{
virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("virFileWrapperFd unsupported on this platform"));
return NULL;
}
#endif /* WIN32 */
/**
* virFileWrapperFdClose:
* @wfd: fd wrapper, or NULL
*
* If @wfd is valid, then ensure that I/O has completed, which may
* include reaping a child process. Return 0 if all data for the
* wrapped fd is complete, or -1 on failure with an error emitted.
* This function intentionally returns 0 when @wfd is NULL, so that
* callers can conditionally create a virFileWrapperFd wrapper but
* unconditionally call the cleanup code. To avoid deadlock, only
* call this after closing the fd resulting from virFileWrapperFdNew().
*
* This function can be safely called multiple times on the same @wfd.
*/
int
virFileWrapperFdClose(virFileWrapperFd *wfd)
{
int ret;
if (!wfd || wfd->closed)
return 0;
ret = virCommandWait(wfd->cmd, NULL);
/* If the command used to process I/O has failed and produced some
* messages on stderr, it's fair to assume those will be more
* relevant to the user than whatever eg. QEMU can figure out on its
* own having no knowledge of the fact a command is handling its I/O
* in the first place, so it's okay if we end up discarding an
* existing error here */
if (ret < 0 && wfd->err_msg && *wfd->err_msg)
virReportError(VIR_ERR_OPERATION_FAILED, "%s", wfd->err_msg);
wfd->closed = true;
return ret;
}
/**
* virFileWrapperFdFree:
* @wfd: fd wrapper, or NULL
*
* Free all remaining resources associated with @wfd. If
* virFileWrapperFdClose() was not previously called, then this may
* discard some previous I/O. To avoid deadlock, only call this after
* closing the fd resulting from virFileWrapperFdNew().
*/
void
virFileWrapperFdFree(virFileWrapperFd *wfd)
{
if (!wfd)
return;
g_free(wfd->err_msg);
virCommandFree(wfd->cmd);
g_free(wfd);
}
#ifndef WIN32
/**
* virFileLock:
* @fd: file descriptor to acquire the lock on
* @shared: type of lock to acquire
* @start: byte offset to start lock
* @len: length of lock (0 to acquire entire remaining file from @start)
* @waitForLock: wait for previously held lock or not
*
* Attempt to acquire a lock on the file @fd. If @shared
* is true, then a shared lock will be acquired,
* otherwise an exclusive lock will be acquired. If
* the lock cannot be acquired, an error will be
* returned. If @waitForLock is true, this will wait
* for the lock if another process has already acquired it.
*
* The lock will be released when @fd is closed. The lock
* will also be released if *any* other open file descriptor
* pointing to the same underlying file is closed. As such
* this function should not be relied on in multi-threaded
* apps where other threads can be opening/closing arbitrary
* files.
*
* Returns 0 on success, or -errno otherwise
*/
int virFileLock(int fd, bool shared, off_t start, off_t len, bool waitForLock)
{
struct flock fl = {
.l_type = shared ? F_RDLCK : F_WRLCK,
.l_whence = SEEK_SET,
.l_start = start,
.l_len = len,
};
int cmd = waitForLock ? F_SETLKW : F_SETLK;
if (fcntl(fd, cmd, &fl) < 0)
return -errno;
return 0;
}
/**
* virFileUnlock:
* @fd: file descriptor to release the lock on
* @start: byte offset to start unlock
* @len: length of lock (0 to release entire remaining file from @start)
*
* Release a lock previously acquired with virFileUnlock().
* NB the lock will also be released if any open file descriptor
* pointing to the same file as @fd is closed
*
* Returns 0 on success, or -errno on error
*/
int virFileUnlock(int fd, off_t start, off_t len)
{
struct flock fl = {
.l_type = F_UNLCK,
.l_whence = SEEK_SET,
.l_start = start,
.l_len = len,
};
if (fcntl(fd, F_SETLK, &fl) < 0)
return -errno;
return 0;
}
#else /* WIN32 */
int virFileLock(int fd G_GNUC_UNUSED,
bool shared G_GNUC_UNUSED,
off_t start G_GNUC_UNUSED,
off_t len G_GNUC_UNUSED,
bool waitForLock G_GNUC_UNUSED)
{
return -ENOSYS;
}
int virFileUnlock(int fd G_GNUC_UNUSED,
off_t start G_GNUC_UNUSED,
off_t len G_GNUC_UNUSED)
{
return -ENOSYS;
}
#endif /* WIN32 */
/**
* virFileRewrite:
* @path: file to rewrite
* @mode: mode of the file
* @uid: uid that should own file
* @gid: gid that should own file
* @rewrite: callback to write file contents
* @opaque: opaque data to pass to the callback
*
* Rewrite given @path atomically. This is achieved by writing a
* temporary file on a side and renaming it to the desired name.
* The temporary file is created using supplied @mode and
* @uid:@gid (pass -1 for current uid/gid) and written by
* @rewrite callback. It's callback's responsibility to report
* errors.
*
* Returns: 0 on success,
* -1 otherwise (with error reported)
*/
int
virFileRewrite(const char *path,
mode_t mode,
uid_t uid, gid_t gid,
virFileRewriteFunc rewrite,
const void *opaque)
{
g_autofree char *newfile = NULL;
int fd = -1;
int ret = -1;
int rc;
newfile = g_strdup_printf("%s.new", path);
if ((fd = virFileOpenAs(newfile, O_WRONLY | O_CREAT | O_TRUNC, mode,
uid, gid,
VIR_FILE_OPEN_FORCE_OWNER | VIR_FILE_OPEN_FORCE_MODE)) < 0) {
virReportSystemError(-fd,
_("Failed to create file '%s'"),
newfile);
goto cleanup;
}
if ((rc = rewrite(fd, newfile, opaque)) < 0) {
goto cleanup;
}
if (g_fsync(fd) < 0) {
virReportSystemError(errno, _("cannot sync file '%s'"),
newfile);
goto cleanup;
}
if (VIR_CLOSE(fd) < 0) {
virReportSystemError(errno, _("cannot save file '%s'"),
newfile);
goto cleanup;
}
if (rename(newfile, path) < 0) {
virReportSystemError(errno, _("cannot rename file '%s' as '%s'"),
newfile, path);
goto cleanup;
}
ret = 0;
cleanup:
VIR_FORCE_CLOSE(fd);
unlink(newfile);
return ret;
}
static int
virFileRewriteStrHelper(int fd,
const char *path,
const void *opaque)
{
const char *data = opaque;
if (safewrite(fd, data, strlen(data)) < 0) {
virReportSystemError(errno,
_("cannot write data to file '%s'"),
path);
return -1;
}
return 0;
}
int
virFileRewriteStr(const char *path,
mode_t mode,
const char *str)
{
return virFileRewrite(path, mode, -1, -1,
virFileRewriteStrHelper, str);
}
/**
* virFileResize:
*
* Change the capacity of the raw storage file at 'path'.
*/
int
virFileResize(const char *path,
unsigned long long capacity,
bool pre_allocate)
{
int rc;
VIR_AUTOCLOSE fd = -1;
if ((fd = open(path, O_RDWR)) < 0) {
virReportSystemError(errno, _("Unable to open '%s'"), path);
return -1;
}
if (pre_allocate) {
if ((rc = virFileAllocate(fd, 0, capacity)) != 0) {
if (rc == -2) {
virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
_("preallocate is not supported on this platform"));
} else {
virReportSystemError(errno,
_("Failed to pre-allocate space for "
"file '%s'"), path);
}
return -1;
}
}
if (ftruncate(fd, capacity) < 0) {
virReportSystemError(errno,
_("Failed to truncate file '%s'"), path);
return -1;
}
if (VIR_CLOSE(fd) < 0) {
virReportSystemError(errno, _("Unable to save '%s'"), path);
return -1;
}
return 0;
}
int virFileTouch(const char *path, mode_t mode)
{
int fd = -1;
if ((fd = open(path, O_WRONLY | O_CREAT, mode)) < 0) {
virReportSystemError(errno, _("cannot create file '%s'"),
path);
return -1;
}
if (VIR_CLOSE(fd) < 0) {
virReportSystemError(errno, _("cannot save file '%s'"),
path);
VIR_FORCE_CLOSE(fd);
return -1;
}
return 0;
}
#define MODE_BITS (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
int virFileUpdatePerm(const char *path,
mode_t mode_remove,
mode_t mode_add)
{
struct stat sb;
mode_t mode;
if (mode_remove & ~MODE_BITS || mode_add & ~MODE_BITS) {
virReportError(VIR_ERR_INVALID_ARG, "%s", _("invalid mode"));
return -1;
}
if (stat(path, &sb) < 0) {
virReportSystemError(errno, _("cannot stat '%s'"), path);
return -1;
}
mode = sb.st_mode & MODE_BITS;
if ((mode & mode_remove) == 0 && (mode & mode_add) == mode_add)
return 0;
mode &= MODE_BITS ^ mode_remove;
mode |= mode_add;
if (chmod(path, mode) < 0) {
virReportSystemError(errno, _("cannot change permission of '%s'"),
path);
return -1;
}
return 0;
}
#if defined(__linux__) && WITH_DECL_LO_FLAGS_AUTOCLEAR
# if WITH_DECL_LOOP_CTL_GET_FREE
/* virFileLoopDeviceOpenLoopCtl() returns -1 when a real failure has occurred
* while in the process of allocating or opening the loop device. On success
* we return 0 and modify the fd to the appropriate file descriptor.
* If /dev/loop-control does not exist, we return 0 and do not set fd. */
static int virFileLoopDeviceOpenLoopCtl(char **dev_name, int *fd)
{
int devnr;
int ctl_fd;
char *looppath = NULL;
VIR_DEBUG("Opening loop-control device");
if ((ctl_fd = open("/dev/loop-control", O_RDWR)) < 0) {
if (errno == ENOENT)
return 0;
virReportSystemError(errno, "%s",
_("Unable to open /dev/loop-control"));
return -1;
}
if ((devnr = ioctl(ctl_fd, LOOP_CTL_GET_FREE)) < 0) {
virReportSystemError(errno, "%s",
_("Unable to get free loop device via ioctl"));
close(ctl_fd);
return -1;
}
close(ctl_fd);
VIR_DEBUG("Found free loop device number %i", devnr);
looppath = g_strdup_printf("/dev/loop%i", devnr);
if ((*fd = open(looppath, O_RDWR)) < 0) {
virReportSystemError(errno,
_("Unable to open %s"), looppath);
VIR_FREE(looppath);
return -1;
}
*dev_name = looppath;
return 0;
}
# endif /* WITH_DECL_LOOP_CTL_GET_FREE */
static int virFileLoopDeviceOpenSearch(char **dev_name)
{
int fd = -1;
g_autoptr(DIR) dh = NULL;
struct dirent *de;
char *looppath = NULL;
struct loop_info64 lo;
int direrr;
VIR_DEBUG("Looking for loop devices in /dev");
if (virDirOpen(&dh, "/dev") < 0)
goto cleanup;
while ((direrr = virDirRead(dh, &de, "/dev")) > 0) {
/* Checking 'loop' prefix is insufficient, since
* new kernels have a dev named 'loop-control'
*/
if (!STRPREFIX(de->d_name, "loop") ||
!g_ascii_isdigit(de->d_name[4]))
continue;
looppath = g_build_filename("/dev", de->d_name, NULL);
VIR_DEBUG("Checking up on device %s", looppath);
if ((fd = open(looppath, O_RDWR)) < 0) {
virReportSystemError(errno,
_("Unable to open %s"), looppath);
goto cleanup;
}
if (ioctl(fd, LOOP_GET_STATUS64, &lo) < 0) {
/* Got a free device, return the fd */
if (errno == ENXIO)
goto cleanup;
VIR_FORCE_CLOSE(fd);
virReportSystemError(errno,
_("Unable to get loop status on %s"),
looppath);
goto cleanup;
}
/* Oh well, try the next device */
VIR_FORCE_CLOSE(fd);
VIR_FREE(looppath);
}
if (direrr < 0)
goto cleanup;
virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("Unable to find a free loop device in /dev"));
cleanup:
if (fd != -1) {
VIR_DEBUG("Got free loop device %s %d", looppath, fd);
*dev_name = looppath;
} else {
VIR_DEBUG("No free loop devices available");
VIR_FREE(looppath);
}
return fd;
}
static int virFileLoopDeviceOpen(char **dev_name)
{
int loop_fd = -1;
# if WITH_DECL_LOOP_CTL_GET_FREE
if (virFileLoopDeviceOpenLoopCtl(dev_name, &loop_fd) < 0)
return -1;
VIR_DEBUG("Return from loop-control got fd %d", loop_fd);
if (loop_fd >= 0)
return loop_fd;
# endif /* WITH_DECL_LOOP_CTL_GET_FREE */
/* Without the loop control device we just use the old technique. */
loop_fd = virFileLoopDeviceOpenSearch(dev_name);
return loop_fd;
}
int virFileLoopDeviceAssociate(const char *file,
char **dev)
{
int lofd = -1;
int fsfd = -1;
struct loop_info64 lo;
g_autofree char *loname = NULL;
int ret = -1;
if ((lofd = virFileLoopDeviceOpen(&loname)) < 0)
return -1;
memset(&lo, 0, sizeof(lo));
lo.lo_flags = LO_FLAGS_AUTOCLEAR;
/* Set backing file name for LOOP_GET_STATUS64 queries */
if (virStrcpy((char *) lo.lo_file_name, file, LO_NAME_SIZE) < 0) {
virReportSystemError(errno,
_("Unable to set backing file %s"), file);
goto cleanup;
}
if ((fsfd = open(file, O_RDWR)) < 0) {
virReportSystemError(errno,
_("Unable to open %s"), file);
goto cleanup;
}
if (ioctl(lofd, LOOP_SET_FD, fsfd) < 0) {
virReportSystemError(errno,
_("Unable to attach %s to loop device"),
file);
goto cleanup;
}
if (ioctl(lofd, LOOP_SET_STATUS64, &lo) < 0) {
virReportSystemError(errno, "%s",
_("Unable to mark loop device as autoclear"));
if (ioctl(lofd, LOOP_CLR_FD, 0) < 0)
VIR_WARN("Unable to detach %s from loop device", file);
goto cleanup;
}
VIR_DEBUG("Attached loop device %s %d to %s", file, lofd, loname);
*dev = g_steal_pointer(&loname);
ret = 0;
cleanup:
VIR_FORCE_CLOSE(fsfd);
if (ret == -1)
VIR_FORCE_CLOSE(lofd);
return lofd;
}
# define SYSFS_BLOCK_DIR "/sys/block"
# define NBD_DRIVER "nbd"
static int
virFileNBDDeviceIsBusy(const char *dev_name)
{
g_autofree char *path = NULL;
path = g_build_filename(SYSFS_BLOCK_DIR, dev_name, "pid", NULL);
if (!virFileExists(path)) {
if (errno == ENOENT)
return 0;
else
virReportSystemError(errno,
_("Cannot check NBD device %s pid"),
dev_name);
return -1;
}
return 1;
}
static char *
virFileNBDDeviceFindUnused(void)
{
g_autoptr(DIR) dh = NULL;
struct dirent *de;
int direrr;
if (virDirOpen(&dh, SYSFS_BLOCK_DIR) < 0)
return NULL;
while ((direrr = virDirRead(dh, &de, SYSFS_BLOCK_DIR)) > 0) {
if (STRPREFIX(de->d_name, "nbd")) {
int rv = virFileNBDDeviceIsBusy(de->d_name);
if (rv < 0)
return NULL;
if (rv == 0)
return g_build_filename("/dev", de->d_name, NULL);
}
}
if (direrr < 0)
return NULL;
virReportSystemError(EBUSY, "%s", _("No free NBD devices"));
return NULL;
}
static bool
virFileNBDLoadDriver(void)
{
if (virKModIsProhibited(NBD_DRIVER)) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("Failed to load nbd module: "
"administratively prohibited"));
return false;
} else {