-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands-posix.c
2983 lines (2564 loc) · 81.4 KB
/
commands-posix.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
/*
* QEMU Guest Agent POSIX-specific command implementations
*
* Copyright IBM Corp. 2011
*
* Authors:
* Michael Roth <[email protected]>
* Michal Privoznik <[email protected]>
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*/
#include "qemu/osdep.h"
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <dirent.h>
#include "qemu-common.h"
#include "guest-agent-core.h"
#include "qga-qapi-commands.h"
#include "qapi/error.h"
#include "qapi/qmp/qerror.h"
#include "qemu/queue.h"
#include "qemu/host-utils.h"
#include "qemu/sockets.h"
#include "qemu/base64.h"
#include "qemu/cutils.h"
#include "commands-common.h"
#ifdef HAVE_UTMPX
#include <utmpx.h>
#endif
#ifndef CONFIG_HAS_ENVIRON
#ifdef __APPLE__
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#else
extern char **environ;
#endif
#endif
#if defined(__linux__)
#include <mntent.h>
#include <linux/fs.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <net/if.h>
#include <sys/statvfs.h>
#ifdef CONFIG_LIBUDEV
#include <libudev.h>
#endif
#ifdef FIFREEZE
#define CONFIG_FSFREEZE
#endif
#ifdef FITRIM
#define CONFIG_FSTRIM
#endif
#endif
static void ga_wait_child(pid_t pid, int *status, Error **errp)
{
pid_t rpid;
*status = 0;
do {
rpid = waitpid(pid, status, 0);
} while (rpid == -1 && errno == EINTR);
if (rpid == -1) {
error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
pid);
return;
}
g_assert(rpid == pid);
}
void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
{
const char *shutdown_flag;
Error *local_err = NULL;
pid_t pid;
int status;
slog("guest-shutdown called, mode: %s", mode);
if (!has_mode || strcmp(mode, "powerdown") == 0) {
shutdown_flag = "-P";
} else if (strcmp(mode, "halt") == 0) {
shutdown_flag = "-H";
} else if (strcmp(mode, "reboot") == 0) {
shutdown_flag = "-r";
} else {
error_setg(errp,
"mode is invalid (valid values are: halt|powerdown|reboot");
return;
}
pid = fork();
if (pid == 0) {
/* child, start the shutdown */
setsid();
reopen_fd_to_null(0);
reopen_fd_to_null(1);
reopen_fd_to_null(2);
execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
"hypervisor initiated shutdown", (char*)NULL, environ);
_exit(EXIT_FAILURE);
} else if (pid < 0) {
error_setg_errno(errp, errno, "failed to create child process");
return;
}
ga_wait_child(pid, &status, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
if (!WIFEXITED(status)) {
error_setg(errp, "child process has terminated abnormally");
return;
}
if (WEXITSTATUS(status)) {
error_setg(errp, "child process has failed to shutdown");
return;
}
/* succeeded */
}
int64_t qmp_guest_get_time(Error **errp)
{
int ret;
qemu_timeval tq;
ret = qemu_gettimeofday(&tq);
if (ret < 0) {
error_setg_errno(errp, errno, "Failed to get time");
return -1;
}
return tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
}
void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
{
int ret;
int status;
pid_t pid;
Error *local_err = NULL;
struct timeval tv;
static const char hwclock_path[] = "/sbin/hwclock";
static int hwclock_available = -1;
if (hwclock_available < 0) {
hwclock_available = (access(hwclock_path, X_OK) == 0);
}
if (!hwclock_available) {
error_setg(errp, QERR_UNSUPPORTED);
return;
}
/* If user has passed a time, validate and set it. */
if (has_time) {
GDate date = { 0, };
/* year-2038 will overflow in case time_t is 32bit */
if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
error_setg(errp, "Time %" PRId64 " is too large", time_ns);
return;
}
tv.tv_sec = time_ns / 1000000000;
tv.tv_usec = (time_ns % 1000000000) / 1000;
g_date_set_time_t(&date, tv.tv_sec);
if (date.year < 1970 || date.year >= 2070) {
error_setg_errno(errp, errno, "Invalid time");
return;
}
ret = settimeofday(&tv, NULL);
if (ret < 0) {
error_setg_errno(errp, errno, "Failed to set time to guest");
return;
}
}
/* Now, if user has passed a time to set and the system time is set, we
* just need to synchronize the hardware clock. However, if no time was
* passed, user is requesting the opposite: set the system time from the
* hardware clock (RTC). */
pid = fork();
if (pid == 0) {
setsid();
reopen_fd_to_null(0);
reopen_fd_to_null(1);
reopen_fd_to_null(2);
/* Use '/sbin/hwclock -w' to set RTC from the system time,
* or '/sbin/hwclock -s' to set the system time from RTC. */
execle(hwclock_path, "hwclock", has_time ? "-w" : "-s",
NULL, environ);
_exit(EXIT_FAILURE);
} else if (pid < 0) {
error_setg_errno(errp, errno, "failed to create child process");
return;
}
ga_wait_child(pid, &status, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
if (!WIFEXITED(status)) {
error_setg(errp, "child process has terminated abnormally");
return;
}
if (WEXITSTATUS(status)) {
error_setg(errp, "hwclock failed to set hardware clock to system time");
return;
}
}
typedef enum {
RW_STATE_NEW,
RW_STATE_READING,
RW_STATE_WRITING,
} RwState;
struct GuestFileHandle {
uint64_t id;
FILE *fh;
RwState state;
QTAILQ_ENTRY(GuestFileHandle) next;
};
static struct {
QTAILQ_HEAD(, GuestFileHandle) filehandles;
} guest_file_state = {
.filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
};
static int64_t guest_file_handle_add(FILE *fh, Error **errp)
{
GuestFileHandle *gfh;
int64_t handle;
handle = ga_get_fd_handle(ga_state, errp);
if (handle < 0) {
return -1;
}
gfh = g_new0(GuestFileHandle, 1);
gfh->id = handle;
gfh->fh = fh;
QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
return handle;
}
GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
{
GuestFileHandle *gfh;
QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
{
if (gfh->id == id) {
return gfh;
}
}
error_setg(errp, "handle '%" PRId64 "' has not been found", id);
return NULL;
}
typedef const char * const ccpc;
#ifndef O_BINARY
#define O_BINARY 0
#endif
/* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
static const struct {
ccpc *forms;
int oflag_base;
} guest_file_open_modes[] = {
{ (ccpc[]){ "r", NULL }, O_RDONLY },
{ (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
{ (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
{ (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
{ (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
{ (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
{ (ccpc[]){ "r+", NULL }, O_RDWR },
{ (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
{ (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
{ (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
{ (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
{ (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
};
static int
find_open_flag(const char *mode_str, Error **errp)
{
unsigned mode;
for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
ccpc *form;
form = guest_file_open_modes[mode].forms;
while (*form != NULL && strcmp(*form, mode_str) != 0) {
++form;
}
if (*form != NULL) {
break;
}
}
if (mode == ARRAY_SIZE(guest_file_open_modes)) {
error_setg(errp, "invalid file open mode '%s'", mode_str);
return -1;
}
return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
}
#define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
S_IRGRP | S_IWGRP | \
S_IROTH | S_IWOTH)
static FILE *
safe_open_or_create(const char *path, const char *mode, Error **errp)
{
Error *local_err = NULL;
int oflag;
oflag = find_open_flag(mode, &local_err);
if (local_err == NULL) {
int fd;
/* If the caller wants / allows creation of a new file, we implement it
* with a two step process: open() + (open() / fchmod()).
*
* First we insist on creating the file exclusively as a new file. If
* that succeeds, we're free to set any file-mode bits on it. (The
* motivation is that we want to set those file-mode bits independently
* of the current umask.)
*
* If the exclusive creation fails because the file already exists
* (EEXIST is not possible for any other reason), we just attempt to
* open the file, but in this case we won't be allowed to change the
* file-mode bits on the preexistent file.
*
* The pathname should never disappear between the two open()s in
* practice. If it happens, then someone very likely tried to race us.
* In this case just go ahead and report the ENOENT from the second
* open() to the caller.
*
* If the caller wants to open a preexistent file, then the first
* open() is decisive and its third argument is ignored, and the second
* open() and the fchmod() are never called.
*/
fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
if (fd == -1 && errno == EEXIST) {
oflag &= ~(unsigned)O_CREAT;
fd = open(path, oflag);
}
if (fd == -1) {
error_setg_errno(&local_err, errno, "failed to open file '%s' "
"(mode: '%s')", path, mode);
} else {
qemu_set_cloexec(fd);
if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
error_setg_errno(&local_err, errno, "failed to set permission "
"0%03o on new file '%s' (mode: '%s')",
(unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
} else {
FILE *f;
f = fdopen(fd, mode);
if (f == NULL) {
error_setg_errno(&local_err, errno, "failed to associate "
"stdio stream with file descriptor %d, "
"file '%s' (mode: '%s')", fd, path, mode);
} else {
return f;
}
}
close(fd);
if (oflag & O_CREAT) {
unlink(path);
}
}
}
error_propagate(errp, local_err);
return NULL;
}
int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
Error **errp)
{
FILE *fh;
Error *local_err = NULL;
int64_t handle;
if (!has_mode) {
mode = "r";
}
slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
fh = safe_open_or_create(path, mode, &local_err);
if (local_err != NULL) {
error_propagate(errp, local_err);
return -1;
}
/* set fd non-blocking to avoid common use cases (like reading from a
* named pipe) from hanging the agent
*/
qemu_set_nonblock(fileno(fh));
handle = guest_file_handle_add(fh, errp);
if (handle < 0) {
fclose(fh);
return -1;
}
slog("guest-file-open, handle: %" PRId64, handle);
return handle;
}
void qmp_guest_file_close(int64_t handle, Error **errp)
{
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
int ret;
slog("guest-file-close called, handle: %" PRId64, handle);
if (!gfh) {
return;
}
ret = fclose(gfh->fh);
if (ret == EOF) {
error_setg_errno(errp, errno, "failed to close handle");
return;
}
QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
g_free(gfh);
}
GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
int64_t count, Error **errp)
{
GuestFileRead *read_data = NULL;
guchar *buf;
FILE *fh = gfh->fh;
size_t read_count;
/* explicitly flush when switching from writing to reading */
if (gfh->state == RW_STATE_WRITING) {
int ret = fflush(fh);
if (ret == EOF) {
error_setg_errno(errp, errno, "failed to flush file");
return NULL;
}
gfh->state = RW_STATE_NEW;
}
buf = g_malloc0(count+1);
read_count = fread(buf, 1, count, fh);
if (ferror(fh)) {
error_setg_errno(errp, errno, "failed to read file");
} else {
buf[read_count] = 0;
read_data = g_new0(GuestFileRead, 1);
read_data->count = read_count;
read_data->eof = feof(fh);
if (read_count) {
read_data->buf_b64 = g_base64_encode(buf, read_count);
}
gfh->state = RW_STATE_READING;
}
g_free(buf);
clearerr(fh);
return read_data;
}
GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
bool has_count, int64_t count,
Error **errp)
{
GuestFileWrite *write_data = NULL;
guchar *buf;
gsize buf_len;
int write_count;
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
FILE *fh;
if (!gfh) {
return NULL;
}
fh = gfh->fh;
if (gfh->state == RW_STATE_READING) {
int ret = fseek(fh, 0, SEEK_CUR);
if (ret == -1) {
error_setg_errno(errp, errno, "failed to seek file");
return NULL;
}
gfh->state = RW_STATE_NEW;
}
buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
if (!buf) {
return NULL;
}
if (!has_count) {
count = buf_len;
} else if (count < 0 || count > buf_len) {
error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
count);
g_free(buf);
return NULL;
}
write_count = fwrite(buf, 1, count, fh);
if (ferror(fh)) {
error_setg_errno(errp, errno, "failed to write to file");
slog("guest-file-write failed, handle: %" PRId64, handle);
} else {
write_data = g_new0(GuestFileWrite, 1);
write_data->count = write_count;
write_data->eof = feof(fh);
gfh->state = RW_STATE_WRITING;
}
g_free(buf);
clearerr(fh);
return write_data;
}
struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
GuestFileWhence *whence_code,
Error **errp)
{
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
GuestFileSeek *seek_data = NULL;
FILE *fh;
int ret;
int whence;
Error *err = NULL;
if (!gfh) {
return NULL;
}
/* We stupidly exposed 'whence':'int' in our qapi */
whence = ga_parse_whence(whence_code, &err);
if (err) {
error_propagate(errp, err);
return NULL;
}
fh = gfh->fh;
ret = fseek(fh, offset, whence);
if (ret == -1) {
error_setg_errno(errp, errno, "failed to seek file");
if (errno == ESPIPE) {
/* file is non-seekable, stdio shouldn't be buffering anyways */
gfh->state = RW_STATE_NEW;
}
} else {
seek_data = g_new0(GuestFileSeek, 1);
seek_data->position = ftell(fh);
seek_data->eof = feof(fh);
gfh->state = RW_STATE_NEW;
}
clearerr(fh);
return seek_data;
}
void qmp_guest_file_flush(int64_t handle, Error **errp)
{
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
FILE *fh;
int ret;
if (!gfh) {
return;
}
fh = gfh->fh;
ret = fflush(fh);
if (ret == EOF) {
error_setg_errno(errp, errno, "failed to flush file");
} else {
gfh->state = RW_STATE_NEW;
}
}
/* linux-specific implementations. avoid this if at all possible. */
#if defined(__linux__)
#if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
typedef struct FsMount {
char *dirname;
char *devtype;
unsigned int devmajor, devminor;
QTAILQ_ENTRY(FsMount) next;
} FsMount;
typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
static void free_fs_mount_list(FsMountList *mounts)
{
FsMount *mount, *temp;
if (!mounts) {
return;
}
QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
QTAILQ_REMOVE(mounts, mount, next);
g_free(mount->dirname);
g_free(mount->devtype);
g_free(mount);
}
}
static int dev_major_minor(const char *devpath,
unsigned int *devmajor, unsigned int *devminor)
{
struct stat st;
*devmajor = 0;
*devminor = 0;
if (stat(devpath, &st) < 0) {
slog("failed to stat device file '%s': %s", devpath, strerror(errno));
return -1;
}
if (S_ISDIR(st.st_mode)) {
/* It is bind mount */
return -2;
}
if (S_ISBLK(st.st_mode)) {
*devmajor = major(st.st_rdev);
*devminor = minor(st.st_rdev);
return 0;
}
return -1;
}
/*
* Walk the mount table and build a list of local file systems
*/
static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
{
struct mntent *ment;
FsMount *mount;
char const *mtab = "/proc/self/mounts";
FILE *fp;
unsigned int devmajor, devminor;
fp = setmntent(mtab, "r");
if (!fp) {
error_setg(errp, "failed to open mtab file: '%s'", mtab);
return;
}
while ((ment = getmntent(fp))) {
/*
* An entry which device name doesn't start with a '/' is
* either a dummy file system or a network file system.
* Add special handling for smbfs and cifs as is done by
* coreutils as well.
*/
if ((ment->mnt_fsname[0] != '/') ||
(strcmp(ment->mnt_type, "smbfs") == 0) ||
(strcmp(ment->mnt_type, "cifs") == 0)) {
continue;
}
if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
/* Skip bind mounts */
continue;
}
mount = g_new0(FsMount, 1);
mount->dirname = g_strdup(ment->mnt_dir);
mount->devtype = g_strdup(ment->mnt_type);
mount->devmajor = devmajor;
mount->devminor = devminor;
QTAILQ_INSERT_TAIL(mounts, mount, next);
}
endmntent(fp);
}
static void decode_mntname(char *name, int len)
{
int i, j = 0;
for (i = 0; i <= len; i++) {
if (name[i] != '\\') {
name[j++] = name[i];
} else if (name[i + 1] == '\\') {
name[j++] = '\\';
i++;
} else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
name[i + 2] >= '0' && name[i + 2] <= '7' &&
name[i + 3] >= '0' && name[i + 3] <= '7') {
name[j++] = (name[i + 1] - '0') * 64 +
(name[i + 2] - '0') * 8 +
(name[i + 3] - '0');
i += 3;
} else {
name[j++] = name[i];
}
}
}
static void build_fs_mount_list(FsMountList *mounts, Error **errp)
{
FsMount *mount;
char const *mountinfo = "/proc/self/mountinfo";
FILE *fp;
char *line = NULL, *dash;
size_t n;
char check;
unsigned int devmajor, devminor;
int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
fp = fopen(mountinfo, "r");
if (!fp) {
build_fs_mount_list_from_mtab(mounts, errp);
return;
}
while (getline(&line, &n, fp) != -1) {
ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
&devmajor, &devminor, &dir_s, &dir_e, &check);
if (ret < 3) {
continue;
}
dash = strstr(line + dir_e, " - ");
if (!dash) {
continue;
}
ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
&type_s, &type_e, &dev_s, &dev_e, &check);
if (ret < 1) {
continue;
}
line[dir_e] = 0;
dash[type_e] = 0;
dash[dev_e] = 0;
decode_mntname(line + dir_s, dir_e - dir_s);
decode_mntname(dash + dev_s, dev_e - dev_s);
if (devmajor == 0) {
/* btrfs reports major number = 0 */
if (strcmp("btrfs", dash + type_s) != 0 ||
dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
continue;
}
}
mount = g_new0(FsMount, 1);
mount->dirname = g_strdup(line + dir_s);
mount->devtype = g_strdup(dash + type_s);
mount->devmajor = devmajor;
mount->devminor = devminor;
QTAILQ_INSERT_TAIL(mounts, mount, next);
}
free(line);
fclose(fp);
}
#endif
#if defined(CONFIG_FSFREEZE)
static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
{
char *path;
char *dpath;
char *driver = NULL;
char buf[PATH_MAX];
ssize_t len;
path = g_strndup(syspath, pathlen);
dpath = g_strdup_printf("%s/driver", path);
len = readlink(dpath, buf, sizeof(buf) - 1);
if (len != -1) {
buf[len] = 0;
driver = g_path_get_basename(buf);
}
g_free(dpath);
g_free(path);
return driver;
}
static int compare_uint(const void *_a, const void *_b)
{
unsigned int a = *(unsigned int *)_a;
unsigned int b = *(unsigned int *)_b;
return a < b ? -1 : a > b ? 1 : 0;
}
/* Walk the specified sysfs and build a sorted list of host or ata numbers */
static int build_hosts(char const *syspath, char const *host, bool ata,
unsigned int *hosts, int hosts_max, Error **errp)
{
char *path;
DIR *dir;
struct dirent *entry;
int i = 0;
path = g_strndup(syspath, host - syspath);
dir = opendir(path);
if (!dir) {
error_setg_errno(errp, errno, "opendir(\"%s\")", path);
g_free(path);
return -1;
}
while (i < hosts_max) {
entry = readdir(dir);
if (!entry) {
break;
}
if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
++i;
} else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
++i;
}
}
qsort(hosts, i, sizeof(hosts[0]), compare_uint);
g_free(path);
closedir(dir);
return i;
}
/* Store disk device info specified by @sysfs into @fs */
static void build_guest_fsinfo_for_real_device(char const *syspath,
GuestFilesystemInfo *fs,
Error **errp)
{
unsigned int pci[4], host, hosts[8], tgt[3];
int i, nhosts = 0, pcilen;
GuestDiskAddress *disk;
GuestPCIAddress *pciaddr;
GuestDiskAddressList *list = NULL;
bool has_ata = false, has_host = false, has_tgt = false;
char *p, *q, *driver = NULL;
#ifdef CONFIG_LIBUDEV
struct udev *udev = NULL;
struct udev_device *udevice = NULL;
#endif
p = strstr(syspath, "/devices/pci");
if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
g_debug("only pci device is supported: sysfs path '%s'", syspath);
return;
}
p += 12 + pcilen;
while (true) {
driver = get_pci_driver(syspath, p - syspath, errp);
if (driver && (g_str_equal(driver, "ata_piix") ||
g_str_equal(driver, "sym53c8xx") ||
g_str_equal(driver, "virtio-pci") ||
g_str_equal(driver, "ahci"))) {
break;
}
g_free(driver);
if (sscanf(p, "/%x:%x:%x.%x%n",
pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) {
p += pcilen;
continue;
}
g_debug("unsupported driver or sysfs path '%s'", syspath);
return;
}
p = strstr(syspath, "/target");
if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
tgt, tgt + 1, tgt + 2) == 3) {
has_tgt = true;
}
p = strstr(syspath, "/ata");
if (p) {
q = p + 4;
has_ata = true;
} else {
p = strstr(syspath, "/host");
q = p + 5;
}
if (p && sscanf(q, "%u", &host) == 1) {
has_host = true;
nhosts = build_hosts(syspath, p, has_ata, hosts,
ARRAY_SIZE(hosts), errp);
if (nhosts < 0) {
goto cleanup;
}
}
pciaddr = g_malloc0(sizeof(*pciaddr));
pciaddr->domain = pci[0];
pciaddr->bus = pci[1];
pciaddr->slot = pci[2];
pciaddr->function = pci[3];
disk = g_malloc0(sizeof(*disk));
disk->pci_controller = pciaddr;
list = g_malloc0(sizeof(*list));
list->value = disk;
#ifdef CONFIG_LIBUDEV
udev = udev_new();
udevice = udev_device_new_from_syspath(udev, syspath);
if (udev == NULL || udevice == NULL) {
g_debug("failed to query udev");
} else {
const char *devnode, *serial;
devnode = udev_device_get_devnode(udevice);
if (devnode != NULL) {
disk->dev = g_strdup(devnode);
disk->has_dev = true;
}
serial = udev_device_get_property_value(udevice, "ID_SERIAL");
if (serial != NULL && *serial != 0) {
disk->serial = g_strdup(serial);
disk->has_serial = true;
}
}
#endif
if (strcmp(driver, "ata_piix") == 0) {
/* a host per ide bus, target*:0:<unit>:0 */
if (!has_host || !has_tgt) {
g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
goto cleanup;
}
for (i = 0; i < nhosts; i++) {
if (host == hosts[i]) {
disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
disk->bus = i;
disk->unit = tgt[1];
break;
}
}
if (i >= nhosts) {
g_debug("no host for '%s' (driver '%s')", syspath, driver);
goto cleanup;
}
} else if (strcmp(driver, "sym53c8xx") == 0) {
/* scsi(LSI Logic): target*:0:<unit>:0 */
if (!has_tgt) {
g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
goto cleanup;
}
disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
disk->unit = tgt[1];
} else if (strcmp(driver, "virtio-pci") == 0) {
if (has_tgt) {
/* virtio-scsi: target*:0:0:<unit> */
disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
disk->unit = tgt[2];
} else {
/* virtio-blk: 1 disk per 1 device */
disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
}
} else if (strcmp(driver, "ahci") == 0) {
/* ahci: 1 host per 1 unit */