1guestfs-hacking(1) Virtualization Support guestfs-hacking(1)
2
3
4
6 guestfs-hacking - extending and contributing to libguestfs
7
9 This manual page is for hackers who want to extend libguestfs itself.
10
12 Libguestfs source is located in the github repository
13 https://github.com/libguestfs/libguestfs
14
15 Large amounts of boilerplate code in libguestfs (RPC, bindings,
16 documentation) are generated. This means that many source files will
17 appear to be missing from a straightforward git checkout. You have to
18 run the generator ("./configure && make -C generator") in order to
19 create those files.
20
21 Libguestfs uses an autotools-based build system, with the main files
22 being configure.ac and Makefile.am. See "THE BUILD SYSTEM".
23
24 The generator subdirectory contains the generator, plus files
25 describing the API. The lib subdirectory contains source for the
26 library. The appliance and daemon subdirectories contain the source
27 for the code that builds the appliance, and the code that runs in the
28 appliance respectively. Other directories are covered in the section
29 "SOURCE CODE SUBDIRECTORIES" below.
30
31 Apart from the fact that all API entry points go via some generated
32 code, the library is straightforward. (In fact, even the generated
33 code is designed to be readable, and should be read as ordinary code).
34 Some actions run entirely in the library, and are written as C
35 functions in files under lib. Others are forwarded to the daemon where
36 (after some generated RPC marshalling) they appear as C functions in
37 files under daemon.
38
39 To build from source, first read the guestfs-building(1).
40
41 SOURCE CODE SUBDIRECTORIES
42 There are a lot of subdirectories in the source tree! Which ones
43 should you concentrate on first? lib and daemon which contain the
44 source code of the core library. generator is the code generator
45 described above, so that is important. The Makefile.am in the root
46 directory will tell you in which order the subdirectories get built.
47 And then if you are looking at a particular tool (eg. customize) or
48 language binding (eg. python), go straight to that subdirectory, but
49 remember that if you didn't run the generator yet, then you may find
50 files which appear to be missing.
51
52 align
53 virt-alignment-scan(1) command and documentation.
54
55 appliance
56 The libguestfs appliance, build scripts and so on.
57
58 bash
59 Bash tab-completion scripts.
60
61 build-aux
62 Various build scripts used by autotools.
63
64 builder
65 virt-builder(1) command and documentation.
66
67 cat The virt-cat(1), virt-filesystems(1), virt-log(1), virt-ls(1) and
68 virt-tail(1) commands and documentation.
69
70 common
71 Various libraries of internal code can be found in the common
72 subdirectory:
73
74 common/edit
75 Common code for interactively and non-interactively editing
76 files within a libguestfs filesystem.
77
78 common/errnostring
79 The communication protocol used between the library and the
80 daemon running inside the appliance has to encode errnos as
81 strings, which is handled by this library.
82
83 common/mlcustomize
84 Library code associated with "virt-customize" but also used in
85 other tools.
86
87 common/mlgettext
88 Small, generated wrapper which allows libguestfs to be compiled
89 with or without ocaml-gettext. This is generated by
90 ./configure.
91
92 common/mlpcre
93 Lightweight OCaml bindings for Perl Compatible Regular
94 Expressions (PCRE). Note this is not related in any way to
95 Markus Mottl's ocaml-pcre library.
96
97 common/mlprogress
98 OCaml bindings for the progress bar functions (see
99 common/progress).
100
101 common/mlstdutils
102 A library of pure OCaml utility functions used in many places.
103
104 common/mltools
105 OCaml utility functions only used by the OCaml virt tools (like
106 "virt-sysprep", "virt-customize" etc.)
107
108 common/mlutils
109 OCaml bindings for C functions in "common/utils", and some
110 POSIX bindings which are missing from the OCaml stdlib.
111
112 common/mlvisit
113 OCaml bindings for the visit functions (see common/visit).
114
115 common/mlxml
116 OCaml bindings for the libxml2 library.
117
118 common/options
119 Common options parsing for guestfish, guestmount and some virt
120 tools.
121
122 common/parallel
123 A framework used for processing multiple libvirt domains in
124 parallel.
125
126 common/progress
127 Common code for printing progress bars.
128
129 common/protocol
130 The XDR-based communication protocol used between the library
131 and the daemon running inside the appliance is defined here.
132
133 common/qemuopts
134 Mini-library for writing qemu command lines and qemu config
135 files.
136
137 common/structs
138 Common code for printing and freeing libguestfs structs, used
139 by the library and some tools.
140
141 common/utils
142 Various utility functions used throughout the library and
143 tools.
144
145 common/visit
146 Recursively visit a guestfs filesystem hierarchy.
147
148 common/windows
149 Utility functions for handling Windows drive letters.
150
151 contrib
152 Outside contributions, experimental parts.
153
154 customize
155 virt-customize(1) command and documentation.
156
157 daemon
158 The daemon that runs inside the libguestfs appliance and carries
159 out actions.
160
161 df virt-df(1) command and documentation.
162
163 dib virt-dib(1) command and documentation.
164
165 diff
166 virt-diff(1) command and documentation.
167
168 docs
169 Miscellaneous manual pages.
170
171 edit
172 virt-edit(1) command and documentation.
173
174 examples
175 C API example code.
176
177 fish
178 guestfish(1), the command-line shell, and various shell scripts
179 built on top such as virt-copy-in(1), virt-copy-out(1),
180 virt-tar-in(1), virt-tar-out(1).
181
182 format
183 virt-format(1) command and documentation.
184
185 fuse
186 guestmount(1), FUSE (userspace filesystem) built on top of
187 libguestfs.
188
189 generator
190 The crucially important generator, used to automatically generate
191 large amounts of boilerplate C code for things like RPC and
192 bindings.
193
194 get-kernel
195 virt-get-kernel(1) command and documentation.
196
197 inspector
198 virt-inspector(1), the virtual machine image inspector.
199
200 lib Source code to the C library.
201
202 logo
203 Logo used on the website. The fish is called Arthur by the way.
204
205 m4 M4 macros used by autoconf. See "THE BUILD SYSTEM".
206
207 make-fs
208 virt-make-fs(1) command and documentation.
209
210 po Translations of simple gettext strings.
211
212 po-docs
213 The build infrastructure and PO files for translations of manpages
214 and POD files. Eventually this will be combined with the po
215 directory, but that is rather complicated.
216
217 rescue
218 virt-rescue(1) command and documentation.
219
220 resize
221 virt-resize(1) command and documentation.
222
223 sparsify
224 virt-sparsify(1) command and documentation.
225
226 sysprep
227 virt-sysprep(1) command and documentation.
228
229 tests
230 Tests.
231
232 test-data
233 Files and other test data used by the tests.
234
235 test-tool
236 Test tool for end users to test if their qemu/kernel combination
237 will work with libguestfs.
238
239 tmp Used for temporary files when running the tests (instead of /tmp
240 etc). The reason is so that you can run multiple parallel tests of
241 libguestfs without having one set of tests overwriting the
242 appliance created by another.
243
244 tools
245 Command line tools written in Perl (virt-win-reg(1) and many
246 others).
247
248 utils
249 Miscellaneous utilities, such as "boot-benchmark".
250
251 v2v Up to libguestfs > 1.42 this contained the virt-v2v(1) tool, but
252 this has now moved into a separate repository:
253 https://github.com/libguestfs/virt-v2v
254
255 website
256 The http://libguestfs.org website files.
257
258 csharp
259 erlang
260 gobject
261 golang
262 haskell
263 java
264 lua
265 ocaml
266 php
267 perl
268 python
269 ruby
270 Language bindings.
271
272 THE BUILD SYSTEM
273 Libguestfs uses the GNU autotools build system (autoconf, automake,
274 libtool).
275
276 The ./configure script is generated from configure.ac and
277 m4/guestfs-*.m4. Most of the configure script is split over many m4
278 macro files by topic, for example m4/guestfs-daemon.m4 deals with the
279 dependencies of the daemon.
280
281 The job of the top level Makefile.am is mainly to list the
282 subdirectories ("SUBDIRS") in the order they should be compiled.
283
284 common-rules.mk is included in every Makefile.am (top level and
285 subdirectories). subdir-rules.mk is included only in subdirectory
286 Makefile.am files.
287
288 There are many make targets. Use this command to list them all:
289
290 make help
291
293 ADDING A NEW API
294 Because large amounts of boilerplate code in libguestfs are generated,
295 this makes it easy to extend the libguestfs API.
296
297 To add a new API action there are two changes:
298
299 1. You need to add a description of the call (name, parameters, return
300 type, tests, documentation) to generator/actions_*.ml and possibly
301 generator/proc_nr.ml.
302
303 There are two sorts of API action, depending on whether the call
304 goes through to the daemon in the appliance, or is serviced
305 entirely by the library (see "ARCHITECTURE" in
306 guestfs-internals(1)). "guestfs_sync" in guestfs(3) is an example
307 of the former, since the sync is done in the appliance.
308 "guestfs_set_trace" in guestfs(3) is an example of the latter,
309 since a trace flag is maintained in the handle and all tracing is
310 done on the library side.
311
312 Most new actions are of the first type, and get added to the
313 "daemon_functions" list. Each function has a unique procedure
314 number used in the RPC protocol which is assigned to that action
315 when we publish libguestfs and cannot be reused. Take the latest
316 procedure number and increment it.
317
318 For library-only actions of the second type, add to the
319 "non_daemon_functions" list. Since these functions are serviced by
320 the library and do not travel over the RPC mechanism to the daemon,
321 these functions do not need a procedure number, and so the
322 procedure number is set to -1.
323
324 2. Implement the action (in C):
325
326 For daemon actions, implement the function "do_<name>" in the
327 "daemon/" directory.
328
329 For library actions, implement the function "guestfs_impl_<name>"
330 in the "lib/" directory.
331
332 In either case, use another function as an example of what to do.
333
334 3. As an alternative to step 2: Since libguestfs 1.38, daemon actions
335 can be implemented in OCaml. You have to set the "impl = OCaml
336 ..." flag in the generator. Take a look at daemon/file.ml for an
337 example.
338
339 After making these changes, use "make" to compile.
340
341 Note that you don’t need to implement the RPC, language bindings,
342 manual pages or anything else. It’s all automatically generated from
343 the OCaml description.
344
345 Adding tests for an API
346
347 You can supply zero or as many tests as you want per API call. The
348 tests can either be added as part of the API description
349 (generator/actions_*.ml), or in some rarer cases you may want to drop a
350 script into "tests/*/". Note that adding a script to "tests/*/" is
351 slower, so if possible use the first method.
352
353 The following describes the test environment used when you add an API
354 test in actions_*.ml.
355
356 The test environment has 4 block devices:
357
358 /dev/sda 2 GB
359 General block device for testing.
360
361 /dev/sdb 2 GB
362 /dev/sdb1 is an ext2 filesystem used for testing filesystem write
363 operations.
364
365 /dev/sdc 10 MB
366 Used in a few tests where two block devices are needed.
367
368 /dev/sdd
369 ISO with fixed content (see images/test.iso).
370
371 To be able to run the tests in a reasonable amount of time, the
372 libguestfs appliance and block devices are reused between tests. So
373 don't try testing "guestfs_kill_subprocess" in guestfs(3) :-x
374
375 Each test starts with an initial scenario, selected using one of the
376 "Init*" expressions, described in generator/types.ml. These initialize
377 the disks mentioned above in a particular way as documented in
378 types.ml. You should not assume anything about the previous contents
379 of other disks that are not initialized.
380
381 You can add a prerequisite clause to any individual test. This is a
382 run-time check, which, if it fails, causes the test to be skipped.
383 Useful if testing a command which might not work on all variations of
384 libguestfs builds. A test that has prerequisite of "Always" means to
385 run unconditionally.
386
387 In addition, packagers can skip individual tests by setting environment
388 variables before running "make check".
389
390 SKIP_TEST_<CMD>_<NUM>=1
391
392 eg: "SKIP_TEST_COMMAND_3=1" skips test #3 of "guestfs_command" in
393 guestfs(3).
394
395 or:
396
397 SKIP_TEST_<CMD>=1
398
399 eg: "SKIP_TEST_ZEROFREE=1" skips all "guestfs_zerofree" in guestfs(3)
400 tests.
401
402 Packagers can run only certain tests by setting for example:
403
404 TEST_ONLY="vfs_type zerofree"
405
406 See tests/c-api/tests.c for more details of how these environment
407 variables work.
408
409 Debugging new APIs
410
411 Test new actions work before submitting them.
412
413 You can use guestfish to try out new commands.
414
415 Debugging the daemon is a problem because it runs inside a minimal
416 environment. However you can fprintf messages in the daemon to stderr,
417 and they will show up if you use "guestfish -v".
418
419 ADDING A NEW LANGUAGE BINDING
420 All language bindings must be generated by the generator (see the
421 generator subdirectory).
422
423 There is no documentation for this yet. We suggest you look at an
424 existing binding, eg. generator/ocaml.ml or generator/perl.ml.
425
426 Adding tests for language bindings
427
428 Language bindings should come with tests. Previously testing of
429 language bindings was rather ad-hoc, but we have been trying to
430 formalize the set of tests that every language binding should use.
431
432 Currently only the OCaml and Perl bindings actually implement the full
433 set of tests, and the OCaml bindings are canonical, so you should
434 emulate what the OCaml tests do.
435
436 This is the numbering scheme used by the tests:
437
438 - 000+ basic tests:
439
440 010 load the library
441 020 create
442 030 create-flags
443 040 create multiple handles
444 050 test setting and getting config properties
445 060 explicit close
446 065 implicit close (in GC'd languages)
447 070 optargs
448 080 version
449 090 retvalues
450
451 - 100 launch, create partitions and LVs and filesystems
452
453 - 400+ events:
454
455 410 close event
456 420 log messages
457 430 progress messages
458
459 - 800+ regression tests (specific to the language)
460
461 - 900+ any other custom tests for the language
462
463 To save time when running the tests, only 100, 430, 800+, 900+ should
464 launch the handle.
465
466 FORMATTING CODE
467 Our C source code generally adheres to some basic code-formatting
468 conventions. The existing code base is not totally consistent on this
469 front, but we do prefer that contributed code be formatted similarly.
470 In short, use spaces-not-TABs for indentation, use 2 spaces for each
471 indentation level, and other than that, follow the K&R style.
472
473 If you use Emacs, add the following to one of your start-up files
474 (e.g., ~/.emacs), to help ensure that you get indentation right:
475
476 ;;; In libguestfs, indent with spaces everywhere (not TABs).
477 ;;; Exceptions: Makefile and ChangeLog modes.
478 (add-hook 'find-file-hook
479 '(lambda () (if (and buffer-file-name
480 (string-match "/libguestfs\\>"
481 (buffer-file-name))
482 (not (string-equal mode-name "Change Log"))
483 (not (string-equal mode-name "Makefile")))
484 (setq indent-tabs-mode nil))))
485
486 ;;; When editing C sources in libguestfs, use this style.
487 (defun libguestfs-c-mode ()
488 "C mode with adjusted defaults for use with libguestfs."
489 (interactive)
490 (c-set-style "K&R")
491 (setq c-indent-level 2)
492 (setq c-basic-offset 2))
493 (add-hook 'c-mode-hook
494 '(lambda () (if (string-match "/libguestfs\\>"
495 (buffer-file-name))
496 (libguestfs-c-mode))))
497
498 TESTING YOUR CHANGES
499 Turn warnings into errors when developing to make warnings hard to
500 ignore:
501
502 ./configure --enable-werror
503
504 Useful targets are:
505
506 "make check"
507 Runs the regular test suite.
508
509 This is implemented using the regular automake "TESTS" target. See
510 the automake documentation for details.
511
512 "make check-valgrind"
513 Runs a subset of the test suite under valgrind.
514
515 See "VALGRIND" below.
516
517 "make check-valgrind-local-guests"
518 Runs a subset of the test suite under valgrind using locally
519 installed libvirt guests (read-only).
520
521 "make check-direct"
522 Runs all tests using default appliance back-end. This only has any
523 effect if a non-default backend was selected using "./configure
524 --with-default-backend=..."
525
526 "make check-valgrind-direct"
527 Run a subset of the test suite under valgrind using the default
528 appliance back-end.
529
530 "make check-with-upstream-qemu"
531 Runs all tests using a local qemu binary. It looks for the qemu
532 binary in QEMUDIR (defaults to $HOME/d/qemu), but you can set this
533 to another directory on the command line, eg:
534
535 make check-with-upstream-qemu QEMUDIR=/usr/src/qemu
536
537 "make check-with-upstream-libvirt"
538 Runs all tests using a local libvirt. This only has any effect if
539 the libvirt backend was selected using "./configure
540 --with-default-backend=libvirt"
541
542 It looks for libvirt in LIBVIRTDIR (defaults to $HOME/d/libvirt),
543 but you can set this to another directory on the command line, eg:
544
545 make check-with-upstream-libvirt LIBVIRTDIR=/usr/src/libvirt
546
547 "make check-slow"
548 Runs some slow/long-running tests which are not run by default.
549
550 To mark a test as slow/long-running:
551
552 • Add it to the list of "TESTS" in the Makefile.am, just like a
553 normal test.
554
555 • Modify the test so it checks if the "SLOW=1" environment
556 variable is set, and if not set it skips (ie. returns with exit
557 code 77). If using $TEST_FUNCTIONS, you can call the function
558 "slow_test" for this.
559
560 • Add a variable "SLOW_TESTS" to the Makefile.am listing the slow
561 tests.
562
563 • Add a rule to the Makefile.am:
564
565 check-slow:
566 $(MAKE) check TESTS="$(SLOW_TESTS)" SLOW=1
567
568 "sudo make check-root"
569 Runs some tests which require root privileges. These are supposed
570 to be safe, but take care. You have to run this as root (eg. using
571 sudo(8) explicitly).
572
573 To mark a test as requiring root:
574
575 • Add it to the list of "TESTS" in the Makefile.am, just like a
576 normal test.
577
578 • Modify the test so it checks if euid == 0, and if not set it
579 skips (ie. returns with exit code 77). If using
580 $TEST_FUNCTIONS, you can call the function "root_test" for
581 this.
582
583 • Add a variable "ROOT_TESTS" to the Makefile.am listing the root
584 tests.
585
586 • Add a rule to the Makefile.am:
587
588 check-root:
589 $(MAKE) check TESTS="$(ROOT_TESTS)"
590
591 "make check-all"
592 Equivalent to running all "make check*" rules except "check-root".
593
594 "make check-release"
595 Runs a subset of "make check*" rules that are required to pass
596 before a tarball can be released. Currently this is:
597
598 • check
599
600 • check-valgrind
601
602 • check-direct
603
604 • check-valgrind-direct
605
606 • check-slow
607
608 "make installcheck"
609 Run "make check" on the installed copy of libguestfs.
610
611 The version of installed libguestfs being tested, and the version
612 of the libguestfs source tree must be the same.
613
614 Do:
615
616 ./configure
617 make clean ||:
618 make
619 make installcheck
620
621 VALGRIND
622 When you do "make check-valgrind", it searches for any Makefile.am in
623 the tree that has a "check-valgrind:" target and runs it.
624
625 Writing the Makefile.am and tests correctly to use valgrind and working
626 with automake parallel tests is subtle.
627
628 If your tests are run via a shell script wrapper, then in the wrapper
629 use:
630
631 $VG virt-foo
632
633 and in the Makefile.am use:
634
635 check-valgrind:
636 make VG="@VG@" check
637
638 However, if your binaries run directly from the "TESTS" rule, you have
639 to modify the Makefile.am like this:
640
641 LOG_COMPILER = $(VG)
642
643 check-valgrind:
644 make VG="@VG@" check
645
646 In either case, check that the right program is being tested by
647 examining the tmp/valgrind* log files carefully.
648
649 SUBMITTING PATCHES
650 Submit patches to the mailing list: https://lists.libguestfs.org and CC
651 to rjones@redhat.com.
652
653 You do not need to subscribe to the mailing list if you don’t want to.
654 There may be a short delay while your message is moderated.
655
656 INTERNATIONALIZATION (I18N) SUPPORT
657 We support i18n (gettext anyhow) in the library.
658
659 However many messages come from the daemon, and we don’t translate
660 those at the moment. One reason is that the appliance generally has
661 all locale files removed from it, because they take up a lot of space.
662 So we'd have to readd some of those, as well as copying our PO files
663 into the appliance.
664
665 Debugging messages are never translated, since they are intended for
666 the programmers.
667
669 HOW OCAML PROGRAMS ARE COMPILED AND LINKED
670 Mostly this section is "how we make automake & ocamlopt work together"
671 since OCaml programs themselves are easy to compile.
672
673 Automake has no native support for OCaml programs, ocamlc nor ocamlopt.
674 What we do instead is to treat OCaml programs as C programs which
675 happen to contain these "other objects" ("DEPENDENCIES" in automake-
676 speak) that happen to be the OCaml objects. This works because OCaml
677 programs usually have C files for native bindings etc.
678
679 So a typical program is described as just its C sources:
680
681 virt_customize_SOURCES = ... crypt-c.c perl_edit-c.c
682
683 For programs that have no explicit C sources, we create an empty
684 dummy.c file, and list that instead:
685
686 virt_resize_SOURCES = dummy.c
687
688 The OCaml objects which contain most of the code are listed as automake
689 dependencies (other dependencies may also be listed):
690
691 virt_customize_DEPENDENCIES = ... customize_main.cmx
692
693 The only other special thing we need to do is to provide a custom link
694 command. This is needed because automake won't assemble the ocamlopt
695 command, the list of objects and the "-cclib" libraries in the correct
696 order otherwise.
697
698 virt_customize_LINK = \
699 $(top_builddir)/ocaml-link.sh -cclib '-lutils' -- ...
700
701 The actual rules, which you can examine in customize/Makefile.am, are a
702 little bit more complicated than this because they have to handle:
703
704 • Compiling for byte code or native code.
705
706 • The pattern rules needed to compile the OCaml sources to objects.
707
708 These are now kept in subdir-rules.mk at the top level, which is
709 included in every subdirectory Makefile.am.
710
711 • Adding OCaml sources files to "EXTRA_DIST".
712
713 Automake isn't aware of the complete list of sources for a binary,
714 so it will not add them all automatically.
715
717 MAINTAINER MAKEFILE TARGETS
718 These "make" targets probably won’t work and aren't useful unless you
719 are a libguestfs maintainer.
720
721 make maintainer-commit
722
723 This commits everything in the working directory with the commit
724 message "Version $(VERSION).". You must update configure.ac, clean and
725 rebuild first.
726
727 make maintainer-tag
728
729 This tags the current HEAD commit with the tag "v$(VERSION)" and one of
730 the messages:
731
732 Version $(VERSION) stable
733
734 Version $(VERSION) development
735
736 (See "LIBGUESTFS VERSION NUMBERS" in guestfs(3) for the difference
737 between a stable and development release.)
738
739 make maintainer-check-authors
740
741 Check that all authors (found in git commit messages) are included in
742 the generator/authors.ml file.
743
744 make maintainer-check-extra-dist
745
746 This rule must be run after "make dist" (so there is a tarball in the
747 working directory). It compares the contents of the tarball with the
748 contents of git to ensure that no files have been missed from
749 Makefile.am "EXTRA_DIST" rules.
750
751 make maintainer-upload-website
752
753 This is used by the software used to automate libguestfs releases to
754 copy the libguestfs website to another git repository before it is
755 uploaded to the web server.
756
757 MAKING A STABLE RELEASE
758 When we make a stable release, there are several steps documented here.
759 See "LIBGUESTFS VERSION NUMBERS" in guestfs(3) for general information
760 about the stable branch policy.
761
762 • Check "make && make check" works on at least:
763
764 Fedora (x86-64)
765 Debian (x86-64)
766 Ubuntu (x86-64)
767 Fedora (aarch64)
768 Fedora (ppc64)
769 Fedora (ppc64le)
770 • Check "./configure --without-libvirt" works.
771
772 • Finalize guestfs-release-notes.pod
773
774 • Create new stable and development directories under
775 http://libguestfs.org/download.
776
777 • Edit website/index.html.in.
778
779 • Set the version (in configure.ac) to the new stable version, ie.
780 1.XX.0, and commit it:
781
782 ./localconfigure
783 make distclean -k
784 ./localconfigure
785 make && make dist
786 make maintainer-commit
787 make maintainer-tag
788
789 • Create the stable branch in git:
790
791 git branch stable-1.XX
792 git push origin stable-1.XX
793
794 • Do a full release of the stable branch.
795
796 • Set the version to the next development version and commit that.
797 Optionally do a full release of the development branch.
798
800 This section documents internal functions inside libguestfs and various
801 utilities. It is intended for libguestfs developers only.
802
803 This section is autogenerated from "/**" comments in source files,
804 which are marked up in POD format.
805
806 These functions are not publicly exported, and may change or be removed
807 at any time.
808
809 Subdirectory lib
810 File lib/actions-support.c
811
812 Helper functions for the actions code in lib/actions-*.c.
813
814 File lib/appliance-cpu.c
815
816 The appliance choice of CPU model.
817
818 Function "lib/appliance-cpu.c:guestfs_int_get_cpu_model"
819
820 const char *
821 guestfs_int_get_cpu_model (int kvm)
822
823 Return the right CPU model to use as the qemu "-cpu" parameter or its
824 equivalent in libvirt. This returns:
825
826 "host"
827 The literal string "host" means use "-cpu host".
828
829 "max"
830 The literal string "max" means use "-cpu max" (the best possible).
831 This requires awkward translation for libvirt.
832
833 some string
834 Some string such as "cortex-a57" means use "-cpu cortex-a57".
835
836 "NULL"
837 "NULL" means no "-cpu" option at all. Note returning "NULL" does
838 not indicate an error.
839
840 This is made unnecessarily hard and fragile because of two stupid
841 choices in QEMU:
842
843 • The default for "qemu-system-aarch64 -M virt" is to emulate a
844 "cortex-a15" (WTF?).
845
846 • We don't know for sure if KVM will work, but "-cpu host" is broken
847 with TCG, so we almost always pass a broken "-cpu" flag if KVM is
848 semi-broken in any way.
849
850 File lib/appliance-kcmdline.c
851
852 The appliance kernel command line.
853
854 Definition "lib/appliance-kcmdline.c:VALID_TERM"
855
856 #define VALID_TERM
857
858 Check that the $TERM environment variable is reasonable before we pass
859 it through to the appliance.
860
861 Function "lib/appliance-kcmdline.c:get_root_uuid_with_file"
862
863 static char *
864 get_root_uuid_with_file (guestfs_h *g, const char *appliance)
865
866 Given a disk image containing an extX filesystem, return the UUID.
867
868 Function "lib/appliance-kcmdline.c:run_qemu_img_dd"
869
870 static int
871 run_qemu_img_dd (guestfs_h *g, const char *in_file, char *out_file)
872
873 Read the first 256k bytes of the in_file with qemu-img(1) command and
874 write them into the out_file. That may be useful to get UUID of the
875 QCOW2 disk image with "get_root_uuid_with_file".
876
877 The function returns zero if successful, otherwise -1.
878
879 Function "lib/appliance-kcmdline.c:get_root_uuid"
880
881 static char *
882 get_root_uuid (guestfs_h *g, const char *appliance)
883
884 Get the UUID from the appliance disk image.
885
886 Function "lib/appliance-kcmdline.c:guestfs_int_appliance_command_line"
887
888 char *
889 guestfs_int_appliance_command_line (guestfs_h *g,
890 const char *appliance,
891 int flags)
892
893 Construct the Linux command line passed to the appliance. This is used
894 by the "direct" and "libvirt" backends, and is simply located in this
895 file because it's a convenient place for this common code.
896
897 The "appliance" parameter is the filename of the appliance (could be
898 NULL) from which we obtain the root UUID.
899
900 The "flags" parameter can contain the following flags logically or'd
901 together (or 0):
902
903 "APPLIANCE_COMMAND_LINE_IS_TCG"
904 If we are launching a qemu TCG guest (ie. KVM is known to be
905 disabled or unavailable). If you don't know, don't pass this flag.
906
907 Note that this function returns a newly allocated buffer which must be
908 freed by the caller.
909
910 File lib/appliance-uefi.c
911
912 Find the UEFI firmware needed to boot the appliance.
913
914 See also lib/uefi.c (autogenerated file) containing the firmware file
915 locations.
916
917 Function "lib/appliance-uefi.c:guestfs_int_get_uefi"
918
919 int
920 guestfs_int_get_uefi (guestfs_h *g, char *const *firmwares,
921 const char **firmware, char **code, char **vars,
922 int *flags)
923
924 Return the location of firmware needed to boot the appliance. This is
925 aarch64 only currently, since that's the only architecture where UEFI
926 is mandatory (and that only for RHEL).
927
928 "firmwares" is an optional list of allowed values for the firmware
929 autoselection of libvirt. It is "NULL" to indicate it is not supported.
930 *firmware is set to one of the strings in "firmwares" in case one can
931 be used.
932
933 *code is initialized with the path to the read-only UEFI code file.
934 *vars is initialized with the path to a copy of the UEFI vars file
935 (which is cleaned up automatically on exit).
936
937 In case a UEFI firmware is available, either *firmware is set to a
938 non-"NULL" value, or *code and *vars are.
939
940 *code and *vars should be freed by the caller, and *firmware must not.
941
942 If the function returns -1 then there was a real error which should
943 cause appliance building to fail (no UEFI firmware is not an error).
944
945 See also virt-v2v.git/v2v/utils.ml:find_uefi_firmware
946
947 File lib/appliance.c
948
949 This file deals with building the libguestfs appliance.
950
951 Function "lib/appliance.c:guestfs_int_build_appliance"
952
953 int
954 guestfs_int_build_appliance (guestfs_h *g,
955 char **kernel_rtn,
956 char **initrd_rtn,
957 char **appliance_rtn)
958
959 Locate or build the appliance.
960
961 This function locates or builds the appliance as necessary, handling
962 the supermin appliance, caching of supermin-built appliances, or using
963 either a fixed or old-style appliance.
964
965 The return value is 0 = good, -1 = error. Returned in
966 "appliance.kernel" will be the name of the kernel to use,
967 "appliance.initrd" the name of the initrd, "appliance.image" the name
968 of the ext2 root filesystem. "appliance.image" can be "NULL", meaning
969 that we are using an old-style (non-ext2) appliance. All three strings
970 must be freed by the caller. However the referenced files themselves
971 must not be deleted.
972
973 The process is as follows:
974
975 1. Look in "path" which contains a supermin appliance skeleton. If no
976 element has this, skip straight to step 3.
977
978 2. Call "supermin --build" to build the full appliance (if it needs to
979 be rebuilt). If this is successful, return the full appliance.
980
981 3. Check "path", looking for a fixed appliance. If one is found,
982 return it.
983
984 4. Check "path", looking for an old-style appliance. If one is found,
985 return it.
986
987 The supermin appliance cache directory lives in $TMPDIR/.guestfs-$UID/
988 and consists of up to four files:
989
990 $TMPDIR/.guestfs-$UID/lock - the supermin lock file
991 $TMPDIR/.guestfs-$UID/appliance.d/kernel - the kernel
992 $TMPDIR/.guestfs-$UID/appliance.d/initrd - the supermin initrd
993 $TMPDIR/.guestfs-$UID/appliance.d/root - the appliance
994
995 Multiple instances of libguestfs with the same UID may be racing to
996 create an appliance. However (since supermin ≥ 5) supermin provides a
997 --lock flag and atomic update of the appliance.d subdirectory.
998
999 Function "lib/appliance.c:locate_or_build_appliance"
1000
1001 static int
1002 locate_or_build_appliance (guestfs_h *g,
1003 struct appliance_files *appliance,
1004 const char *path)
1005
1006 Check "path", looking for one of appliances: supermin appliance, fixed
1007 appliance or old-style appliance. If one of the fixed appliances is
1008 found, return it. If the supermin appliance skeleton is found, build
1009 and return appliance.
1010
1011 Return values:
1012
1013 1 = appliance is found, returns C<appliance>,
1014 0 = appliance not found,
1015 -1 = error which aborts the launch process.
1016
1017 Function "lib/appliance.c:search_appliance"
1018
1019 static int
1020 search_appliance (guestfs_h *g, struct appliance_files *appliance)
1021
1022 Search elements of "g->path", returning the first "appliance" element
1023 which matches the predicate function "locate_or_build_appliance".
1024
1025 Return values:
1026
1027 1 = a path element matched, returns C<appliance>,
1028 0 = no path element matched,
1029 -1 = error which aborts the launch process.
1030
1031 Function "lib/appliance.c:build_supermin_appliance"
1032
1033 static int
1034 build_supermin_appliance (guestfs_h *g,
1035 const char *supermin_path,
1036 struct appliance_files *appliance)
1037
1038 Build supermin appliance from "supermin_path" to $TMPDIR/.guestfs-$UID.
1039
1040 Returns: 0 = built or -1 = error (aborts launch).
1041
1042 Function "lib/appliance.c:run_supermin_build"
1043
1044 static int
1045 run_supermin_build (guestfs_h *g,
1046 const char *lockfile,
1047 const char *appliancedir,
1048 const char *supermin_path)
1049
1050 Run "supermin --build" and tell it to generate the appliance.
1051
1052 Function "lib/appliance.c:dir_contains_file"
1053
1054 static int
1055 dir_contains_file (guestfs_h *g, const char *dir, const char *file)
1056
1057 Returns true iff "file" is contained in "dir".
1058
1059 Function "lib/appliance.c:dir_contains_files"
1060
1061 static int
1062 dir_contains_files (guestfs_h *g, const char *dir, ...)
1063
1064 Returns true iff every listed file is contained in "dir".
1065
1066 File lib/command.c
1067
1068 A wrapper for running external commands, loosely based on libvirt's
1069 "virCommand" interface.
1070
1071 In outline to use this interface you must:
1072
1073 1. Create a new command handle:
1074
1075 struct command *cmd;
1076 cmd = guestfs_int_new_command (g);
1077
1078 2. Either add arguments:
1079
1080 guestfs_int_cmd_add_arg (cmd, "qemu-img");
1081 guestfs_int_cmd_add_arg (cmd, "info");
1082 guestfs_int_cmd_add_arg (cmd, filename);
1083
1084 (NB: You don't need to add a "NULL" argument at the end.)
1085
1086 3. Or construct a command using a mix of quoted and unquoted strings.
1087 (This is useful for system(3)/popen("r")-style shell commands, with
1088 the added safety of allowing args to be quoted properly).
1089
1090 guestfs_int_cmd_add_string_unquoted (cmd, "qemu-img info ");
1091 guestfs_int_cmd_add_string_quoted (cmd, filename);
1092
1093 4. Set various flags, such as whether you want to capture errors in
1094 the regular libguestfs error log.
1095
1096 5. Run the command. This is what does the fork(2) call, optionally
1097 loops over the output, and then does a waitpid(3) and returns the
1098 exit status of the command.
1099
1100 r = guestfs_int_cmd_run (cmd);
1101 if (r == -1)
1102 // error
1103 // else test r using the WIF* functions
1104
1105 6. Close the handle:
1106
1107 guestfs_int_cmd_close (cmd);
1108
1109 (or use "CLEANUP_CMD_CLOSE").
1110
1111 Function "lib/command.c:guestfs_int_new_command"
1112
1113 struct command *
1114 guestfs_int_new_command (guestfs_h *g)
1115
1116 Create a new command handle.
1117
1118 Function "lib/command.c:guestfs_int_cmd_add_arg"
1119
1120 void
1121 guestfs_int_cmd_add_arg (struct command *cmd, const char *arg)
1122
1123 Add single arg (for "execv"-style command execution).
1124
1125 Function "lib/command.c:guestfs_int_cmd_add_arg_format"
1126
1127 void
1128 guestfs_int_cmd_add_arg_format (struct command *cmd, const char *fs, ...)
1129
1130 Add single arg (for "execv"-style command execution) using a
1131 printf(3)-style format string.
1132
1133 Function "lib/command.c:guestfs_int_cmd_add_string_unquoted"
1134
1135 void
1136 guestfs_int_cmd_add_string_unquoted (struct command *cmd, const char *str)
1137
1138 Add a string (for system(3)-style command execution).
1139
1140 This variant adds the strings without quoting them, which is dangerous
1141 if the string contains untrusted content.
1142
1143 Function "lib/command.c:guestfs_int_cmd_add_string_quoted"
1144
1145 void
1146 guestfs_int_cmd_add_string_quoted (struct command *cmd, const char *str)
1147
1148 Add a string (for system(3)-style command execution).
1149
1150 The string is enclosed in double quotes, with any special characters
1151 within the string which need escaping done. This is used to add a
1152 single argument to a system(3)-style command string.
1153
1154 Function "lib/command.c:guestfs_int_cmd_set_stdout_callback"
1155
1156 void
1157 guestfs_int_cmd_set_stdout_callback (struct command *cmd,
1158 cmd_stdout_callback stdout_callback,
1159 void *stdout_data, unsigned flags)
1160
1161 Set a callback which will capture stdout.
1162
1163 If flags contains "CMD_STDOUT_FLAG_LINE_BUFFER" (the default), then the
1164 callback is called line by line on the output. If there is a trailing
1165 "\n" then it is automatically removed before the callback is called.
1166 The line buffer is "\0"-terminated.
1167
1168 If flags contains "CMD_STDOUT_FLAG_UNBUFFERED", then buffers are passed
1169 to the callback as it is received from the command. Note in this case
1170 the buffer is not "\0"-terminated, so you need to may attention to the
1171 length field in the callback.
1172
1173 If flags contains "CMD_STDOUT_FLAG_WHOLE_BUFFER", then the callback is
1174 called exactly once, with the entire buffer. Note in this case the
1175 buffer is not "\0"-terminated, so you need to may attention to the
1176 length field in the callback.
1177
1178 Function "lib/command.c:guestfs_int_cmd_set_stderr_to_stdout"
1179
1180 void
1181 guestfs_int_cmd_set_stderr_to_stdout (struct command *cmd)
1182
1183 Equivalent to adding "2>&1" to the end of the command. This is
1184 incompatible with the "capture_errors" flag, because it doesn't make
1185 sense to combine them.
1186
1187 Function "lib/command.c:guestfs_int_cmd_clear_capture_errors"
1188
1189 void
1190 guestfs_int_cmd_clear_capture_errors (struct command *cmd)
1191
1192 Clear the "capture_errors" flag. This means that any errors will go to
1193 stderr, instead of being captured in the event log, and that is usually
1194 undesirable.
1195
1196 Function "lib/command.c:guestfs_int_cmd_set_child_callback"
1197
1198 void
1199 guestfs_int_cmd_set_child_callback (struct command *cmd,
1200 cmd_child_callback child_callback,
1201 void *data)
1202
1203 Set a function to be executed in the child, right before the execution.
1204 Can be used to setup the child, for example changing its current
1205 directory.
1206
1207 Function "lib/command.c:guestfs_int_cmd_set_child_rlimit"
1208
1209 void
1210 guestfs_int_cmd_set_child_rlimit (struct command *cmd, int resource, long limit)
1211
1212 Set up child rlimits, in case the process we are running could consume
1213 lots of space or time.
1214
1215 Function "lib/command.c:finish_command"
1216
1217 static void
1218 finish_command (struct command *cmd)
1219
1220 Finish off the command by either "NULL"-terminating the argv array or
1221 adding a terminating "\0" to the string, or die with an internal error
1222 if no command has been added.
1223
1224 Function "lib/command.c:loop"
1225
1226 static int
1227 loop (struct command *cmd)
1228
1229 The loop which reads errors and output and directs it either to the log
1230 or to the stdout callback as appropriate.
1231
1232 Function "lib/command.c:guestfs_int_cmd_run"
1233
1234 int
1235 guestfs_int_cmd_run (struct command *cmd)
1236
1237 Fork, run the command, loop over the output, and waitpid.
1238
1239 Returns the exit status. Test it using "WIF*" macros.
1240
1241 On error: Calls "error" and returns -1.
1242
1243 Function "lib/command.c:guestfs_int_cmd_pipe_run"
1244
1245 int
1246 guestfs_int_cmd_pipe_run (struct command *cmd, const char *mode)
1247
1248 Fork and run the command, but don't wait. Roughly equivalent to
1249 "popen (..., "r"|"w")".
1250
1251 Returns the file descriptor of the pipe, connected to stdout ("r") or
1252 stdin ("w") of the child process.
1253
1254 After reading/writing to this pipe, call "guestfs_int_cmd_pipe_wait" to
1255 wait for the status of the child.
1256
1257 Errors from the subcommand cannot be captured to the error log using
1258 this interface. Instead the caller should call
1259 "guestfs_int_cmd_get_pipe_errors" (after "guestfs_int_cmd_pipe_wait"
1260 returns an error).
1261
1262 Function "lib/command.c:guestfs_int_cmd_pipe_wait"
1263
1264 int
1265 guestfs_int_cmd_pipe_wait (struct command *cmd)
1266
1267 Wait for a subprocess created by "guestfs_int_cmd_pipe_run" to finish.
1268 On error (eg. failed syscall) this returns -1 and sets the error. If
1269 the subcommand fails, then use "WIF*" macros to check this, and call
1270 "guestfs_int_cmd_get_pipe_errors" to read the error messages printed by
1271 the child.
1272
1273 Function "lib/command.c:guestfs_int_cmd_get_pipe_errors"
1274
1275 char *
1276 guestfs_int_cmd_get_pipe_errors (struct command *cmd)
1277
1278 Read the error messages printed by the child. The caller must free the
1279 returned buffer after use.
1280
1281 Function "lib/command.c:guestfs_int_cmd_close"
1282
1283 void
1284 guestfs_int_cmd_close (struct command *cmd)
1285
1286 Close the "cmd" object and free all resources.
1287
1288 Function "lib/command.c:process_line_buffer"
1289
1290 static void
1291 process_line_buffer (struct command *cmd, int closed)
1292
1293 Deal with buffering stdout for the callback.
1294
1295 File lib/conn-socket.c
1296
1297 This file handles connections to the child process where this is done
1298 over regular POSIX sockets.
1299
1300 Function "lib/conn-socket.c:handle_log_message"
1301
1302 static int
1303 handle_log_message (guestfs_h *g,
1304 struct connection_socket *conn)
1305
1306 This is called if "conn->console_sock" becomes ready to read while we
1307 are doing one of the connection operations above. It reads and deals
1308 with the log message.
1309
1310 Returns:
1311
1312 1 log message(s) were handled successfully
1313
1314 0 connection to appliance closed
1315
1316 -1 error
1317
1318 Function "lib/conn-socket.c:guestfs_int_new_conn_socket_listening"
1319
1320 struct connection *
1321 guestfs_int_new_conn_socket_listening (guestfs_h *g,
1322 int daemon_accept_sock,
1323 int console_sock)
1324
1325 Create a new socket connection, listening.
1326
1327 Note that it's OK for "console_sock" to be passed as -1, meaning
1328 there's no console available for this appliance.
1329
1330 After calling this, "daemon_accept_sock" is owned by the connection,
1331 and will be closed properly either in "accept_connection" or
1332 "free_connection".
1333
1334 Function "lib/conn-socket.c:guestfs_int_new_conn_socket_connected"
1335
1336 struct connection *
1337 guestfs_int_new_conn_socket_connected (guestfs_h *g,
1338 int daemon_sock,
1339 int console_sock)
1340
1341 Create a new socket connection, connected.
1342
1343 As above, but the caller passes us a connected "daemon_sock" and
1344 promises not to call "accept_connection".
1345
1346 File lib/create.c
1347
1348 APIs for creating empty disks.
1349
1350 Mostly this consists of wrappers around the qemu-img(1) program.
1351
1352 Definition "lib/create.c:VALID_FORMAT"
1353
1354 #define VALID_FORMAT
1355
1356 Check for valid backing format. Allow any "^[[:alnum]]+$" (in C
1357 locale), but limit the length to something reasonable.
1358
1359 File lib/drives.c
1360
1361 Drives added are stored in an array in the handle. Code here manages
1362 that array and the individual "struct drive" data.
1363
1364 Function "lib/drives.c:create_overlay"
1365
1366 static int
1367 create_overlay (guestfs_h *g, struct drive *drv)
1368
1369 For readonly drives, create an overlay to protect the original drive
1370 content. Note we never need to clean up these overlays since they are
1371 created in the temporary directory and deleted when the handle is
1372 closed.
1373
1374 Function "lib/drives.c:create_drive_file"
1375
1376 static struct drive *
1377 create_drive_file (guestfs_h *g,
1378 const struct drive_create_data *data)
1379
1380 Create and free the "struct drive".
1381
1382 Function "lib/drives.c:create_drive_dev_null"
1383
1384 static struct drive *
1385 create_drive_dev_null (guestfs_h *g,
1386 struct drive_create_data *data)
1387
1388 Create the special /dev/null drive.
1389
1390 Traditionally you have been able to use /dev/null as a filename, as
1391 many times as you like. Ancient KVM (RHEL 5) cannot handle adding
1392 /dev/null readonly. qemu 1.2 + virtio-scsi segfaults when you use any
1393 zero-sized file including /dev/null.
1394
1395 Because of these problems, we replace /dev/null with a non-zero sized
1396 temporary file. This shouldn't make any difference since users are not
1397 supposed to try and access a null drive.
1398
1399 Function "lib/drives.c:drive_to_string"
1400
1401 static char *
1402 drive_to_string (guestfs_h *g, const struct drive *drv)
1403
1404 Convert a "struct drive" to a string for debugging. The caller must
1405 free this string.
1406
1407 Function "lib/drives.c:add_drive_to_handle_at"
1408
1409 static void
1410 add_drive_to_handle_at (guestfs_h *g, struct drive *d, size_t drv_index)
1411
1412 Add "struct drive" to the "g->drives" vector at the given index
1413 "drv_index". If the array isn't large enough it is reallocated. The
1414 index must not contain a drive already.
1415
1416 Function "lib/drives.c:add_drive_to_handle"
1417
1418 static void
1419 add_drive_to_handle (guestfs_h *g, struct drive *d)
1420
1421 Add struct drive to the end of the "g->drives" vector in the handle.
1422
1423 Function "lib/drives.c:guestfs_int_add_dummy_appliance_drive"
1424
1425 void
1426 guestfs_int_add_dummy_appliance_drive (guestfs_h *g)
1427
1428 Called during launch to add a dummy slot to "g->drives".
1429
1430 Function "lib/drives.c:guestfs_int_free_drives"
1431
1432 void
1433 guestfs_int_free_drives (guestfs_h *g)
1434
1435 Free up all the drives in the handle.
1436
1437 Definition "lib/drives.c:VALID_FORMAT"
1438
1439 #define VALID_FORMAT
1440
1441 Check string parameter matches regular expression "^[-_[:alnum:]]+$"
1442 (in C locale).
1443
1444 Definition "lib/drives.c:VALID_DISK_LABEL"
1445
1446 #define VALID_DISK_LABEL
1447
1448 Check the disk label is reasonable. It can't contain certain
1449 characters, eg. '/', ','. However be stricter here and ensure it's
1450 just alphabetic and ≤ 20 characters in length.
1451
1452 Definition "lib/drives.c:VALID_HOSTNAME"
1453
1454 #define VALID_HOSTNAME
1455
1456 Check the server hostname is reasonable.
1457
1458 Function "lib/drives.c:valid_port"
1459
1460 static int
1461 valid_port (int port)
1462
1463 Check the port number is reasonable.
1464
1465 Function "lib/drives.c:valid_blocksize"
1466
1467 static int
1468 valid_blocksize (int blocksize)
1469
1470 Check the block size is reasonable. It can't be other then 512 or
1471 4096.
1472
1473 Function "lib/drives.c:guestfs_int_checkpoint_drives"
1474
1475 size_t
1476 guestfs_int_checkpoint_drives (guestfs_h *g)
1477
1478 Checkpoint and roll back drives, so that groups of drives can be added
1479 atomically. Only used by "guestfs_add_domain" in guestfs(3).
1480
1481 Function "lib/drives.c:guestfs_impl_debug_drives"
1482
1483 char **
1484 guestfs_impl_debug_drives (guestfs_h *g)
1485
1486 Internal function to return the list of drives.
1487
1488 File lib/errors.c
1489
1490 This file handles errors, and also debug, trace and warning messages.
1491
1492 Errors in libguestfs API calls are handled by setting an error message
1493 and optional errno in the handle. The caller has the choice of testing
1494 API calls to find out if they failed and then querying the last error
1495 from the handle, and/or getting a callback.
1496
1497 From the point of view of the library source, generally you should use
1498 the "error" or "perrorf" macros along error paths, eg:
1499
1500 if (something_bad) {
1501 error (g, "something bad happened");
1502 return -1;
1503 }
1504
1505 Make sure to call the "error" or "perrorf" macro exactly once along
1506 each error path, since the handle can only store a single error and the
1507 previous error will be overwritten.
1508
1509 Function "lib/errors.c:guestfs_int_warning"
1510
1511 void
1512 guestfs_int_warning (guestfs_h *g, const char *fs, ...)
1513
1514 Print a warning.
1515
1516 Code should not call this function directly. Use the
1517 "warning (g, fs, ...)" macro.
1518
1519 Warnings are printed unconditionally. We try to make these rare:
1520 Generally speaking, a warning should either be an error, or if it's not
1521 important for end users then it should be a debug message.
1522
1523 Function "lib/errors.c:guestfs_int_debug"
1524
1525 void
1526 guestfs_int_debug (guestfs_h *g, const char *fs, ...)
1527
1528 Print a debug message.
1529
1530 Code should not call this function directly. To add debug messages in
1531 the library, use the "debug (g, fs, ...)" macro. The macro checks if
1532 "g->verbose" is false and avoids the function call, meaning the macro
1533 is more efficient.
1534
1535 Function "lib/errors.c:guestfs_int_trace"
1536
1537 void
1538 guestfs_int_trace (guestfs_h *g, const char *fs, ...)
1539
1540 Print a trace message.
1541
1542 Do not call this function. All calls are generated automatically.
1543
1544 Function "lib/errors.c:guestfs_int_error_errno"
1545
1546 void
1547 guestfs_int_error_errno (guestfs_h *g, int errnum, const char *fs, ...)
1548
1549 Set the last error and errno in the handle, and optionally raise the
1550 error callback if one is defined.
1551
1552 If you don't need to set errno, use the "error (g, fs, ...)" macro
1553 instead of calling this directly. If you need to set errno then there
1554 is no macro wrapper, so calling this function directly is fine.
1555
1556 Function "lib/errors.c:guestfs_int_perrorf"
1557
1558 void
1559 guestfs_int_perrorf (guestfs_h *g, const char *fs, ...)
1560
1561 Similar to perror(3), but it sets the last error in the handle, raises
1562 the error callback if one is defined, and supports format strings.
1563
1564 You should probably use the "perrorf (g, fs, ...)" macro instead of
1565 calling this directly.
1566
1567 Function "lib/errors.c:guestfs_int_launch_failed_error"
1568
1569 void
1570 guestfs_int_launch_failed_error (guestfs_h *g)
1571
1572 Raise a launch failed error in a standard format.
1573
1574 Since this is the most common error seen by people who have
1575 installation problems, buggy qemu, etc, and since no one reads the FAQ,
1576 describe in this error message what resources are available to debug
1577 launch problems.
1578
1579 Function "lib/errors.c:guestfs_int_unexpected_close_error"
1580
1581 void
1582 guestfs_int_unexpected_close_error (guestfs_h *g)
1583
1584 Raise an error if the appliance unexpectedly crashes after launch.
1585
1586 Function "lib/errors.c:guestfs_int_launch_timeout"
1587
1588 void
1589 guestfs_int_launch_timeout (guestfs_h *g)
1590
1591 Raise an error if the appliance hangs during launch.
1592
1593 Function "lib/errors.c:guestfs_int_external_command_failed"
1594
1595 void
1596 guestfs_int_external_command_failed (guestfs_h *g, int status,
1597 const char *cmd_name, const char *extra)
1598
1599 Raise an error if an external command fails.
1600
1601 "status" is the status code of the command (eg. returned from
1602 waitpid(2) or system(3)). This function turns the status code into an
1603 explanatory string.
1604
1605 File lib/events.c
1606
1607 Function "lib/events.c:replace_old_style_event_callback"
1608
1609 static void
1610 replace_old_style_event_callback (guestfs_h *g,
1611 guestfs_event_callback cb,
1612 uint64_t event_bitmask,
1613 void *opaque,
1614 void *opaque2)
1615
1616 Emulate old-style callback API.
1617
1618 There were no event handles, so multiple callbacks per event were not
1619 supported. Calling the same "guestfs_set_*_callback" function would
1620 replace the existing event. Calling it with "cb == NULL" meant that
1621 the caller wanted to remove the callback.
1622
1623 File lib/guestfs-internal-all.h
1624
1625 This header contains definitions which are shared by all parts of
1626 libguestfs, ie. the daemon, the library, language bindings and virt
1627 tools (ie. all C code).
1628
1629 If you need a definition used by only the library, put it in
1630 lib/guestfs-internal.h instead.
1631
1632 If a definition is used by only a single tool, it should not be in any
1633 shared header file at all.
1634
1635 File lib/guestfs-internal.h
1636
1637 This header file is included in the libguestfs library (lib/) only.
1638
1639 See also lib/guestfs-internal-all.h.
1640
1641 Structure "lib/guestfs-internal.h:event"
1642
1643 struct event {
1644 uint64_t event_bitmask;
1645 guestfs_event_callback cb;
1646 void *opaque;
1647
1648 /* opaque2 is not exposed through the API, but is used internally to
1649 * emulate the old-style callback API.
1650 */
1651 void *opaque2;
1652 };
1653
1654 This struct is used to maintain a list of events registered against the
1655 handle. See "g->events" in the handle.
1656
1657 Structure "lib/guestfs-internal.h:drive"
1658
1659 struct drive {
1660 /* Original source of the drive, eg. file:..., http:... */
1661 struct drive_source src;
1662
1663 /* If the drive is readonly, then an overlay [a local file] is
1664 * created before launch to protect the original drive content, and
1665 * the filename is stored here. Backends should open this file if
1666 * it is non-NULL, else consult the original source above.
1667 *
1668 * Note that the overlay is in a backend-specific format, probably
1669 * different from the source format. eg. qcow2
1670 */
1671 char *overlay;
1672
1673 /* Various per-drive flags. */
1674 bool readonly;
1675 char *name;
1676 char *disk_label;
1677 char *cachemode;
1678 enum discard discard;
1679 bool copyonread;
1680 int blocksize;
1681 };
1682
1683 There is one "struct drive" per drive.
1684
1685 Structure "lib/guestfs-internal.h:backend_ops"
1686
1687 struct backend_ops {
1688 /* Size (in bytes) of the per-handle data structure needed by this
1689 * backend. The data pointer is allocated and freed by libguestfs
1690 * and passed to the functions in the 'void *data' parameter.
1691 * Inside the data structure is opaque to libguestfs. Any strings
1692 * etc pointed to by it must be freed by the backend during
1693 * shutdown.
1694 */
1695 size_t data_size;
1696
1697 /* Create a COW overlay on top of a drive. This must be a local
1698 * file, created in the temporary directory. This is called when
1699 * the drive is added to the handle.
1700 */
1701 char *(*create_cow_overlay) (guestfs_h *g, void *data, struct drive *drv);
1702
1703 /* Launch and shut down. */
1704 int (*launch) (guestfs_h *g, void *data, const char *arg);
1705 int (*shutdown) (guestfs_h *g, void *data, int check_for_errors);
1706
1707 /* Miscellaneous. */
1708 int (*get_pid) (guestfs_h *g, void *data);
1709 int (*max_disks) (guestfs_h *g, void *data);
1710 };
1711
1712 Backend operations.
1713
1714 Each backend (eg. libvirt, direct) defines some functions which get run
1715 at various places in the handle lifecycle (eg. at launch, shutdown).
1716 The backend defines this struct pointing to those functions.
1717
1718 Structure "lib/guestfs-internal.h:connection"
1719
1720 struct connection {
1721 const struct connection_ops *ops;
1722
1723 /* In the real struct, private data used by each connection module
1724 * follows here.
1725 */
1726 };
1727
1728 Connection module.
1729
1730 A "connection" represents the appliance console connection plus the
1731 daemon connection. It hides the underlying representation (POSIX
1732 sockets, "virStreamPtr").
1733
1734 Structure "lib/guestfs-internal.h:cached_feature"
1735
1736 struct cached_feature {
1737 char *group;
1738 int result;
1739 };
1740
1741 Cache of queried features.
1742
1743 Used to cache the appliance features (see lib/available.c).
1744
1745 Structure "lib/guestfs-internal.h:guestfs_h"
1746
1747 struct guestfs_h {
1748 struct guestfs_h *next; /* Linked list of open handles. */
1749 enum state state; /* See the state machine diagram in guestfs(3)*/
1750
1751 /* Lock acquired when entering any public guestfs_* function to
1752 * protect the handle.
1753 */
1754 pthread_mutex_t lock;
1755
1756 /**** Configuration of the handle. ****/
1757 bool verbose; /* Debugging. */
1758 bool trace; /* Trace calls. */
1759 bool autosync; /* Autosync. */
1760 bool direct_mode; /* Direct mode. */
1761 bool recovery_proc; /* Create a recovery process. */
1762 bool enable_network; /* Enable the network. */
1763 bool selinux; /* selinux enabled? */
1764 bool pgroup; /* Create process group for children? */
1765 bool close_on_exit; /* Is this handle on the atexit list? */
1766
1767 int smp; /* If > 1, -smp flag passed to hv. */
1768 int memsize; /* Size of RAM (megabytes). */
1769
1770 char *path; /* Path to the appliance. */
1771 char *hv; /* Hypervisor (HV) binary. */
1772 char *append; /* Append to kernel command line. */
1773
1774 struct hv_param *hv_params; /* Extra hv parameters. */
1775
1776 char *program; /* Program name. */
1777 char *identifier; /* Handle identifier. */
1778
1779 /* Array of drives added by add-drive* APIs.
1780 *
1781 * Before launch this list can be empty or contain some drives.
1782 *
1783 * During launch, a dummy slot may be added which represents the
1784 * slot taken up by the appliance drive.
1785 *
1786 * During shutdown, this list is deleted, so that each launch gets a
1787 * fresh set of drives (however callers: don't do this, create a new
1788 * handle each time).
1789 *
1790 * Always use ITER_DRIVES macro to iterate over this list!
1791 */
1792 struct drive **drives;
1793 size_t nr_drives;
1794
1795 #define ITER_DRIVES(g,i,drv) \
1796 for (i = 0; i < (g)->nr_drives; ++i) \
1797 if (((drv) = (g)->drives[i]) != NULL)
1798
1799 /* Backend. NB: Use guestfs_int_set_backend to change the backend. */
1800 char *backend; /* The full string, always non-NULL. */
1801 char *backend_arg; /* Pointer to the argument part. */
1802 const struct backend_ops *backend_ops;
1803 void *backend_data; /* Per-handle data. */
1804 char **backend_settings; /* Backend settings (can be NULL). */
1805
1806 /**** Runtime information. ****/
1807 /* Temporary and cache directories. */
1808 /* The actual temporary directory - this is not created with the
1809 * handle, you have to call guestfs_int_lazy_make_tmpdir.
1810 */
1811 char *tmpdir;
1812 char *sockdir;
1813 /* Environment variables that affect tmpdir/cachedir/sockdir locations. */
1814 char *env_tmpdir; /* $TMPDIR (NULL if not set) */
1815 char *env_runtimedir; /* $XDG_RUNTIME_DIR (NULL if not set)*/
1816 char *int_tmpdir; /* $LIBGUESTFS_TMPDIR or guestfs_set_tmpdir or NULL */
1817 char *int_cachedir; /* $LIBGUESTFS_CACHEDIR or guestfs_set_cachedir or NULL */
1818
1819 /* Error handler, plus stack of old error handlers. */
1820 pthread_key_t error_data;
1821
1822 /* Linked list of error_data structures allocated for this handle,
1823 * plus a mutex to protect the linked list.
1824 */
1825 pthread_mutex_t error_data_list_lock;
1826 struct error_data *error_data_list;
1827
1828 /* Out of memory error handler. */
1829 guestfs_abort_cb abort_cb;
1830
1831 /* Events. */
1832 struct event *events;
1833 size_t nr_events;
1834
1835 /* Private data area. */
1836 struct hash_table *pda;
1837 struct pda_entry *pda_next;
1838
1839 /* User cancelled transfer. Not signal-atomic, but it doesn't
1840 * matter for this case because we only care if it is != 0.
1841 */
1842 int user_cancel;
1843
1844 struct timeval launch_t; /* The time that we called guestfs_launch. */
1845
1846 /* Used by bindtests. */
1847 FILE *test_fp;
1848
1849 /* Used to generate unique numbers, eg for temp files. To use this,
1850 * '++g->unique'. Note these are only unique per-handle, not
1851 * globally unique.
1852 */
1853 int unique;
1854
1855 /*** Protocol. ***/
1856 struct connection *conn; /* Connection to appliance. */
1857 int msg_next_serial;
1858
1859 #if HAVE_FUSE
1860 /**** Used by the mount-local APIs. ****/
1861 char *localmountpoint;
1862 struct fuse *fuse; /* FUSE handle. */
1863 int ml_dir_cache_timeout; /* Directory cache timeout. */
1864 Hash_table *lsc_ht, *xac_ht, *rlc_ht; /* Directory cache. */
1865 int ml_read_only; /* If mounted read-only. */
1866 int ml_debug_calls; /* Extra debug info on each FUSE call. */
1867 #endif
1868
1869 #ifdef HAVE_LIBVIRT
1870 /* Used by lib/libvirt-auth.c. */
1871 #define NR_CREDENTIAL_TYPES 9
1872 unsigned int nr_supported_credentials;
1873 int supported_credentials[NR_CREDENTIAL_TYPES];
1874 const char *saved_libvirt_uri; /* Doesn't need to be freed. */
1875 bool wrapper_warning_done;
1876 unsigned int nr_requested_credentials;
1877 virConnectCredentialPtr requested_credentials;
1878 #endif
1879
1880 /* Cached features. */
1881 struct cached_feature *features;
1882 size_t nr_features;
1883
1884 /* Used by lib/info.c. -1 = not tested or error; else 0 or 1. */
1885 int qemu_img_supports_U_option;
1886 };
1887
1888 The libguestfs handle.
1889
1890 Structure "lib/guestfs-internal.h:version"
1891
1892 struct version {
1893 int v_major;
1894 int v_minor;
1895 int v_micro;
1896 };
1897
1898 Used for storing major.minor.micro version numbers. See lib/version.c
1899 for more information.
1900
1901 File lib/guid.c
1902
1903 Function "lib/guid.c:guestfs_int_validate_guid"
1904
1905 int
1906 guestfs_int_validate_guid (const char *str)
1907
1908 Check whether a string supposed to contain a GUID actually contains it.
1909 It can recognize strings either as
1910 "{21EC2020-3AEA-1069-A2DD-08002B30309D}" or
1911 "21EC2020-3AEA-1069-A2DD-08002B30309D".
1912
1913 File lib/handle.c
1914
1915 This file deals with the "guestfs_h" handle, creating it, closing it,
1916 and initializing/setting/getting fields.
1917
1918 Function "lib/handle.c:init_libguestfs"
1919
1920 static void
1921 init_libguestfs (void)
1922
1923 No initialization is required by libguestfs, but libvirt and libxml2
1924 require initialization if they might be called from multiple threads.
1925 Hence this constructor function which is called when libguestfs is
1926 first loaded.
1927
1928 Function "lib/handle.c:shutdown_backend"
1929
1930 static int
1931 shutdown_backend (guestfs_h *g, int check_for_errors)
1932
1933 This function is the common path for shutting down the backend qemu
1934 process.
1935
1936 "guestfs_shutdown" calls "shutdown_backend" with "check_for_errors=1".
1937 "guestfs_close" calls "shutdown_backend" with "check_for_errors=0".
1938
1939 "check_for_errors" is a hint to the backend about whether we care about
1940 errors or not. In the libvirt case it can be used to optimize the
1941 shutdown for speed when we don't care.
1942
1943 Function "lib/handle.c:close_handles"
1944
1945 static void
1946 close_handles (void)
1947
1948 Close all open handles (called from atexit(3)).
1949
1950 Function "lib/handle.c:guestfs_int_get_backend_setting_bool"
1951
1952 int
1953 guestfs_int_get_backend_setting_bool (guestfs_h *g, const char *name)
1954
1955 This is a convenience function, but we might consider exporting it as
1956 an API in future.
1957
1958 File lib/info.c
1959
1960 Function "lib/info.c:qemu_img_supports_U_option"
1961
1962 static int
1963 qemu_img_supports_U_option (guestfs_h *g)
1964
1965 Test if the qemu-img info command supports the "-U" option to disable
1966 locking. The result is memoized in the handle.
1967
1968 Note this option was added in qemu 2.11. We can remove this test when
1969 we can assume everyone is using qemu >= 2.11.
1970
1971 File lib/inspect-icon.c
1972
1973 Function "lib/inspect-icon.c:guestfs_int_download_to_tmp"
1974
1975 char *
1976 guestfs_int_download_to_tmp (guestfs_h *g, const char *filename,
1977 const char *extension,
1978 uint64_t max_size)
1979
1980 Download a guest file to a local temporary file.
1981
1982 The name of the temporary (downloaded) file is returned. The caller
1983 must free the pointer, but does not need to delete the temporary file.
1984 It will be deleted when the handle is closed.
1985
1986 The name of the temporary file is randomly generated, but an extension
1987 can be specified using "extension" (or pass "NULL" for none).
1988
1989 Refuse to download the guest file if it is larger than "max_size". On
1990 this and other errors, "NULL" is returned.
1991
1992 File lib/launch-direct.c
1993
1994 Implementation of the "direct" backend.
1995
1996 For more details see "BACKENDS" in guestfs(3).
1997
1998 Function "lib/launch-direct.c:add_drive_standard_params"
1999
2000 static int
2001 add_drive_standard_params (guestfs_h *g, struct backend_direct_data *data,
2002 struct qemuopts *qopts,
2003 size_t i, struct drive *drv)
2004
2005 Add the standard elements of the "-drive" parameter.
2006
2007 Function "lib/launch-direct.c:add_device_blocksize_params"
2008
2009 static int
2010 add_device_blocksize_params (guestfs_h *g, struct qemuopts *qopts,
2011 struct drive *drv)
2012
2013 Add the physical_block_size and logical_block_size elements of the
2014 "-device" parameter.
2015
2016 Function "lib/launch-direct.c:launch_passt"
2017
2018 static int
2019 launch_passt (guestfs_h *g, long *passt_pid, char (*sockpath)[UNIX_PATH_MAX])
2020
2021 Launch passt such that it daemonizes.
2022
2023 On error, -1 is returned; "passt_pid" and "sockpath" are not modified.
2024
2025 On success, 0 is returned. "passt_pid" contains the PID of the passt
2026 background process. "sockpath" contains the pathname of the unix
2027 domain socket where passt will accept a single connection.
2028
2029 File lib/launch-libvirt.c
2030
2031 Function "lib/launch-libvirt.c:get_source_format_or_autodetect"
2032
2033 static char *
2034 get_source_format_or_autodetect (guestfs_h *g, struct drive *drv)
2035
2036 Return "drv->src.format", but if it is "NULL", autodetect the format.
2037
2038 libvirt has disabled the feature of detecting the disk format, unless
2039 the administrator sets "allow_disk_format_probing=1" in
2040 /etc/libvirt/qemu.conf. There is no way to detect if this option is
2041 set, so we have to do format detection here using "qemu-img" and pass
2042 that to libvirt.
2043
2044 This can still be a security issue, so in most cases it is recommended
2045 the users pass the format to libguestfs which will faithfully pass that
2046 straight through to libvirt without doing autodetection.
2047
2048 Caller must free the returned string. On error this function sets the
2049 error in the handle and returns "NULL".
2050
2051 Function "lib/launch-libvirt.c:make_qcow2_overlay"
2052
2053 static char *
2054 make_qcow2_overlay (guestfs_h *g, const char *backing_drive,
2055 const char *format)
2056
2057 Create a qcow2 format overlay, with the given "backing_drive" (file).
2058 The "format" parameter is the backing file format. The "format"
2059 parameter can be NULL, in this case the backing format will be
2060 determined automatically. This is used to create the appliance
2061 overlay, and also for read-only drives.
2062
2063 File lib/launch.c
2064
2065 This file implements "guestfs_launch" in guestfs(3).
2066
2067 Most of the work is done by the backends (see "BACKEND" in guestfs(3)),
2068 which are implemented in lib/launch-direct.c, lib/launch-libvirt.c etc,
2069 so this file mostly passes calls through to the current backend.
2070
2071 Function "lib/launch.c:guestfs_int_launch_send_progress"
2072
2073 void
2074 guestfs_int_launch_send_progress (guestfs_h *g, int perdozen)
2075
2076 This function sends a launch progress message.
2077
2078 Launching the appliance generates approximate progress messages.
2079 Currently these are defined as follows:
2080
2081 0 / 12: launch clock starts
2082 3 / 12: appliance created
2083 6 / 12: detected that guest kernel started
2084 9 / 12: detected that /init script is running
2085 12 / 12: launch completed successfully
2086
2087 Notes:
2088
2089 1. This is not a documented ABI and the behaviour may be changed or
2090 removed in future.
2091
2092 2. Messages are only sent if more than 5 seconds has elapsed since the
2093 launch clock started.
2094
2095 3. There is a hack in lib/proto.c to make this work.
2096
2097 Function "lib/launch.c:guestfs_int_timeval_diff"
2098
2099 int64_t
2100 guestfs_int_timeval_diff (const struct timeval *x, const struct timeval *y)
2101
2102 Compute "y - x" and return the result in milliseconds.
2103
2104 Approximately the same as this code:
2105 http://www.mpp.mpg.de/~huber/util/timevaldiff.c
2106
2107 Function "lib/launch.c:guestfs_int_unblock_sigterm"
2108
2109 void
2110 guestfs_int_unblock_sigterm (void)
2111
2112 Unblock the "SIGTERM" signal. Call this after fork(2) so that the
2113 parent process can send "SIGTERM" to the child process in case
2114 "SIGTERM" is blocked. See https://bugzilla.redhat.com/1460338.
2115
2116 Function "lib/launch.c:guestfs_impl_max_disks"
2117
2118 int
2119 guestfs_impl_max_disks (guestfs_h *g)
2120
2121 Returns the maximum number of disks allowed to be added to the backend
2122 (backend dependent).
2123
2124 Function "lib/launch.c:guestfs_impl_wait_ready"
2125
2126 int
2127 guestfs_impl_wait_ready (guestfs_h *g)
2128
2129 Implementation of "guestfs_wait_ready" in guestfs(3). You had to call
2130 this function after launch in versions ≤ 1.0.70, but it is now an
2131 (almost) no-op.
2132
2133 Function "lib/launch.c:guestfs_int_register_backend"
2134
2135 void
2136 guestfs_int_register_backend (const char *name, const struct backend_ops *ops)
2137
2138 When the library is loaded, each backend calls this function to
2139 register itself in a global list.
2140
2141 Function "lib/launch.c:guestfs_int_set_backend"
2142
2143 int
2144 guestfs_int_set_backend (guestfs_h *g, const char *method)
2145
2146 Implementation of "guestfs_set_backend" in guestfs(3).
2147
2148 • Callers must ensure this is only called in the config state.
2149
2150 • This shouldn't call "error" since it may be called early in handle
2151 initialization. It can return an error code however.
2152
2153 Function "lib/launch.c:guestfs_int_passt_runnable"
2154
2155 bool
2156 guestfs_int_passt_runnable (guestfs_h *g)
2157
2158 Return "true" if we can call "passt --help", and it exits with status 0
2159 or 1.
2160
2161 (At least "passt-0^20230222.g4ddbcb9-2.el9_2.x86_64" terminates with
2162 status 1 in response to "--help", which is arguably wrong, and
2163 potentially subject to change, but it doesn't really matter.)
2164
2165 File lib/private-data.c
2166
2167 Implement a private data area where libguestfs C API users can attach
2168 arbitrary pieces of data to a "guestfs_h" handle.
2169
2170 For more information see "PRIVATE DATA AREA" in guestfs(3).
2171
2172 Language bindings do not generally expose this, largely because in non-
2173 C languages it is easy to associate data with handles in other ways
2174 (using hash tables or maps).
2175
2176 Structure "lib/private-data.c:pda_entry"
2177
2178 struct pda_entry {
2179 char *key; /* key */
2180 void *data; /* opaque user data pointer */
2181 };
2182
2183 The private data area is internally stored as a gnulib hash table
2184 containing "pda_entry" structures.
2185
2186 Note the private data area is allocated lazily, since the vast majority
2187 of callers will never use it. This means "g->pda" is likely to be
2188 "NULL".
2189
2190 File lib/proto.c
2191
2192 This is the code used to send and receive RPC messages and (for certain
2193 types of message) to perform file transfers. This code is driven from
2194 the generated actions (lib/actions-*.c). There are five different
2195 cases to consider:
2196
2197 1. A non-daemon function (eg. "guestfs_set_verbose" in guestfs(3)).
2198 There is no RPC involved at all, it's all handled inside the
2199 library.
2200
2201 2. A simple RPC (eg. "guestfs_mount" in guestfs(3)). We write the
2202 request, then read the reply. The sequence of calls is:
2203
2204 guestfs_int_send
2205 guestfs_int_recv
2206
2207 3. An RPC with "FileIn" parameters (eg. "guestfs_upload" in
2208 guestfs(3)). We write the request, then write the file(s), then
2209 read the reply. The sequence of calls is:
2210
2211 guestfs_int_send
2212 guestfs_int_send_file (possibly multiple times)
2213 guestfs_int_recv
2214
2215 4. An RPC with "FileOut" parameters (eg. "guestfs_download" in
2216 guestfs(3)). We write the request, then read the reply, then read
2217 the file(s). The sequence of calls is:
2218
2219 guestfs_int_send
2220 guestfs_int_recv
2221 guestfs_int_recv_file (possibly multiple times)
2222
2223 5. Both "FileIn" and "FileOut" parameters. There are no calls like
2224 this in the current API, but they would be implemented as a
2225 combination of cases 3 and 4.
2226
2227 All read/write/etc operations are performed using the current
2228 connection module ("g->conn"). During operations the connection module
2229 transparently handles log messages that appear on the console.
2230
2231 Function "lib/proto.c:child_cleanup"
2232
2233 static void
2234 child_cleanup (guestfs_h *g)
2235
2236 This is called if we detect EOF, ie. qemu died.
2237
2238 Function "lib/proto.c:guestfs_int_progress_message_callback"
2239
2240 void
2241 guestfs_int_progress_message_callback (guestfs_h *g,
2242 const guestfs_progress *message)
2243
2244 Convenient wrapper to generate a progress message callback.
2245
2246 Function "lib/proto.c:guestfs_int_log_message_callback"
2247
2248 void
2249 guestfs_int_log_message_callback (guestfs_h *g, const char *buf, size_t len)
2250
2251 Connection modules call us back here when they get a log message.
2252
2253 Function "lib/proto.c:check_daemon_socket"
2254
2255 static ssize_t
2256 check_daemon_socket (guestfs_h *g)
2257
2258 Before writing to the daemon socket, check the read side of the daemon
2259 socket for any of these conditions:
2260
2261 error
2262 return -1
2263
2264 daemon cancellation message
2265 return -2
2266
2267 progress message
2268 handle it here
2269
2270 end of input or appliance exited unexpectedly
2271 return 0
2272
2273 anything else
2274 return 1
2275
2276 Function "lib/proto.c:guestfs_int_send_file"
2277
2278 int
2279 guestfs_int_send_file (guestfs_h *g, const char *filename)
2280
2281 Send a file.
2282
2283 Returns 0 on success, -1 for error, -2 if the daemon cancelled (we must
2284 read the error message).
2285
2286 Function "lib/proto.c:send_file_data"
2287
2288 static int
2289 send_file_data (guestfs_h *g, const char *buf, size_t len)
2290
2291 Send a chunk of file data.
2292
2293 Function "lib/proto.c:send_file_cancellation"
2294
2295 static int
2296 send_file_cancellation (guestfs_h *g)
2297
2298 Send a cancellation message.
2299
2300 Function "lib/proto.c:send_file_complete"
2301
2302 static int
2303 send_file_complete (guestfs_h *g)
2304
2305 Send a file complete chunk.
2306
2307 Function "lib/proto.c:recv_from_daemon"
2308
2309 static int
2310 recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
2311
2312 This function reads a single message, file chunk, launch flag or
2313 cancellation flag from the daemon. If something was read, it returns
2314 0, otherwise -1.
2315
2316 Both "size_rtn" and "buf_rtn" must be passed by the caller as non-NULL.
2317
2318 *size_rtn returns the size of the returned message or it may be
2319 "GUESTFS_LAUNCH_FLAG" or "GUESTFS_CANCEL_FLAG".
2320
2321 *buf_rtn is returned containing the message (if any) or will be set to
2322 "NULL". *buf_rtn must be freed by the caller.
2323
2324 This checks for EOF (appliance died) and passes that up through the
2325 child_cleanup function above.
2326
2327 Log message, progress messages are handled transparently here.
2328
2329 Function "lib/proto.c:guestfs_int_recv"
2330
2331 int
2332 guestfs_int_recv (guestfs_h *g, const char *fn,
2333 guestfs_message_header *hdr,
2334 guestfs_message_error *err,
2335 xdrproc_t xdrp, char *ret)
2336
2337 Receive a reply.
2338
2339 Function "lib/proto.c:guestfs_int_recv_discard"
2340
2341 int
2342 guestfs_int_recv_discard (guestfs_h *g, const char *fn)
2343
2344 Same as "guestfs_int_recv", but it discards the reply message.
2345
2346 Notes (XXX):
2347
2348 • This returns an int, but all current callers ignore it.
2349
2350 • The error string may end up being set twice on error paths.
2351
2352 Function "lib/proto.c:guestfs_int_recv_file"
2353
2354 int
2355 guestfs_int_recv_file (guestfs_h *g, const char *filename)
2356
2357 Returns -1 = error, 0 = EOF, ">0" = more data
2358
2359 Function "lib/proto.c:receive_file_data"
2360
2361 static ssize_t
2362 receive_file_data (guestfs_h *g, void **buf_r)
2363
2364 Receive a chunk of file data.
2365
2366 Returns -1 = error, 0 = EOF, ">0" = more data
2367
2368 File lib/qemu.c
2369
2370 Functions to handle qemu versions and features.
2371
2372 Function "lib/qemu.c:guestfs_int_test_qemu"
2373
2374 struct qemu_data *
2375 guestfs_int_test_qemu (guestfs_h *g)
2376
2377 Test that the qemu binary (or wrapper) runs, and do "qemu -help" and
2378 other commands so we can find out the version of qemu and what options
2379 this qemu supports.
2380
2381 This caches the results in the cachedir so that as long as the qemu
2382 binary does not change, calling this is effectively free.
2383
2384 Function "lib/qemu.c:cache_filename"
2385
2386 static char *
2387 cache_filename (guestfs_h *g, const char *cachedir,
2388 const struct stat *statbuf, const char *suffix)
2389
2390 Generate the filenames, for the stat file and the other cache files.
2391
2392 By including the size and mtime in the filename we also ensure that the
2393 same user can use multiple versions of qemu without conflicts.
2394
2395 Function "lib/qemu.c:parse_qemu_version"
2396
2397 static void
2398 parse_qemu_version (guestfs_h *g, const char *qemu_help,
2399 struct version *qemu_version)
2400
2401 Parse the first line of "qemu_help" into the major and minor version of
2402 qemu, but don't fail if parsing is not possible.
2403
2404 Function "lib/qemu.c:parse_json"
2405
2406 static void
2407 parse_json (guestfs_h *g, const char *json, json_t **treep)
2408
2409 Parse the json output from QMP. But don't fail if parsing is not
2410 possible.
2411
2412 Function "lib/qemu.c:parse_has_kvm"
2413
2414 static void
2415 parse_has_kvm (guestfs_h *g, const char *json, bool *ret)
2416
2417 Parse the json output from QMP query-kvm to find out if KVM is enabled
2418 on this machine. Don't fail if parsing is not possible, assume KVM is
2419 available.
2420
2421 The JSON output looks like: {"return": {"enabled": true, "present":
2422 true}}
2423
2424 Function "lib/qemu.c:generic_read_cache"
2425
2426 static int
2427 generic_read_cache (guestfs_h *g, const char *filename, char **strp)
2428
2429 Generic functions for reading and writing the cache files, used where
2430 we are just reading and writing plain text strings.
2431
2432 Function "lib/qemu.c:generic_qmp_test"
2433
2434 static int
2435 generic_qmp_test (guestfs_h *g, struct qemu_data *data,
2436 const char *qmp_command,
2437 char **outp)
2438
2439 Run a generic QMP test on the QEMU binary.
2440
2441 Function "lib/qemu.c:guestfs_int_qemu_version"
2442
2443 struct version
2444 guestfs_int_qemu_version (guestfs_h *g, struct qemu_data *data)
2445
2446 Return the parsed version of qemu.
2447
2448 Function "lib/qemu.c:guestfs_int_qemu_supports"
2449
2450 int
2451 guestfs_int_qemu_supports (guestfs_h *g, const struct qemu_data *data,
2452 const char *option)
2453
2454 Test if option is supported by qemu command line (just by grepping the
2455 help text).
2456
2457 Function "lib/qemu.c:guestfs_int_qemu_supports_device"
2458
2459 int
2460 guestfs_int_qemu_supports_device (guestfs_h *g,
2461 const struct qemu_data *data,
2462 const char *device_name)
2463
2464 Test if device is supported by qemu (currently just greps the "qemu
2465 -device ?" output).
2466
2467 Function "lib/qemu.c:guestfs_int_qemu_mandatory_locking"
2468
2469 int
2470 guestfs_int_qemu_mandatory_locking (guestfs_h *g,
2471 const struct qemu_data *data)
2472
2473 Test if the qemu binary uses mandatory file locking, added in QEMU >=
2474 2.10 (but sometimes disabled).
2475
2476 Function "lib/qemu.c:guestfs_int_qemu_escape_param"
2477
2478 char *
2479 guestfs_int_qemu_escape_param (guestfs_h *g, const char *param)
2480
2481 Escape a qemu parameter.
2482
2483 Every "," becomes ",,". The caller must free the returned string.
2484
2485 XXX This functionality is now only used when constructing a qemu-img
2486 command in lib/create.c. We should extend the qemuopts library to
2487 cover this use case.
2488
2489 Function "lib/qemu.c:guestfs_int_drive_source_qemu_param"
2490
2491 char *
2492 guestfs_int_drive_source_qemu_param (guestfs_h *g,
2493 const struct drive_source *src)
2494
2495 Useful function to format a drive + protocol for qemu.
2496
2497 Note that the qemu parameter is the bit after "file=". It is not
2498 escaped here, but would usually be escaped if passed to qemu as part of
2499 a full -drive parameter (but not for qemu-img(1)).
2500
2501 Function "lib/qemu.c:guestfs_int_discard_possible"
2502
2503 bool
2504 guestfs_int_discard_possible (guestfs_h *g, struct drive *drv,
2505 const struct version *qemu_version)
2506
2507 Test if discard is both supported by qemu AND possible with the
2508 underlying file or device. This returns 1 if discard is possible. It
2509 returns 0 if not possible and sets the error to the reason why.
2510
2511 This function is called when the user set "discard == "enable"".
2512
2513 Function "lib/qemu.c:guestfs_int_free_qemu_data"
2514
2515 void
2516 guestfs_int_free_qemu_data (struct qemu_data *data)
2517
2518 Free the "struct qemu_data".
2519
2520 File lib/rescue.c
2521
2522 Support for virt-rescue(1).
2523
2524 File lib/stringsbuf.c
2525
2526 An expandable NULL-terminated vector of strings (like "argv").
2527
2528 Use the "DECLARE_STRINGSBUF" macro to declare the stringsbuf.
2529
2530 Note: Don't confuse this with stringsbuf in the daemon which is a
2531 different type with different methods.
2532
2533 Function "lib/stringsbuf.c:guestfs_int_add_string_nodup"
2534
2535 void
2536 guestfs_int_add_string_nodup (guestfs_h *g, struct stringsbuf *sb, char *str)
2537
2538 Add a string to the end of the list.
2539
2540 This doesn't call strdup(3) on the string, so the string itself is
2541 stored inside the vector.
2542
2543 Function "lib/stringsbuf.c:guestfs_int_add_string"
2544
2545 void
2546 guestfs_int_add_string (guestfs_h *g, struct stringsbuf *sb, const char *str)
2547
2548 Add a string to the end of the list.
2549
2550 This makes a copy of the string.
2551
2552 Function "lib/stringsbuf.c:guestfs_int_add_sprintf"
2553
2554 void
2555 guestfs_int_add_sprintf (guestfs_h *g, struct stringsbuf *sb,
2556 const char *fs, ...)
2557
2558 Add a string to the end of the list.
2559
2560 Uses an sprintf-like format string when creating the string.
2561
2562 Function "lib/stringsbuf.c:guestfs_int_end_stringsbuf"
2563
2564 void
2565 guestfs_int_end_stringsbuf (guestfs_h *g, struct stringsbuf *sb)
2566
2567 Finish the string buffer.
2568
2569 This adds the terminating NULL to the end of the vector.
2570
2571 Function "lib/stringsbuf.c:guestfs_int_free_stringsbuf"
2572
2573 void
2574 guestfs_int_free_stringsbuf (struct stringsbuf *sb)
2575
2576 Free the string buffer and the strings.
2577
2578 File lib/tmpdirs.c
2579
2580 Handle temporary directories.
2581
2582 Function "lib/tmpdirs.c:set_abs_path"
2583
2584 static int
2585 set_abs_path (guestfs_h *g, const char *ctxstr,
2586 const char *tmpdir, char **tmpdir_ret)
2587
2588 We need to make all tmpdir paths absolute because lots of places in the
2589 code assume this. Do it at the time we set the path or read the
2590 environment variable (https://bugzilla.redhat.com/882417).
2591
2592 The "ctxstr" parameter is a string displayed in error messages giving
2593 the context of the operation (eg. name of environment variable being
2594 used, or API function being called).
2595
2596 Function "lib/tmpdirs.c:guestfs_impl_get_tmpdir"
2597
2598 char *
2599 guestfs_impl_get_tmpdir (guestfs_h *g)
2600
2601 Implements the "guestfs_get_tmpdir" API.
2602
2603 Note this actually calculates the tmpdir, so it never returns "NULL".
2604
2605 Function "lib/tmpdirs.c:guestfs_impl_get_cachedir"
2606
2607 char *
2608 guestfs_impl_get_cachedir (guestfs_h *g)
2609
2610 Implements the "guestfs_get_cachedir" API.
2611
2612 Note this actually calculates the cachedir, so it never returns "NULL".
2613
2614 Function "lib/tmpdirs.c:guestfs_impl_get_sockdir"
2615
2616 char *
2617 guestfs_impl_get_sockdir (guestfs_h *g)
2618
2619 Implements the "guestfs_get_sockdir" API.
2620
2621 Note this actually calculates the sockdir, so it never returns "NULL".
2622
2623 Function "lib/tmpdirs.c:guestfs_int_lazy_make_tmpdir"
2624
2625 int
2626 guestfs_int_lazy_make_tmpdir (guestfs_h *g)
2627
2628 The "g->tmpdir" (per-handle temporary directory) is not created when
2629 the handle is created. Instead we create it lazily before the first
2630 time it is used, or during launch.
2631
2632 Function "lib/tmpdirs.c:guestfs_int_make_temp_path"
2633
2634 char *
2635 guestfs_int_make_temp_path (guestfs_h *g,
2636 const char *name, const char *extension)
2637
2638 Generate unique temporary paths for temporary files.
2639
2640 Returns a unique path or NULL on error.
2641
2642 Function "lib/tmpdirs.c:guestfs_int_create_socketname"
2643
2644 int
2645 guestfs_int_create_socketname (guestfs_h *g, const char *filename,
2646 char (*sockpath)[UNIX_PATH_MAX])
2647
2648 Create the path for a socket with the selected filename in the sockdir.
2649
2650 Function "lib/tmpdirs.c:guestfs_int_make_pid_path"
2651
2652 char *
2653 guestfs_int_make_pid_path (guestfs_h *g, const char *name)
2654
2655 Generate unique paths for PID files.
2656
2657 Returns a unique path or NULL on error. On success, the pathname
2658 points under sockdir and not tmpdir; daemons that write PID files after
2659 dropping privileges may not have access to tmpdir.
2660
2661 Function "lib/tmpdirs.c:guestfs_int_lazy_make_supermin_appliance_dir"
2662
2663 char *
2664 guestfs_int_lazy_make_supermin_appliance_dir (guestfs_h *g)
2665
2666 Create the supermin appliance directory under cachedir, if it does not
2667 exist.
2668
2669 Sanity-check that the permissions on the cachedir are safe, in case it
2670 has been pre-created maliciously or tampered with.
2671
2672 Returns the directory name which the caller must free.
2673
2674 Function "lib/tmpdirs.c:guestfs_int_recursive_remove_dir"
2675
2676 void
2677 guestfs_int_recursive_remove_dir (guestfs_h *g, const char *dir)
2678
2679 Recursively remove a temporary directory. If removal fails, just
2680 return (it's a temporary directory so it'll eventually be cleaned up by
2681 a temp cleaner).
2682
2683 This is implemented using "rm -rf" because that's simpler and safer.
2684
2685 File lib/umask.c
2686
2687 Return current umask in a thread-safe way.
2688
2689 glibc documents, but does not actually implement, a "getumask(3)" call.
2690
2691 We use "Umask" from /proc/self/status for Linux ≥ 4.7. For older Linux
2692 and other Unix, this file implements an expensive but thread-safe way
2693 to get the current process's umask.
2694
2695 Thanks to: Josh Stone, Jiri Jaburek, Eric Blake.
2696
2697 Function "lib/umask.c:guestfs_int_getumask"
2698
2699 int
2700 guestfs_int_getumask (guestfs_h *g)
2701
2702 Returns the current process's umask. On failure, returns -1 and sets
2703 the error in the guestfs handle.
2704
2705 Function "lib/umask.c:get_umask_from_proc"
2706
2707 static int
2708 get_umask_from_proc (guestfs_h *g)
2709
2710 For Linux ≥ 4.7 get the umask from /proc/self/status.
2711
2712 On failure this returns -1. However if we could not open the /proc
2713 file or find the "Umask" entry in it, return -2 which causes the
2714 fallback path to run.
2715
2716 Function "lib/umask.c:get_umask_from_fork"
2717
2718 static int
2719 get_umask_from_fork (guestfs_h *g)
2720
2721 Fallback method of getting the umask using fork.
2722
2723 File lib/unit-tests.c
2724
2725 Unit tests of internal functions.
2726
2727 These tests may use a libguestfs handle, but must not launch the
2728 handle. Also, avoid long-running tests.
2729
2730 Function "lib/unit-tests.c:test_split"
2731
2732 static void
2733 test_split (void)
2734
2735 Test "guestfs_int_split_string".
2736
2737 Function "lib/unit-tests.c:test_concat"
2738
2739 static void
2740 test_concat (void)
2741
2742 Test "guestfs_int_concat_strings".
2743
2744 Function "lib/unit-tests.c:test_join"
2745
2746 static void
2747 test_join (void)
2748
2749 Test "guestfs_int_join_strings".
2750
2751 Function "lib/unit-tests.c:test_validate_guid"
2752
2753 static void
2754 test_validate_guid (void)
2755
2756 Test "guestfs_int_validate_guid".
2757
2758 Function "lib/unit-tests.c:test_drive_name"
2759
2760 static void
2761 test_drive_name (void)
2762
2763 Test "guestfs_int_drive_name".
2764
2765 Function "lib/unit-tests.c:test_drive_index"
2766
2767 static void
2768 test_drive_index (void)
2769
2770 Test "guestfs_int_drive_index".
2771
2772 Function "lib/unit-tests.c:test_getumask"
2773
2774 static void
2775 test_getumask (void)
2776
2777 Test "guestfs_int_getumask".
2778
2779 Function "lib/unit-tests.c:test_command"
2780
2781 static void
2782 test_command (void)
2783
2784 Test "guestfs_int_new_command" etc.
2785
2786 XXX These tests could be made much more thorough. So far we simply
2787 test that it's not obviously broken.
2788
2789 Function "lib/unit-tests.c:test_qemu_escape_param"
2790
2791 static void
2792 test_qemu_escape_param (void)
2793
2794 Test "guestfs_int_qemu_escape_param"
2795
2796 XXX I wanted to make this test run qemu, passing some parameters which
2797 need to be escaped, but I cannot think of a way to do that without
2798 launching a VM.
2799
2800 Function "lib/unit-tests.c:test_timeval_diff"
2801
2802 static void
2803 test_timeval_diff (void)
2804
2805 Test "guestfs_int_timeval_diff".
2806
2807 File lib/version.c
2808
2809 This file provides simple version number management.
2810
2811 Function "lib/version.c:guestfs_int_version_from_x_y"
2812
2813 int
2814 guestfs_int_version_from_x_y (guestfs_h *g, struct version *v, const char *str)
2815
2816 Parses a version from a string, looking for a "X.Y" pattern.
2817
2818 Returns -1 on failure (like failed integer parsing), 0 on missing
2819 match, and 1 on match and successful parsing. "v" is changed only on
2820 successful match.
2821
2822 Function "lib/version.c:guestfs_int_version_from_x_y_re"
2823
2824 int
2825 guestfs_int_version_from_x_y_re (guestfs_h *g, struct version *v,
2826 const char *str, const pcre2_code *re)
2827
2828 Parses a version from a string, using the specified "re" as regular
2829 expression which must provide (at least) two matches.
2830
2831 Returns -1 on failure (like failed integer parsing), 0 on missing
2832 match, and 1 on match and successful parsing. "v" is changed only on
2833 successful match.
2834
2835 Function "lib/version.c:guestfs_int_version_from_x_y_or_x"
2836
2837 int
2838 guestfs_int_version_from_x_y_or_x (guestfs_h *g, struct version *v,
2839 const char *str)
2840
2841 Parses a version from a string, either looking for a "X.Y" pattern or
2842 considering it as whole integer.
2843
2844 Returns -1 on failure (like failed integer parsing), 0 on missing
2845 match, and 1 on match and successful parsing. "v" is changed only on
2846 successful match.
2847
2848 Function "lib/version.c:guestfs_int_parse_unsigned_int"
2849
2850 int
2851 guestfs_int_parse_unsigned_int (guestfs_h *g, const char *str)
2852
2853 Parse small, unsigned ints, as used in version numbers.
2854
2855 This will fail with an error if trailing characters are found after the
2856 integer.
2857
2858 Returns ≥ 0 on success, or -1 on failure.
2859
2860 File lib/wait.c
2861
2862 Function "lib/wait.c:guestfs_int_waitpid"
2863
2864 int
2865 guestfs_int_waitpid (guestfs_h *g, pid_t pid, int *status, const char *errmsg)
2866
2867 A safe version of waitpid(3) which retries if "EINTR" is returned.
2868
2869 Note: this only needs to be used in the library, or in programs that
2870 install a non-restartable "SIGCHLD" handler (which is not the case for
2871 any current libguestfs virt tools).
2872
2873 If the main program installs a SIGCHLD handler and sets it to be non-
2874 restartable, then what can happen is the library is waiting in a wait
2875 syscall, the child exits, "SIGCHLD" is sent to the process, and the
2876 wait syscall returns "EINTR". Since the library cannot control the
2877 signal handler, we have to instead restart the wait syscall, which is
2878 the purpose of this wrapper.
2879
2880 Function "lib/wait.c:guestfs_int_waitpid_noerror"
2881
2882 void
2883 guestfs_int_waitpid_noerror (pid_t pid)
2884
2885 Like "guestfs_int_waitpid", but ignore errors.
2886
2887 Function "lib/wait.c:guestfs_int_wait4"
2888
2889 int
2890 guestfs_int_wait4 (guestfs_h *g, pid_t pid, int *status,
2891 struct rusage *rusage, const char *errmsg)
2892
2893 A safe version of wait4(2) which retries if "EINTR" is returned.
2894
2895 File lib/whole-file.c
2896
2897 Function "lib/whole-file.c:guestfs_int_read_whole_file"
2898
2899 int
2900 guestfs_int_read_whole_file (guestfs_h *g, const char *filename,
2901 char **data_r, size_t *size_r)
2902
2903 Read the whole file "filename" into a memory buffer.
2904
2905 The memory buffer is initialized and returned in "data_r". The size of
2906 the file in bytes is returned in "size_r". The return buffer must be
2907 freed by the caller.
2908
2909 On error this sets the error in the handle and returns -1.
2910
2911 For the convenience of callers, the returned buffer is NUL-terminated
2912 (the NUL is not included in the size).
2913
2914 The file must be a regular, local, trusted file. In particular, do not
2915 use this function to read files that might be under control of an
2916 untrusted user since that will lead to a denial-of-service attack.
2917
2918 Subdirectory common/edit
2919 File common/edit/file-edit.c
2920
2921 This file implements common file editing in a range of utilities
2922 including guestfish(1), virt-edit(1), virt-customize(1) and
2923 virt-builder(1).
2924
2925 It contains the code for both interactive-(editor-)based editing and
2926 non-interactive editing using Perl snippets.
2927
2928 Function "common/edit/file-edit.c:edit_file_editor"
2929
2930 int
2931 edit_file_editor (guestfs_h *g, const char *filename, const char *editor,
2932 const char *backup_extension, int verbose)
2933
2934 Edit "filename" using the specified "editor" application.
2935
2936 If "backup_extension" is not null, then a copy of "filename" is saved
2937 with "backup_extension" appended to its file name.
2938
2939 If "editor" is null, then the $EDITOR environment variable will be
2940 queried for the editor application, leaving "vi" as fallback if not
2941 set.
2942
2943 Returns -1 for failure, 0 on success, 1 if the editor did not change
2944 the file (e.g. the user closed the editor without saving).
2945
2946 Function "common/edit/file-edit.c:edit_file_perl"
2947
2948 int
2949 edit_file_perl (guestfs_h *g, const char *filename, const char *perl_expr,
2950 const char *backup_extension, int verbose)
2951
2952 Edit "filename" running the specified "perl_expr" using Perl.
2953
2954 If "backup_extension" is not null, then a copy of "filename" is saved
2955 with "backup_extension" appended to its file name.
2956
2957 Returns -1 for failure, 0 on success.
2958
2959 Subdirectory common/options
2960 File common/options/config.c
2961
2962 This file parses the guestfish configuration file, usually
2963 ~/.libguestfs-tools.rc or /etc/libguestfs-tools.conf.
2964
2965 Note that "parse_config" is called very early, before command line
2966 parsing, before the "verbose" flag has been set, even before the global
2967 handle "g" is opened.
2968
2969 File common/options/decrypt.c
2970
2971 This file implements the decryption of disk images, usually done before
2972 mounting their partitions.
2973
2974 Function "common/options/decrypt.c:make_mapname"
2975
2976 static char *
2977 make_mapname (const char *device)
2978
2979 Make a LUKS map name from the partition or logical volume name, eg.
2980 "/dev/vda2" => "cryptvda2", or "/dev/vg-ssd/lv-root7" =>
2981 "cryptvgssdlvroot7". Note that, in logical volume device names,
2982 c_isalnum() eliminates the "/" separator from between the VG and the
2983 LV, so this mapping is not unique; but for our purposes, it will do.
2984
2985 Function "common/options/decrypt.c:inspect_do_decrypt"
2986
2987 void
2988 inspect_do_decrypt (guestfs_h *g, struct key_store *ks)
2989
2990 Simple implementation of decryption: look for any encrypted partitions
2991 and decrypt them, then rescan for VGs.
2992
2993 File common/options/display-options.c
2994
2995 This file contains common code used to implement --short-options and
2996 --long-options in C virt tools. (The equivalent for OCaml virt tools
2997 is implemented by common/mltools/getopt.ml).
2998
2999 These "hidden" options are used to implement bash tab completion.
3000
3001 Function "common/options/display-options.c:display_short_options"
3002
3003 void
3004 display_short_options (const char *format)
3005
3006 Implements the internal "tool --short-options" flag, which just lists
3007 out the short options available. Used by bash completion.
3008
3009 Function "common/options/display-options.c:display_long_options"
3010
3011 void
3012 display_long_options (const struct option *long_options)
3013
3014 Implements the internal "tool --long-options" flag, which just lists
3015 out the long options available. Used by bash completion.
3016
3017 File common/options/domain.c
3018
3019 Implements the guestfish (and other tools) -d option.
3020
3021 Function "common/options/domain.c:add_libvirt_drives"
3022
3023 int
3024 add_libvirt_drives (guestfs_h *g, const char *guest)
3025
3026 This function is called when a user invokes "guestfish -d guest".
3027
3028 Returns the number of drives added ("> 0"), or -1 for failure.
3029
3030 File common/options/inspect.c
3031
3032 This file implements inspecting the guest and mounting the filesystems
3033 found in the right places. It is used by the guestfish(1) -i option
3034 and some utilities such as virt-cat(1).
3035
3036 Function "common/options/inspect.c:inspect_mount_handle"
3037
3038 void
3039 inspect_mount_handle (guestfs_h *g, struct key_store *ks)
3040
3041 This function implements the -i option.
3042
3043 Function "common/options/inspect.c:print_inspect_prompt"
3044
3045 void
3046 print_inspect_prompt (void)
3047
3048 This function is called only if "inspect_mount_root" was called, and
3049 only after we've printed the prompt in interactive mode.
3050
3051 File common/options/keys.c
3052
3053 Function "common/options/keys.c:read_key"
3054
3055 char *
3056 read_key (const char *param)
3057
3058 Read a passphrase ('Key') from /dev/tty with echo off.
3059
3060 The caller (fish/cmds.c) will call free on the string afterwards.
3061 Based on the code in cryptsetup file lib/utils.c.
3062
3063 File common/options/options.c
3064
3065 This file contains common options parsing code used by guestfish and
3066 many other tools which share a common options syntax.
3067
3068 For example, guestfish, virt-cat, virt-ls etc all support the -a
3069 option, and that is handled in all of those tools using a macro
3070 "OPTION_a" defined in fish/options.h.
3071
3072 There are a lot of common global variables used, "drvs" accumulates the
3073 list of drives, "verbose" for the -v flag, and many more.
3074
3075 Function "common/options/options.c:option_a"
3076
3077 void
3078 option_a (const char *arg, const char *format, int blocksize,
3079 struct drv **drvsp)
3080
3081 Handle the guestfish -a option on the command line.
3082
3083 Function "common/options/options.c:option_d"
3084
3085 void
3086 option_d (const char *arg, struct drv **drvsp)
3087
3088 Handle the -d option when passed on the command line.
3089
3090 Function "common/options/options.c:display_mountpoints_on_failure"
3091
3092 static void
3093 display_mountpoints_on_failure (const char *mp_device,
3094 const char *user_supplied_options)
3095
3096 If the -m option fails on any command, display a useful error message
3097 listing the mountpoints.
3098
3099 File common/options/uri.c
3100
3101 This file implements URI parsing for the -a option, in many utilities
3102 including guestfish(1), virt-cat(1), virt-builder(1),
3103 virt-customize(1), etc.
3104
3105 Subdirectory common/parallel
3106 File common/parallel/domains.c
3107
3108 This file is used by "virt-df" and some of the other tools when they
3109 are implicitly asked to operate over all libvirt domains (VMs), for
3110 example when "virt-df" is called without specifying any particular disk
3111 image.
3112
3113 It hides the complexity of querying the list of domains from libvirt.
3114
3115 Function "common/parallel/domains.c:free_domains"
3116
3117 void
3118 free_domains (void)
3119
3120 Frees up everything allocated by "get_all_libvirt_domains".
3121
3122 Function "common/parallel/domains.c:get_all_libvirt_domains"
3123
3124 void
3125 get_all_libvirt_domains (const char *libvirt_uri)
3126
3127 Read all libguest guests into the global variables "domains" and
3128 "nr_domains". The guests are ordered by name. This exits on any
3129 error.
3130
3131 File common/parallel/estimate-max-threads.c
3132
3133 Function "common/parallel/estimate-max-threads.c:estimate_max_threads"
3134
3135 size_t
3136 estimate_max_threads (void)
3137
3138 This function uses the output of "free -m" to estimate how many
3139 libguestfs appliances could be safely started in parallel. Note that
3140 it always returns ≥ 1.
3141
3142 Function "common/parallel/estimate-max-threads.c:read_line_from"
3143
3144 static char *
3145 read_line_from (const char *cmd)
3146
3147 Run external command and read the first line of output.
3148
3149 File common/parallel/parallel.c
3150
3151 This file is used by "virt-df" and some of the other tools when they
3152 need to run multiple parallel libguestfs instances to operate on a
3153 large number of libvirt domains efficiently.
3154
3155 It implements a multithreaded work queue. In addition it reorders the
3156 output so the output still appears in the same order as the input (ie.
3157 still ordered alphabetically).
3158
3159 Function "common/parallel/parallel.c:start_threads"
3160
3161 int
3162 start_threads (size_t option_P, guestfs_h *options_handle, work_fn work)
3163
3164 Run the threads and work through the global list of libvirt domains.
3165
3166 "option_P" is whatever the user passed in the -P option, or 0 if the
3167 user didn't use the -P option (in which case the number of threads is
3168 chosen heuristically).
3169
3170 "options_handle" (which may be "NULL") is the global guestfs handle
3171 created by the options mini-library.
3172
3173 The work function ("work") should do the work (inspecting the domain,
3174 etc.) on domain index "i". However it must not print out any result
3175 directly. Instead it prints anything it needs to the supplied "FILE
3176 *". The work function should return 0 on success or -1 on error.
3177
3178 The "start_threads" function returns 0 if all work items completed
3179 successfully, or -1 if there was an error.
3180
3181 Subdirectory common/progress
3182 File common/progress/progress.c
3183
3184 This file implements the progress bar in guestfish(1), virt-resize(1)
3185 and virt-sparsify(1).
3186
3187 Function "common/progress/progress.c:progress_bar_init"
3188
3189 struct progress_bar *
3190 progress_bar_init (unsigned flags)
3191
3192 Initialize a progress bar struct.
3193
3194 It is intended that you can reuse the same struct for multiple commands
3195 (but only in a single thread). Call "progress_bar_reset" before each
3196 new command.
3197
3198 Function "common/progress/progress.c:progress_bar_free"
3199
3200 void
3201 progress_bar_free (struct progress_bar *bar)
3202
3203 Free a progress bar struct.
3204
3205 Function "common/progress/progress.c:progress_bar_reset"
3206
3207 void
3208 progress_bar_reset (struct progress_bar *bar)
3209
3210 This function should be called just before you issue any command.
3211
3212 Function "common/progress/progress.c:estimate_remaining_time"
3213
3214 static double
3215 estimate_remaining_time (struct progress_bar *bar, double ratio)
3216
3217 Return remaining time estimate (in seconds) for current call.
3218
3219 This returns the running mean estimate of remaining time, but if the
3220 latest estimate of total time is greater than two s.d.'s from the
3221 running mean then we don't print anything because we're not confident
3222 that the estimate is meaningful. (Returned value is <0.0 when nothing
3223 should be printed).
3224
3225 Function "common/progress/progress.c:progress_bar_set"
3226
3227 void
3228 progress_bar_set (struct progress_bar *bar,
3229 uint64_t position, uint64_t total)
3230
3231 Set the position of the progress bar.
3232
3233 This should be called from a "GUESTFS_EVENT_PROGRESS" event callback.
3234
3235 Subdirectory common/qemuopts
3236 File common/qemuopts/qemuopts-tests.c
3237
3238 Unit tests of internal functions.
3239
3240 These tests may use a libguestfs handle, but must not launch the
3241 handle. Also, avoid long-running tests.
3242
3243 File common/qemuopts/qemuopts.c
3244
3245 Mini-library for writing qemu command lines and qemu config files.
3246
3247 There are some shortcomings with the model used for qemu options which
3248 aren't clear until you try to convert options into a configuration
3249 file. However if we attempted to model the options in more detail then
3250 this library would be both very difficult to use and incompatible with
3251 older versions of qemu. Hopefully the current model is a decent
3252 compromise.
3253
3254 For reference here are the problems:
3255
3256 • There's inconsistency in qemu between options and config file, eg.
3257 "-smp 4" becomes:
3258
3259 [smp-opts]
3260 cpus = "4"
3261
3262 • Similar to the previous point, you can write either "-smp 4" or
3263 "-smp cpus=4" (although this won't work in very old qemu). When
3264 generating a config file you need to know the implicit key name.
3265
3266 • In "-opt key=value,..." the "key" is really a tree/array specifier.
3267 The way this works is complicated but hinted at here:
3268 http://git.qemu.org/?p=qemu.git;a=blob;f=util/keyval.c;h=93d5db6b590427e412dfb172f1c406d6dd8958c1;hb=HEAD
3269
3270 • Some options are syntactic sugar. eg. "-kernel foo" is sugar for
3271 "-machine kernel=foo".
3272
3273 Function "common/qemuopts/qemuopts.c:qemuopts_create"
3274
3275 struct qemuopts *
3276 qemuopts_create (void)
3277
3278 Create an empty list of qemu options.
3279
3280 The caller must eventually free the list by calling "qemuopts_free".
3281
3282 Returns "NULL" on error, setting "errno".
3283
3284 Function "common/qemuopts/qemuopts.c:qemuopts_free"
3285
3286 void
3287 qemuopts_free (struct qemuopts *qopts)
3288
3289 Free the list of qemu options.
3290
3291 Function "common/qemuopts/qemuopts.c:qemuopts_add_flag"
3292
3293 int
3294 qemuopts_add_flag (struct qemuopts *qopts, const char *flag)
3295
3296 Add a command line flag which has no argument. eg:
3297
3298 qemuopts_add_flag (qopts, "-no-user-config");
3299
3300 Returns 0 on success. Returns -1 on error, setting "errno".
3301
3302 Function "common/qemuopts/qemuopts.c:qemuopts_add_arg"
3303
3304 int
3305 qemuopts_add_arg (struct qemuopts *qopts, const char *flag, const char *value)
3306
3307 Add a command line flag which has a single argument. eg:
3308
3309 qemuopts_add_arg (qopts, "-m", "1024");
3310
3311 Don't use this if the argument is a comma-separated list, since quoting
3312 will not be done properly. See "qemuopts_add_arg_list".
3313
3314 Returns 0 on success. Returns -1 on error, setting "errno".
3315
3316 Function "common/qemuopts/qemuopts.c:qemuopts_add_arg_format"
3317
3318 int
3319 qemuopts_add_arg_format (struct qemuopts *qopts, const char *flag,
3320 const char *fs, ...)
3321
3322 Add a command line flag which has a single formatted argument. eg:
3323
3324 qemuopts_add_arg_format (qopts, "-m", "%d", 1024);
3325
3326 Don't use this if the argument is a comma-separated list, since quoting
3327 will not be done properly. See "qemuopts_add_arg_list".
3328
3329 Returns 0 on success. Returns -1 on error, setting "errno".
3330
3331 Function "common/qemuopts/qemuopts.c:qemuopts_add_arg_noquote"
3332
3333 int
3334 qemuopts_add_arg_noquote (struct qemuopts *qopts, const char *flag,
3335 const char *value)
3336
3337 This is like "qemuopts_add_arg" except that no quoting is done on the
3338 value.
3339
3340 For "qemuopts_to_script" and "qemuopts_to_channel", this means that
3341 neither shell quoting nor qemu comma quoting is done on the value.
3342
3343 For "qemuopts_to_argv" this means that qemu comma quoting is not done.
3344
3345 "qemuopts_to_config*" will fail.
3346
3347 You should use this with great care.
3348
3349 Function "common/qemuopts/qemuopts.c:qemuopts_start_arg_list"
3350
3351 int
3352 qemuopts_start_arg_list (struct qemuopts *qopts, const char *flag)
3353
3354 Start an argument that takes a comma-separated list of fields.
3355
3356 Typical usage is like this (with error handling omitted):
3357
3358 qemuopts_start_arg_list (qopts, "-drive");
3359 qemuopts_append_arg_list (qopts, "file=foo");
3360 qemuopts_append_arg_list_format (qopts, "if=%s", "ide");
3361 qemuopts_end_arg_list (qopts);
3362
3363 which would construct "-drive file=foo,if=ide"
3364
3365 See also "qemuopts_add_arg_list" for a way to do simple cases in one
3366 call.
3367
3368 Returns 0 on success. Returns -1 on error, setting "errno".
3369
3370 Function "common/qemuopts/qemuopts.c:qemuopts_add_arg_list"
3371
3372 int
3373 qemuopts_add_arg_list (struct qemuopts *qopts, const char *flag,
3374 const char *elem0, ...)
3375
3376 Add a command line flag which has a list of arguments. eg:
3377
3378 qemuopts_add_arg_list (qopts, "-drive", "file=foo", "if=ide", NULL);
3379
3380 This is turned into a comma-separated list, like: "-drive
3381 file=foo,if=ide". Note that this handles qemu quoting properly, so
3382 individual elements may contain commas and this will do the right
3383 thing.
3384
3385 Returns 0 on success. Returns -1 on error, setting "errno".
3386
3387 Function "common/qemuopts/qemuopts.c:qemuopts_set_binary"
3388
3389 int
3390 qemuopts_set_binary (struct qemuopts *qopts, const char *binary)
3391
3392 Set the qemu binary name.
3393
3394 Returns 0 on success. Returns -1 on error, setting "errno".
3395
3396 Function "common/qemuopts/qemuopts.c:qemuopts_set_binary_by_arch"
3397
3398 int
3399 qemuopts_set_binary_by_arch (struct qemuopts *qopts, const char *arch)
3400
3401 Set the qemu binary name to "qemu-system-[arch]".
3402
3403 As a special case if "arch" is "NULL", the binary is set to the KVM
3404 binary for the current host architecture:
3405
3406 qemuopts_set_binary_by_arch (qopts, NULL);
3407
3408 Returns 0 on success. Returns -1 on error, setting "errno".
3409
3410 Function "common/qemuopts/qemuopts.c:qemuopts_to_script"
3411
3412 int
3413 qemuopts_to_script (struct qemuopts *qopts, const char *filename)
3414
3415 Write the qemu options to a script.
3416
3417 "qemuopts_set_binary*" must be called first.
3418
3419 The script file will start with "#!/bin/sh" and will be chmod to mode
3420 0755.
3421
3422 Returns 0 on success. Returns -1 on error, setting "errno".
3423
3424 Function "common/qemuopts/qemuopts.c:shell_quote"
3425
3426 static void
3427 shell_quote (const char *str, FILE *fp)
3428
3429 Print "str" to "fp", shell-quoting it if necessary.
3430
3431 Function "common/qemuopts/qemuopts.c:shell_and_comma_quote"
3432
3433 static void
3434 shell_and_comma_quote (const char *str, FILE *fp)
3435
3436 Print "str" to "fp" doing both shell and qemu comma quoting.
3437
3438 Function "common/qemuopts/qemuopts.c:qemuopts_to_channel"
3439
3440 int
3441 qemuopts_to_channel (struct qemuopts *qopts, FILE *fp)
3442
3443 Write the qemu options to a "FILE *fp".
3444
3445 "qemuopts_set_binary*" must be called first.
3446
3447 Only the qemu command line is written. The caller may need to add
3448 "#!/bin/sh" and may need to chmod the resulting file to 0755.
3449
3450 Returns 0 on success. Returns -1 on error, setting "errno".
3451
3452 Function "common/qemuopts/qemuopts.c:qemuopts_to_argv"
3453
3454 char **
3455 qemuopts_to_argv (struct qemuopts *qopts)
3456
3457 Return a NULL-terminated argument list, of the kind that can be passed
3458 directly to execv(3).
3459
3460 "qemuopts_set_binary*" must be called first. It will be returned as
3461 "argv[0]" in the returned list.
3462
3463 The list of strings and the strings themselves must be freed by the
3464 caller.
3465
3466 Returns "NULL" on error, setting "errno".
3467
3468 Function "common/qemuopts/qemuopts.c:qemuopts_to_config_file"
3469
3470 int
3471 qemuopts_to_config_file (struct qemuopts *qopts, const char *filename)
3472
3473 Write the qemu options to a qemu config file, suitable for reading in
3474 using "qemu -readconfig filename".
3475
3476 Note that qemu config files have limitations on content and quoting, so
3477 not all qemuopts structs can be written (this function returns an error
3478 in these cases). For more information see
3479 https://habkost.net/posts/2016/12/qemu-apis-qemuopts.html
3480 https://bugs.launchpad.net/qemu/+bug/1686364
3481
3482 Also, command line argument names and config file sections sometimes
3483 have different names. For example the equivalent of "-m 1024" is:
3484
3485 [memory]
3486 size = "1024"
3487
3488 This code does not attempt to convert between the two forms. You just
3489 need to know how to do that yourself.
3490
3491 Returns 0 on success. Returns -1 on error, setting "errno".
3492
3493 Function "common/qemuopts/qemuopts.c:qemuopts_to_config_channel"
3494
3495 int
3496 qemuopts_to_config_channel (struct qemuopts *qopts, FILE *fp)
3497
3498 Same as "qemuopts_to_config_file", but this writes to a "FILE *fp".
3499
3500 Subdirectory common/utils
3501 File common/utils/cleanups.c
3502
3503 Libguestfs uses "CLEANUP_*" macros to simplify temporary allocations.
3504 They are implemented using the "__attribute__((cleanup))" feature of
3505 gcc and clang. Typical usage is:
3506
3507 fn ()
3508 {
3509 CLEANUP_FREE char *str = NULL;
3510 str = safe_asprintf (g, "foo");
3511 // str is freed automatically when the function returns
3512 }
3513
3514 There are a few catches to be aware of with the cleanup mechanism:
3515
3516 • If a cleanup variable is not initialized, then you can end up
3517 calling free(3) with an undefined value, resulting in the program
3518 crashing. For this reason, you should usually initialize every
3519 cleanup variable with something, eg. "NULL"
3520
3521 • Don't mark variables holding return values as cleanup variables.
3522
3523 • The main() function shouldn't use cleanup variables since it is
3524 normally exited by calling exit(3), and that doesn't call the
3525 cleanup handlers.
3526
3527 The functions in this file are used internally by the "CLEANUP_*"
3528 macros. Don't call them directly.
3529
3530 File common/utils/gnulib-cleanups.c
3531
3532 Libguestfs uses "CLEANUP_*" macros to simplify temporary allocations.
3533 They are implemented using the "__attribute__((cleanup))" feature of
3534 gcc and clang. Typical usage is:
3535
3536 fn ()
3537 {
3538 CLEANUP_FREE char *str = NULL;
3539 str = safe_asprintf (g, "foo");
3540 // str is freed automatically when the function returns
3541 }
3542
3543 There are a few catches to be aware of with the cleanup mechanism:
3544
3545 • If a cleanup variable is not initialized, then you can end up
3546 calling free(3) with an undefined value, resulting in the program
3547 crashing. For this reason, you should usually initialize every
3548 cleanup variable with something, eg. "NULL"
3549
3550 • Don't mark variables holding return values as cleanup variables.
3551
3552 • The main() function shouldn't use cleanup variables since it is
3553 normally exited by calling exit(3), and that doesn't call the
3554 cleanup handlers.
3555
3556 The functions in this file are used internally by the "CLEANUP_*"
3557 macros. Don't call them directly.
3558
3559 File common/utils/guestfs-utils.h
3560
3561 This header file is included in all "frontend" parts of libguestfs,
3562 namely the library, non-C language bindings, virt tools and tests.
3563
3564 The daemon does not use this header. If you need a place to put
3565 something shared with absolutely everything including the daemon, put
3566 it in lib/guestfs-internal-all.h
3567
3568 If a definition is only needed by a single component of libguestfs (eg.
3569 just the library, or just a single virt tool) then it should not be
3570 here!
3571
3572 File common/utils/libxml2-writer-macros.h
3573
3574 These macros make it easier to write XML. To use them correctly you
3575 must be aware of these assumptions:
3576
3577 • The "xmlTextWriterPtr" is called "xo". It is used implicitly by
3578 all the macros.
3579
3580 • On failure, a function called "xml_error" is called which you must
3581 define (usually as a macro). You must use "CLEANUP_*" macros in
3582 your functions if you want correct cleanup of local variables along
3583 the error path.
3584
3585 • All the "bad" casting is hidden inside the macros.
3586
3587 Definition "common/utils/libxml2-writer-macros.h:start_element"
3588
3589 #define start_element
3590
3591 To define an XML element use:
3592
3593 start_element ("name") {
3594 ...
3595 } end_element ();
3596
3597 which produces "<name>...</name>"
3598
3599 Definition "common/utils/libxml2-writer-macros.h:empty_element"
3600
3601 #define empty_element
3602
3603 To define an empty element:
3604
3605 empty_element ("name");
3606
3607 which produces "<name/>"
3608
3609 Definition "common/utils/libxml2-writer-macros.h:single_element"
3610
3611 #define single_element
3612
3613 To define a single element with no attributes containing some text:
3614
3615 single_element ("name", text);
3616
3617 which produces "<name>text</name>"
3618
3619 Definition "common/utils/libxml2-writer-macros.h:single_element_format"
3620
3621 #define single_element_format
3622
3623 To define a single element with no attributes containing some text
3624 using a format string:
3625
3626 single_element_format ("cores", "%d", nr_cores);
3627
3628 which produces "<cores>4</cores>"
3629
3630 Definition "common/utils/libxml2-writer-macros.h:attribute"
3631
3632 #define attribute
3633
3634 To define an XML element with attributes, use:
3635
3636 start_element ("name") {
3637 attribute ("foo", "bar");
3638 attribute_format ("count", "%d", count);
3639 ...
3640 } end_element ();
3641
3642 which produces "<name foo="bar" count="123">...</name>"
3643
3644 Definition "common/utils/libxml2-writer-macros.h:attribute_ns"
3645
3646 #define attribute_ns
3647
3648 "attribute_ns (prefix, key, namespace_uri, value)" defines a namespaced
3649 attribute.
3650
3651 Definition "common/utils/libxml2-writer-macros.h:string"
3652
3653 #define string
3654
3655 To define a verbatim string, use:
3656
3657 string ("hello");
3658
3659 Definition "common/utils/libxml2-writer-macros.h:string_format"
3660
3661 #define string_format
3662
3663 To define a verbatim string using a format string, use:
3664
3665 string ("%s, world", greeting);
3666
3667 Definition "common/utils/libxml2-writer-macros.h:base64"
3668
3669 #define base64
3670
3671 To write a string encoded as base64:
3672
3673 base64 (data, size);
3674
3675 Definition "common/utils/libxml2-writer-macros.h:comment"
3676
3677 #define comment
3678
3679 To define a comment in the XML, use:
3680
3681 comment ("number of items = %d", nr_items);
3682
3683 File common/utils/stringlists-utils.c
3684
3685 Utility functions used by the library, tools and language bindings.
3686
3687 These functions must not call internal library functions such as
3688 "safe_*", "error" or "perrorf", or any "guestfs_int_*".
3689
3690 Function "common/utils/stringlists-utils.c:guestfs_int_split_string"
3691
3692 char **
3693 guestfs_int_split_string (char sep, const char *str)
3694
3695 Split string at separator character "sep", returning the list of
3696 strings. Returns "NULL" on memory allocation failure.
3697
3698 Note (assuming "sep" is ":"):
3699
3700 "str == NULL"
3701 aborts
3702
3703 "str == """
3704 returns "[]"
3705
3706 "str == "abc""
3707 returns "["abc"]"
3708
3709 "str == ":""
3710 returns "["", ""]"
3711
3712 File common/utils/utils.c
3713
3714 Utility functions used by the library, tools and language bindings.
3715
3716 These functions must not call internal library functions such as
3717 "safe_*", "error" or "perrorf", or any "guestfs_int_*".
3718
3719 Function "common/utils/utils.c:guestfs_int_replace_string"
3720
3721 char *
3722 guestfs_int_replace_string (const char *str, const char *s1, const char *s2)
3723
3724 Replace every instance of "s1" appearing in "str" with "s2". A newly
3725 allocated string is returned which must be freed by the caller. If
3726 allocation fails this can return "NULL".
3727
3728 For example:
3729
3730 replace_string ("abcabb", "ab", "a");
3731
3732 would return "acab".
3733
3734 Function "common/utils/utils.c:guestfs_int_exit_status_to_string"
3735
3736 char *
3737 guestfs_int_exit_status_to_string (int status, const char *cmd_name,
3738 char *buffer, size_t buflen)
3739
3740 Translate a wait/system exit status into a printable string.
3741
3742 Function "common/utils/utils.c:guestfs_int_random_string"
3743
3744 int
3745 guestfs_int_random_string (char *ret, size_t len)
3746
3747 Return a random string of characters.
3748
3749 Notes:
3750
3751 • The "ret" buffer must have length "len+1" in order to store the
3752 final "\0" character.
3753
3754 • There is about 5 bits of randomness per output character (so about
3755 "5*len" bits of randomness in the resulting string).
3756
3757 Function "common/utils/utils.c:guestfs_int_drive_name"
3758
3759 char *
3760 guestfs_int_drive_name (size_t index, char *ret)
3761
3762 This turns a drive index (eg. 27) into a drive name (eg. "ab").
3763
3764 Drive indexes count from 0. The return buffer has to be large enough
3765 for the resulting string, and the returned pointer points to the *end*
3766 of the string.
3767
3768 https://rwmj.wordpress.com/2011/01/09/how-are-linux-drives-named-beyond-drive-26-devsdz/
3769
3770 Function "common/utils/utils.c:guestfs_int_drive_index"
3771
3772 ssize_t
3773 guestfs_int_drive_index (const char *name)
3774
3775 The opposite of "guestfs_int_drive_name". Take a string like "ab" and
3776 return the index (eg 27).
3777
3778 Note that you must remove any prefix such as "hd", "sd" etc, or any
3779 partition number before calling the function.
3780
3781 Function "common/utils/utils.c:guestfs_int_is_true"
3782
3783 int
3784 guestfs_int_is_true (const char *str)
3785
3786 Similar to "Tcl_GetBoolean".
3787
3788 Function "common/utils/utils.c:guestfs_int_string_is_valid"
3789
3790 bool
3791 guestfs_int_string_is_valid (const char *str,
3792 size_t min_length, size_t max_length,
3793 int flags, const char *extra)
3794
3795 Check a string for validity, that it contains only certain characters,
3796 and minimum and maximum length. This function is usually wrapped in a
3797 VALID_* macro, see lib/drives.c for an example.
3798
3799 "str" is the string to check.
3800
3801 "min_length" and "max_length" are the minimum and maximum length
3802 checks. 0 means no check.
3803
3804 The flags control:
3805
3806 "VALID_FLAG_ALPHA"
3807 7-bit ASCII-only alphabetic characters are permitted.
3808
3809 "VALID_FLAG_DIGIT"
3810 7-bit ASCII-only digits are permitted.
3811
3812 "extra" is a set of extra characters permitted, in addition to
3813 alphabetic and/or digits. ("extra = NULL" for no extra).
3814
3815 Returns boolean "true" if the string is valid (passes all the tests),
3816 or "false" if not.
3817
3818 Function "common/utils/utils.c:guestfs_int_fadvise_normal"
3819
3820 void
3821 guestfs_int_fadvise_normal (int fd)
3822
3823 Hint that we will read or write the file descriptor normally.
3824
3825 On Linux, this clears the "FMODE_RANDOM" flag on the file [see below]
3826 and sets the per-file number of readahead pages to equal the block
3827 device readahead setting.
3828
3829 It's OK to call this on a non-file since we ignore failure as it is
3830 only a hint.
3831
3832 Function "common/utils/utils.c:guestfs_int_fadvise_sequential"
3833
3834 void
3835 guestfs_int_fadvise_sequential (int fd)
3836
3837 Hint that we will read or write the file descriptor sequentially.
3838
3839 On Linux, this clears the "FMODE_RANDOM" flag on the file [see below]
3840 and sets the per-file number of readahead pages to twice the block
3841 device readahead setting.
3842
3843 It's OK to call this on a non-file since we ignore failure as it is
3844 only a hint.
3845
3846 Function "common/utils/utils.c:guestfs_int_fadvise_random"
3847
3848 void
3849 guestfs_int_fadvise_random (int fd)
3850
3851 Hint that we will read or write the file descriptor randomly.
3852
3853 On Linux, this sets the "FMODE_RANDOM" flag on the file. The effect of
3854 this flag is to:
3855
3856 • Disable normal sequential file readahead.
3857
3858 • If any read of the file is done which misses in the page cache, 2MB
3859 are read into the page cache. [I think - I'm not sure I totally
3860 understand what this is doing]
3861
3862 It's OK to call this on a non-file since we ignore failure as it is
3863 only a hint.
3864
3865 Function "common/utils/utils.c:guestfs_int_fadvise_noreuse"
3866
3867 void
3868 guestfs_int_fadvise_noreuse (int fd)
3869
3870 Hint that we will access the data only once.
3871
3872 On Linux, this does nothing.
3873
3874 It's OK to call this on a non-file since we ignore failure as it is
3875 only a hint.
3876
3877 Function "common/utils/utils.c:guestfs_int_fadvise_dontneed"
3878
3879 void
3880 guestfs_int_fadvise_dontneed (int fd)
3881
3882 Hint that we will not access the data in the near future.
3883
3884 On Linux, this immediately writes out any dirty pages in the page cache
3885 and then invalidates (drops) all pages associated with this file from
3886 the page cache. Apparently it does this even if the file is opened or
3887 being used by other processes. This setting is not persistent; if you
3888 subsequently read the file it will be cached in the page cache as
3889 normal.
3890
3891 It's OK to call this on a non-file since we ignore failure as it is
3892 only a hint.
3893
3894 Function "common/utils/utils.c:guestfs_int_fadvise_willneed"
3895
3896 void
3897 guestfs_int_fadvise_willneed (int fd)
3898
3899 Hint that we will access the data in the near future.
3900
3901 On Linux, this immediately reads the whole file into the page cache.
3902 This setting is not persistent; subsequently pages may be dropped from
3903 the page cache as normal.
3904
3905 It's OK to call this on a non-file since we ignore failure as it is
3906 only a hint.
3907
3908 Function "common/utils/utils.c:guestfs_int_shell_unquote"
3909
3910 char *
3911 guestfs_int_shell_unquote (const char *str)
3912
3913 Unquote a shell-quoted string.
3914
3915 Augeas passes strings to us which may be quoted, eg. if they come from
3916 files in /etc/sysconfig. This function can do simple unquoting of
3917 these strings.
3918
3919 Note this function does not do variable substitution, since that is
3920 impossible without knowing the file context and indeed the environment
3921 under which the shell script is run. Configuration files should not
3922 use complex quoting.
3923
3924 "str" is the input string from Augeas, a string that may be single- or
3925 double-quoted or may not be quoted. The returned string is unquoted,
3926 and must be freed by the caller. "NULL" is returned on error and
3927 "errno" is set accordingly.
3928
3929 For information on double-quoting in bash, see
3930 https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
3931
3932 Function "common/utils/utils.c:guestfs_int_is_reg"
3933
3934 int
3935 guestfs_int_is_reg (int64_t mode)
3936
3937 Return true if the "guestfs_statns" or "guestfs_lstatns" "st_mode"
3938 field represents a regular file.
3939
3940 Function "common/utils/utils.c:guestfs_int_is_dir"
3941
3942 int
3943 guestfs_int_is_dir (int64_t mode)
3944
3945 Return true if the "guestfs_statns" or "guestfs_lstatns" "st_mode"
3946 field represents a directory.
3947
3948 Function "common/utils/utils.c:guestfs_int_is_chr"
3949
3950 int
3951 guestfs_int_is_chr (int64_t mode)
3952
3953 Return true if the "guestfs_statns" or "guestfs_lstatns" "st_mode"
3954 field represents a char device.
3955
3956 Function "common/utils/utils.c:guestfs_int_is_blk"
3957
3958 int
3959 guestfs_int_is_blk (int64_t mode)
3960
3961 Return true if the "guestfs_statns" or "guestfs_lstatns" "st_mode"
3962 field represents a block device.
3963
3964 Function "common/utils/utils.c:guestfs_int_is_fifo"
3965
3966 int
3967 guestfs_int_is_fifo (int64_t mode)
3968
3969 Return true if the "guestfs_statns" or "guestfs_lstatns" "st_mode"
3970 field represents a named pipe (FIFO).
3971
3972 Function "common/utils/utils.c:guestfs_int_is_lnk"
3973
3974 int
3975 guestfs_int_is_lnk (int64_t mode)
3976
3977 Return true if the "guestfs_statns" or "guestfs_lstatns" "st_mode"
3978 field represents a symbolic link.
3979
3980 Function "common/utils/utils.c:guestfs_int_is_sock"
3981
3982 int
3983 guestfs_int_is_sock (int64_t mode)
3984
3985 Return true if the "guestfs_statns" or "guestfs_lstatns" "st_mode"
3986 field represents a Unix domain socket.
3987
3988 Function "common/utils/utils.c:guestfs_int_full_path"
3989
3990 char *
3991 guestfs_int_full_path (const char *dir, const char *name)
3992
3993 Concatenate "dir" and "name" to create a path. This correctly handles
3994 the case of concatenating "/" + "filename" as well as "/dir" +
3995 "filename". "name" may be "NULL".
3996
3997 The caller must free the returned path.
3998
3999 This function sets "errno" and returns "NULL" on error.
4000
4001 Function "common/utils/utils.c:guestfs_int_hexdump"
4002
4003 void
4004 guestfs_int_hexdump (const void *data, size_t len, FILE *fp)
4005
4006 Hexdump a block of memory to "FILE *", used for debugging.
4007
4008 Function "common/utils/utils.c:guestfs_int_strerror"
4009
4010 const char *
4011 guestfs_int_strerror (int errnum, char *buf, size_t buflen)
4012
4013 Thread-safe strerror_r.
4014
4015 This is a wrapper around the two variants of strerror_r(3) in glibc
4016 since it is hard to use correctly (RHBZ#2030396).
4017
4018 The buffer passed in should be large enough to store the error message
4019 (256 chars at least) and should be non-static. Note that the buffer
4020 might not be used, use the return value.
4021
4022 Subdirectory common/visit
4023 File common/visit/visit.c
4024
4025 This file contains a recursive function for visiting all files and
4026 directories in a guestfs filesystem.
4027
4028 Adapted from
4029 https://rwmj.wordpress.com/2010/12/15/tip-audit-virtual-machine-for-setuid-files/
4030
4031 Function "common/visit/visit.c:visit"
4032
4033 int
4034 visit (guestfs_h *g, const char *dir, visitor_function f, void *opaque)
4035
4036 Visit every file and directory in a guestfs filesystem, starting at
4037 "dir".
4038
4039 "dir" may be "/" to visit the entire filesystem, or may be some
4040 subdirectory. Symbolic links are not followed.
4041
4042 The visitor function "f" is called once for every directory and every
4043 file. The parameters passed to "f" include the current directory name,
4044 the current file name (or "NULL" when we're visiting a directory), the
4045 "guestfs_statns" (file permissions etc), and the list of extended
4046 attributes of the file. The visitor function may return -1 which
4047 causes the whole recursion to stop with an error.
4048
4049 Also passed to this function is an "opaque" pointer which is passed
4050 through to the visitor function.
4051
4052 Returns 0 if everything went OK, or -1 if there was an error. Error
4053 handling is not particularly well defined. It will either set an error
4054 in the libguestfs handle or print an error on stderr, but there is no
4055 way for the caller to tell the difference.
4056
4057 Subdirectory common/windows
4058 File common/windows/windows.c
4059
4060 This file implements "win:" Windows file path support in guestfish(1).
4061
4062 Function "common/windows/windows.c:is_windows"
4063
4064 int
4065 is_windows (guestfs_h *g, const char *root)
4066
4067 Checks whether "root" is a Windows installation.
4068
4069 This relies on an already being done introspection.
4070
4071 Function "common/windows/windows.c:windows_path"
4072
4073 char *
4074 windows_path (guestfs_h *g, const char *root, const char *path, int readonly)
4075
4076 Resolves "path" as possible Windows path according to "root", giving a
4077 new path that can be used in libguestfs API calls.
4078
4079 Notes:
4080
4081 • "root" must be a Windows installation
4082
4083 • relies on an already being done introspection
4084
4085 • will unmount all the existing mount points and mount the Windows
4086 root (according to "readonly")
4087
4088 • calls exit(3) on memory allocation failures
4089
4090 Subdirectory daemon
4091 File daemon/command.c
4092
4093 This file contains a number of useful functions for running external
4094 commands and capturing their output.
4095
4096 Function "daemon/command.c:commandf"
4097
4098 int
4099 commandf (char **stdoutput, char **stderror, unsigned flags,
4100 const char *name, ...)
4101
4102 Run a command. Optionally capture stdout and stderr as strings.
4103
4104 Returns 0 if the command ran successfully, or -1 if there was any
4105 error.
4106
4107 For a description of the "flags" see "commandrvf".
4108
4109 There is also a macro "command(out,err,name,...)" which calls
4110 "commandf" with "flags=0".
4111
4112 Function "daemon/command.c:commandrf"
4113
4114 int
4115 commandrf (char **stdoutput, char **stderror, unsigned flags,
4116 const char *name, ...)
4117
4118 Same as "command", but we allow the status code from the subcommand to
4119 be non-zero, and return that status code.
4120
4121 We still return -1 if there was some other error.
4122
4123 There is also a macro "commandr(out,err,name,...)" which calls
4124 "commandrf" with "flags=0".
4125
4126 Function "daemon/command.c:commandvf"
4127
4128 int
4129 commandvf (char **stdoutput, char **stderror, unsigned flags,
4130 char const *const *argv)
4131
4132 Same as "command", but passing in an argv array.
4133
4134 There is also a macro "commandv(out,err,argv)" which calls "commandvf"
4135 with "flags=0".
4136
4137 Function "daemon/command.c:commandrvf"
4138
4139 int
4140 commandrvf (char **stdoutput, char **stderror, unsigned flags,
4141 char const* const *argv)
4142
4143 This is a more sane version of system(3) for running external commands.
4144 It uses fork/execvp, so we don't need to worry about quoting of
4145 parameters, and it allows us to capture any error messages in a buffer.
4146
4147 If "stdoutput" is not "NULL", then *stdoutput will return the stdout of
4148 the command as a string.
4149
4150 If "stderror" is not "NULL", then *stderror will return the stderr of
4151 the command. If there is a final \n character, it is removed so you
4152 can use the error string directly in a call to "reply_with_error".
4153
4154 Flags are:
4155
4156 "COMMAND_FLAG_FOLD_STDOUT_ON_STDERR"
4157 For broken external commands that send error messages to stdout
4158 (hello, parted) but that don't have any useful stdout information,
4159 use this flag to capture the error messages in the *stderror
4160 buffer. If using this flag, you should pass "stdoutput=NULL"
4161 because nothing could ever be captured in that buffer.
4162
4163 "COMMAND_FLAG_CHROOT_COPY_FILE_TO_STDIN"
4164 For running external commands on chrooted files correctly (see
4165 https://bugzilla.redhat.com/579608) specifying this flag causes
4166 another process to be forked which chroots into sysroot and just
4167 copies the input file to stdin of the specified command. The file
4168 descriptor is ORed with the flags, and that file descriptor is
4169 always closed by this function. See daemon/hexdump.c for an
4170 example of usage.
4171
4172 There is also a macro "commandrv(out,err,argv)" which calls
4173 "commandrvf" with "flags=0".
4174
4175 File daemon/device-name-translation.c
4176
4177 Function
4178 "daemon/device-name-translation.c:device_name_translation_init"
4179
4180 void
4181 device_name_translation_init (void)
4182
4183 Cache daemon disk mapping.
4184
4185 When the daemon starts up, populate a cache with the contents of
4186 /dev/disk/by-path. It's easiest to use "ls -lv" here since the names
4187 are sorted awkwardly.
4188
4189 Function "daemon/device-name-translation.c:device_name_translation"
4190
4191 char *
4192 device_name_translation (const char *device)
4193
4194 Perform device name translation.
4195
4196 Libguestfs defines a few standard formats for device names. (see also
4197 "BLOCK DEVICE NAMING" in guestfs(3) and "guestfs_canonical_device_name"
4198 in guestfs(3)). They are:
4199
4200 /dev/sdX[N]
4201 /dev/hdX[N]
4202 /dev/vdX[N]
4203 These mean the Nth partition on the Xth device. Because Linux no
4204 longer enumerates devices in the order they are passed to qemu, we
4205 must translate these by looking up the actual device using
4206 /dev/disk/by-path/
4207
4208 /dev/mdX
4209 /dev/VG/LV
4210 /dev/mapper/...
4211 /dev/dm-N
4212 These are not translated here.
4213
4214 It returns a newly allocated string which the caller must free.
4215
4216 It returns "NULL" on error. Note it does not call "reply_with_*".
4217
4218 We have to open the device and test for "ENXIO", because the device
4219 nodes may exist in the appliance.
4220
4221 File daemon/guestfsd.c
4222
4223 This is the guestfs daemon which runs inside the guestfs appliance.
4224 This file handles start up and connecting back to the library.
4225
4226 Function "daemon/guestfsd.c:shell_quote"
4227
4228 void
4229 shell_quote (const char *str, FILE *fp)
4230
4231 Write "str" to the file "fp", ensuring it is shell quoted.
4232
4233 Function "daemon/guestfsd.c:sysroot_shell_quote"
4234
4235 void
4236 sysroot_shell_quote (const char *path, FILE *fp)
4237
4238 Write "sysroot" + "path" to the file "fp", ensuring it is shell quoted.
4239 The path must be an absolute path.
4240
4241 File daemon/internal.c
4242
4243 Internal functions that are not part of the public API.
4244
4245 File daemon/utils-c.c
4246
4247 Bindings for utility functions.
4248
4249 Note that functions called from OCaml code must never call any of the
4250 "reply*" functions.
4251
4252 File daemon/utils.c
4253
4254 Miscellaneous utility functions used by the daemon.
4255
4256 Function "daemon/utils.c:is_root_device_stat"
4257
4258 static int
4259 is_root_device_stat (struct stat *statbuf)
4260
4261 Return true iff device is the root device (and therefore should be
4262 ignored from the point of view of user calls).
4263
4264 Function "daemon/utils.c:is_device_parameter"
4265
4266 int
4267 is_device_parameter (const char *device)
4268
4269 Parameters marked as "Device", "Dev_or_Path", etc can be passed a block
4270 device name. This function tests if the parameter is a block device
4271 name.
4272
4273 It can also be used in daemon code to test if the string passed as a
4274 "Dev_or_Path" parameter is a device or path.
4275
4276 Function "daemon/utils.c:sysroot_path"
4277
4278 char *
4279 sysroot_path (const char *path)
4280
4281 Turn "/path" into "/sysroot/path".
4282
4283 Returns "NULL" on failure. The caller must check for this and call
4284 "reply_with_perror ("malloc")". The caller must also free the returned
4285 string.
4286
4287 See also the custom %R printf formatter which does shell quoting too.
4288
4289 Function "daemon/utils.c:sysroot_realpath"
4290
4291 char *
4292 sysroot_realpath (const char *path)
4293
4294 Resolve path within sysroot, calling "sysroot_path" on the resolved
4295 path.
4296
4297 Returns "NULL" on failure. The caller must check for this and call
4298 "reply_with_perror ("malloc")". The caller must also free the returned
4299 string.
4300
4301 See also the custom %R printf formatter which does shell quoting too.
4302
4303 Function "daemon/utils.c:is_power_of_2"
4304
4305 int
4306 is_power_of_2 (unsigned long v)
4307
4308 Returns true if "v" is a power of 2.
4309
4310 Uses the algorithm described at
4311 http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
4312
4313 Function "daemon/utils.c:split_lines_sb"
4314
4315 struct stringsbuf
4316 split_lines_sb (char *str)
4317
4318 Split an output string into a NULL-terminated list of lines, wrapped
4319 into a stringsbuf.
4320
4321 Typically this is used where we have run an external command which has
4322 printed out a list of things, and we want to return an actual list.
4323
4324 The corner cases here are quite tricky. Note in particular:
4325
4326 "" returns "[]"
4327
4328 "\n"
4329 returns "[""]"
4330
4331 "a\nb"
4332 returns "["a"; "b"]"
4333
4334 "a\nb\n"
4335 returns "["a"; "b"]"
4336
4337 "a\nb\n\n"
4338 returns "["a"; "b"; ""]"
4339
4340 The original string is written over and destroyed by this function
4341 (which is usually OK because it's the 'out' string from "command*()").
4342 You can free the original string, because add_string() strdups the
4343 strings.
4344
4345 "argv" in the "struct stringsbuf" will be "NULL" in case of errors.
4346
4347 Function "daemon/utils.c:filter_list"
4348
4349 char **
4350 filter_list (bool (*p) (const char *str), char **strs)
4351
4352 Filter a list of strings. Returns a newly allocated list of only the
4353 strings where "p (str) == true".
4354
4355 Note it does not copy the strings, be careful not to double-free them.
4356
4357 Function "daemon/utils.c:trim"
4358
4359 void
4360 trim (char *str)
4361
4362 Skip leading and trailing whitespace, updating the original string in-
4363 place.
4364
4365 Function "daemon/utils.c:parse_btrfsvol"
4366
4367 int
4368 parse_btrfsvol (const char *desc_orig, mountable_t *mountable)
4369
4370 Parse the mountable descriptor for a btrfs subvolume. Don't call this
4371 directly; it is only used from the stubs.
4372
4373 A btrfs subvolume is given as:
4374
4375 btrfsvol:/dev/sda3/root
4376
4377 where /dev/sda3 is a block device containing a btrfs filesystem, and
4378 root is the name of a subvolume on it. This function is passed the
4379 string following "btrfsvol:".
4380
4381 On success, "mountable->device" and "mountable->volume" must be freed
4382 by the caller.
4383
4384 Function "daemon/utils.c:mountable_to_string"
4385
4386 char *
4387 mountable_to_string (const mountable_t *mountable)
4388
4389 Convert a "mountable_t" back to its string representation
4390
4391 This function can be used in an error path, so must not call
4392 "reply_with_error".
4393
4394 Function "daemon/utils.c:prog_exists"
4395
4396 int
4397 prog_exists (const char *prog)
4398
4399 Check program exists and is executable on $PATH.
4400
4401 Function "daemon/utils.c:random_name"
4402
4403 int
4404 random_name (char *template)
4405
4406 Pass a template such as "/sysroot/XXXXXXXX.XXX". This updates the
4407 template to contain a randomly named file. Any 'X' characters after
4408 the final '/' in the template are replaced with random characters.
4409
4410 Notes: You should probably use an 8.3 path, so it's compatible with all
4411 filesystems including basic FAT. Also this only substitutes lowercase
4412 ASCII letters and numbers, again for compatibility with lowest common
4413 denominator filesystems.
4414
4415 This doesn't create a file or check whether or not the file exists (it
4416 would be extremely unlikely to exist as long as the RNG is working).
4417
4418 If there is an error, -1 is returned.
4419
4420 Function "daemon/utils.c:udev_settle_file"
4421
4422 void
4423 udev_settle_file (const char *file)
4424
4425 LVM and other commands aren't synchronous, especially when udev is
4426 involved. eg. You can create or remove some device, but the "/dev"
4427 device node won't appear until some time later. This means that you
4428 get an error if you run one command followed by another.
4429
4430 Use "udevadm settle" after certain commands, but don't be too fussed if
4431 it fails.
4432
4433 Function "daemon/utils.c:make_exclude_from_file"
4434
4435 char *
4436 make_exclude_from_file (const char *function, char *const *excludes)
4437
4438 Turn list "excludes" into a temporary file, and return a string
4439 containing the temporary file name. Caller must unlink the file and
4440 free the string.
4441
4442 "function" is the function that invoked this helper, and it is used
4443 mainly for errors/debugging.
4444
4445 Function "daemon/utils.c:read_whole_file"
4446
4447 char *
4448 read_whole_file (const char *filename, size_t *size_r)
4449
4450 Read whole file into dynamically allocated array. If there is an
4451 error, DON'T call reply_with_perror, just return NULL. Returns a
4452 "\0"-terminated string. "size_r" can be specified to get the size of
4453 the returned data.
4454
4455 File daemon/xattr.c
4456
4457 Function "daemon/xattr.c:split_attr_names"
4458
4459 static char **
4460 split_attr_names (char *buf, size_t len)
4461
4462 listxattr(2) returns the string "foo\0bar\0baz" of length "len". (The
4463 last string in the list is \0-terminated but the \0 is not included in
4464 "len").
4465
4466 This function splits it into a regular list of strings.
4467
4468 Note that the returned list contains pointers to the original strings
4469 in "buf" so be careful that you do not double-free them.
4470
4471 Subdirectory fish
4472 File fish/alloc.c
4473
4474 This file implements the guestfish "alloc" and "sparse" commands.
4475
4476 Function "fish/alloc.c:alloc_disk"
4477
4478 int
4479 alloc_disk (const char *filename, const char *size_str, int add, int sparse)
4480
4481 This is the underlying allocation function. It's called from a few
4482 other places in guestfish.
4483
4484 File fish/copy.c
4485
4486 This file implements the guestfish commands "copy-in" and "copy-out".
4487
4488 File fish/destpaths.c
4489
4490 The file handles tab-completion of filesystem paths in guestfish.
4491
4492 File fish/display.c
4493
4494 The file implements the guestfish "display" command, for displaying
4495 graphical files (icons, images) in disk images.
4496
4497 File fish/echo.c
4498
4499 The file implements the guestfish "echo" command.
4500
4501 File fish/edit.c
4502
4503 guestfish "edit" command, suggested by Ján Ondrej.
4504
4505 File fish/events.c
4506
4507 This file implements the guestfish event-related commands, "event",
4508 "delete-event" and "list-events".
4509
4510 File fish/fish.c
4511
4512 guestfish, the guest filesystem shell. This file contains the main
4513 loop and utilities.
4514
4515 Function "fish/fish.c:parse_command_line"
4516
4517 static struct parsed_command
4518 parse_command_line (char *buf, int *exit_on_error_rtn)
4519
4520 Parse a command string, splitting at whitespace, handling '!', '#' etc.
4521 This destructively updates "buf".
4522
4523 "exit_on_error_rtn" is used to pass in the global "exit_on_error"
4524 setting and to return the local setting (eg. if the command begins with
4525 '-').
4526
4527 Returns in "parsed_command.status":
4528
4529 1 got a guestfish command (returned in
4530 "cmd_rtn"/"argv_rtn"/"pipe_rtn")
4531
4532 0 no guestfish command, but otherwise OK
4533
4534 -1 an error
4535
4536 Function "fish/fish.c:parse_quoted_string"
4537
4538 static ssize_t
4539 parse_quoted_string (char *p)
4540
4541 Parse double-quoted strings, replacing backslash escape sequences with
4542 the true character. Since the string is returned in place, the escapes
4543 must make the string shorter.
4544
4545 Function "fish/fish.c:execute_and_inline"
4546
4547 static int
4548 execute_and_inline (const char *cmd, int global_exit_on_error)
4549
4550 Used to handle "<!" (execute command and inline result).
4551
4552 Function "fish/fish.c:issue_command"
4553
4554 int
4555 issue_command (const char *cmd, char *argv[], const char *pipecmd,
4556 int rc_exit_on_error_flag)
4557
4558 Run a command.
4559
4560 "rc_exit_on_error_flag" is the "exit_on_error" flag that we pass to the
4561 remote server (when issuing --remote commands). It does not cause
4562 "issue_command" itself to exit on error.
4563
4564 Function "fish/fish.c:extended_help_message"
4565
4566 void
4567 extended_help_message (void)
4568
4569 Print an extended help message when the user types in an unknown
4570 command for the first command issued. A common case is the user doing:
4571
4572 guestfish disk.img
4573
4574 expecting guestfish to open disk.img (in fact, this tried to run a non-
4575 existent command "disk.img").
4576
4577 Function "fish/fish.c:error_cb"
4578
4579 static void
4580 error_cb (guestfs_h *g, void *data, const char *msg)
4581
4582 Error callback. This replaces the standard libguestfs error handler.
4583
4584 Function "fish/fish.c:free_n_strings"
4585
4586 static void
4587 free_n_strings (char **str, size_t len)
4588
4589 Free strings from a non-NULL terminated "char**".
4590
4591 Function "fish/fish.c:decode_ps1"
4592
4593 static char *
4594 decode_ps1 (const char *str)
4595
4596 Decode "str" into the final printable prompt string.
4597
4598 Function "fish/fish.c:win_prefix"
4599
4600 char *
4601 win_prefix (const char *path)
4602
4603 Resolve the special "win:..." form for Windows-specific paths. The
4604 generated code calls this for all device or path arguments.
4605
4606 The function returns a newly allocated string, and the caller must free
4607 this string; else display an error and return "NULL".
4608
4609 Function "fish/fish.c:file_in"
4610
4611 char *
4612 file_in (const char *arg)
4613
4614 Resolve the special "FileIn" paths ("-" or "-<<END" or filename).
4615
4616 The caller (fish/cmds.c) will call "free_file_in" after the command has
4617 run which should clean up resources.
4618
4619 Function "fish/fish.c:file_out"
4620
4621 char *
4622 file_out (const char *arg)
4623
4624 Resolve the special "FileOut" paths ("-" or filename).
4625
4626 The caller (fish/cmds.c) will call "free (str)" after the command has
4627 run.
4628
4629 Function "fish/fish.c:progress_callback"
4630
4631 void
4632 progress_callback (guestfs_h *g, void *data,
4633 uint64_t event, int event_handle, int flags,
4634 const char *buf, size_t buf_len,
4635 const uint64_t *array, size_t array_len)
4636
4637 Callback which displays a progress bar.
4638
4639 File fish/glob.c
4640
4641 This file implements the guestfish "glob" command.
4642
4643 Function "fish/glob.c:expand_devicename"
4644
4645 static char **
4646 expand_devicename (guestfs_h *g, const char *device)
4647
4648 Glob-expand device patterns, such as "/dev/sd*"
4649 (https://bugzilla.redhat.com/635971).
4650
4651 There is no "guestfs_glob_expand_device" function because the
4652 equivalent can be implemented using functions like
4653 "guestfs_list_devices".
4654
4655 It's not immediately clear what it means to expand a pattern like
4656 "/dev/sd*". Should that include device name translation? Should the
4657 result include partitions as well as devices?
4658
4659 Should "/dev/" + "*" return every possible device and filesystem? How
4660 about VGs? LVs?
4661
4662 To solve this what we do is build up a list of every device, partition,
4663 etc., then glob against that list.
4664
4665 Notes for future work (XXX):
4666
4667 • This doesn't handle device name translation. It wouldn't be too
4668 hard to add.
4669
4670 • Could have an API function for returning all device-like things.
4671
4672 Function "fish/glob.c:add_strings_matching"
4673
4674 static int
4675 add_strings_matching (char **pp, const char *glob,
4676 char ***ret, size_t *size_r)
4677
4678 Using POSIX fnmatch(3), find strings in the list "pp" which match
4679 pattern "glob". Add strings which match to the "ret" array. *size_r
4680 is the current size of the "ret" array, which is updated with the new
4681 size.
4682
4683 Function "fish/glob.c:single_element_list"
4684
4685 static char **
4686 single_element_list (const char *element)
4687
4688 Return a single element list containing "element".
4689
4690 File fish/help.c
4691
4692 The file implements the guestfish "help" command.
4693
4694 Function "fish/help.c:display_help"
4695
4696 int
4697 display_help (const char *cmd, size_t argc, char *argv[])
4698
4699 The "help" command.
4700
4701 This used to just list all commands, but that's not very useful.
4702 Instead display some useful context-sensitive help. This could be
4703 improved if we knew how many drives had been added already, and whether
4704 anything was mounted.
4705
4706 File fish/hexedit.c
4707
4708 This file implements the guestfish "hexedit" command.
4709
4710 File fish/lcd.c
4711
4712 Function "fish/lcd.c:run_lcd"
4713
4714 int
4715 run_lcd (const char *cmd, size_t argc, char *argv[])
4716
4717 guestfish "lcd" command (similar to the "lcd" command in BSD ftp).
4718
4719 File fish/man.c
4720
4721 Function "fish/man.c:run_man"
4722
4723 int
4724 run_man (const char *cmd, size_t argc, char *argv[])
4725
4726 guestfish "man" command
4727
4728 File fish/more.c
4729
4730 This file implements the guestfish "more" command.
4731
4732 File fish/prep.c
4733
4734 This file implements the guestfish -N option for creating pre-prepared
4735 disk layouts.
4736
4737 File fish/rc.c
4738
4739 This file implements guestfish remote (command) support.
4740
4741 Function "fish/rc.c:rc_listen"
4742
4743 void
4744 rc_listen (void)
4745
4746 The remote control server (ie. "guestfish --listen").
4747
4748 Function "fish/rc.c:rc_remote"
4749
4750 int
4751 rc_remote (int pid, const char *cmd, size_t argc, char *argv[],
4752 int exit_on_error)
4753
4754 The remote control client (ie. "guestfish --remote").
4755
4756 File fish/reopen.c
4757
4758 This file implements the guestfish "reopen" command.
4759
4760 File fish/setenv.c
4761
4762 This file implements the guestfish "setenv" and "unsetenv" commands.
4763
4764 File fish/supported.c
4765
4766 This file implements the guestfish "supported" command.
4767
4768 File fish/tilde.c
4769
4770 This file implements tilde ("~") expansion of home directories in
4771 guestfish(1).
4772
4773 Function "fish/tilde.c:try_tilde_expansion"
4774
4775 char *
4776 try_tilde_expansion (char *str)
4777
4778 This is called from the script loop if we find a candidate for
4779 "~username" (tilde-expansion).
4780
4781 Function "fish/tilde.c:expand_home"
4782
4783 static char *
4784 expand_home (char *orig, const char *append)
4785
4786 Return $HOME + append string.
4787
4788 Function "fish/tilde.c:find_home_for_username"
4789
4790 static const char *
4791 find_home_for_username (const char *username, size_t ulen)
4792
4793 Lookup "username" (of length "ulen"), return home directory if found,
4794 or "NULL" if not found.
4795
4796 File fish/time.c
4797
4798 This file implements the guestfish "time" command.
4799
4800 Subdirectory python
4801 File python/handle.c
4802
4803 This file contains a small number of functions that are written by
4804 hand. The majority of the bindings are generated (see
4805 python/actions-*.c).
4806
4808 guestfs(3), guestfs-building(1), guestfs-examples(3),
4809 guestfs-internals(1), guestfs-performance(1), guestfs-release-notes(1),
4810 guestfs-testing(1), libguestfs-test-tool(1),
4811 libguestfs-make-fixed-appliance(1), http://libguestfs.org/.
4812
4814 Richard W.M. Jones ("rjones at redhat dot com")
4815
4817 Copyright (C) 2009-2023 Red Hat Inc.
4818
4820 This library is free software; you can redistribute it and/or modify it
4821 under the terms of the GNU Lesser General Public License as published
4822 by the Free Software Foundation; either version 2 of the License, or
4823 (at your option) any later version.
4824
4825 This library is distributed in the hope that it will be useful, but
4826 WITHOUT ANY WARRANTY; without even the implied warranty of
4827 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
4828 Lesser General Public License for more details.
4829
4830 You should have received a copy of the GNU Lesser General Public
4831 License along with this library; if not, write to the Free Software
4832 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
4833 02110-1301 USA
4834
4836 To get a list of bugs against libguestfs, use this link:
4837 https://bugzilla.redhat.com/buglist.cgi?component=libguestfs&product=Virtualization+Tools
4838
4839 To report a new bug against libguestfs, use this link:
4840 https://bugzilla.redhat.com/enter_bug.cgi?component=libguestfs&product=Virtualization+Tools
4841
4842 When reporting a bug, please supply:
4843
4844 • The version of libguestfs.
4845
4846 • Where you got libguestfs (eg. which Linux distro, compiled from
4847 source, etc)
4848
4849 • Describe the bug accurately and give a way to reproduce it.
4850
4851 • Run libguestfs-test-tool(1) and paste the complete, unedited output
4852 into the bug report.
4853
4854
4855
4856libguestfs-1.51.9 2023-12-09 guestfs-hacking(1)