# $VBOX_PRODUCT®

Programming Guide and Reference

Version $VBOX_VERSION_STRING $VBOX_VENDOR

    http://www.virtualbox.org

2004-$VBOX_C_YEAR $VBOX_VENDOR

## Introduction

VirtualBox comes with comprehensive support for third-party developers. This Software Development Kit (SDK) contains all the documentation and interface files that are needed to write code that interacts with VirtualBox.

### Modularity: the building blocks of VirtualBox

VirtualBox is cleanly separated into several layers, which can be visualized like in the picture below:

The orange area represents code that runs in kernel mode, the blue area represents userspace code.

At the bottom of the stack resides the hypervisor -- the core of the virtualization engine, controlling execution of the virtual machines and making sure they do not conflict with each other or whatever the host computer is doing otherwise.

On top of the hypervisor, additional internal modules provide extra functionality. For example, the RDP server, which can deliver the graphical output of a VM remotely to an RDP client, is a separate module that is only loosely tacked into the virtual graphics device. Live Migration and Resource Monitor are additional modules currently in the process of being added to VirtualBox.

What is primarily of interest for purposes of the SDK is the API layer block that sits on top of all the previously mentioned blocks. This API, which we call the "Main API", exposes the entire feature set of the virtualization engine below. It is completely documented in this SDK Reference -- see and -- and available to anyone who wishes to control VirtualBox programmatically. We chose the name "Main API" to differentiate it from other programming interfaces of VirtualBox that may be publicly accessible.

With the Main API, you can create, configure, start, stop and delete virtual machines, retrieve performance statistics about running VMs, configure the VirtualBox installation in general, and more. In fact, internally, the front-end programs `VirtualBox` and `VBoxManage` use nothing but this API as well -- there are no hidden backdoors into the virtualization engine for our own front-ends. This ensures the entire Main API is both well-documented and well-tested. (The same applies to `VBoxHeadless`, which is not shown in the image.)

### Two guises of the same "Main API": the web service or COM/XPCOM

There are several ways in which the Main API can be called by other code:

1. VirtualBox comes with a web service that maps nearly the entire Main API. The web service ships in a stand-alone executable (`vboxwebsrv`) that, when running, acts as an HTTP server, accepts SOAP connections and processes them.

   Since the entire web service API is publicly described in a web service description file (in WSDL format), you can write client programs that call the web service in any language with a toolkit that understands WSDL. These days, that includes most programming languages that are available: Java, C++, .NET, PHP, Python, Perl and probably many more.

   All of this is explained in detail in subsequent chapters of this book.

   There are two ways in which you can write client code that uses the web service:

   1. For Java as well as Python, the SDK contains easy-to-use classes that allow you to use the web service in an object-oriented, straightforward manner. We shall refer to this as the "object-oriented web service (OOWS)".

      The OO bindings for Java are described in , those for Python in .

   2. Alternatively, you can use the web service directly, without the object-oriented client layer. We shall refer to this as the "raw web service".

      You will then have neither native object orientation nor full type safety, since web services are neither object-oriented nor stateful. However, in this way, you can write client code even in languages for which we do not ship object-oriented client code; all you need is a programming language with a toolkit that can parse WSDL and generate client wrapper code from it.

      We describe this further in , with samples for Java and Perl.

2. Internally, for portability and easier maintenance, the Main API is implemented using the Component Object Model (COM), an interprocess mechanism for software components originally introduced by Microsoft for Microsoft Windows. On a Windows host, VirtualBox will use Microsoft COM; on other hosts where COM is not present, it ships with XPCOM, a free software implementation of COM originally created by the Mozilla project for their browsers.

   So, if you are familiar with COM and the C++ programming language (or with any other programming language that can handle COM/XPCOM objects, such as Java, Visual Basic or C#), then you can use the COM/XPCOM API directly. VirtualBox comes with all necessary files and documentation to build fully functional COM applications. For an introduction, please see below.

   The VirtualBox front-ends (the graphical user interfaces as well as the command line), which are all written in C++, use COM/XPCOM to call the Main API. Technically, the web service is another front-end to this COM API, mapping almost all of it to SOAP clients.

If you wonder which way to choose, here are a few comparisons:

Comparison web service vs. COM/XPCOM

Web service | COM/XPCOM
Pro: Easy to use with Java and Python with the object-oriented web service; extensive support even with other languages (C++, .NET, PHP, Perl and others) | Con: Usable from languages where COM bridge available (most languages on Windows platform, Python and C++ on other hosts)
Pro: Client can be on remote machine | Con: Client must be on the same host where virtual machine is executed
Con: Significant overhead due to XML marshalling over the wire for each method call | Pro: Relatively low invocation overhead

In the following chapters, we will describe the different ways in which to program VirtualBox, starting with the method that is easiest to use and then increase complexity as we go along.

### About web services in general

Web services are a particular type of programming interface. Whereas, with "normal" programming, a program calls an application programming interface (API) defined by another program or the operating system and both sides of the interface have to agree on the calling convention and, in most cases, use the same programming language, web services use Internet standards such as HTTP and XML to communicate.

In some ways, web services promise to deliver the same thing as CORBA and DCOM did years ago. However, while these previous technologies relied on specific binary protocols and thus proved to be difficult to use between diverging platforms, web services circumvent these incompatibilities by using text-only standards like HTTP and XML. On the downside (and, one could say, typical of things related to XML), a lot of standards are involved before a web service can be implemented. Many of the standards invented around XML are used one way or another. As a result, web services are slow and verbose, and the details can be incredibly messy. The relevant standards here are called SOAP and WSDL, where SOAP describes the format of the messages that are exchanged (an XML document wrapped in an HTTP header), and WSDL is an XML format that describes a complete API provided by a web service. WSDL in turn uses XML Schema to describe types, which is not exactly terse either. However, as you will see from the samples provided in this chapter, the VirtualBox web service shields you from these details and is easy to use.

In order to successfully use a web service, a number of things are required -- primarily, a web service accepting connections; service descriptions; and then a client that connects to that web service. The connections are governed by the SOAP standard, which describes how messages are to be exchanged between a service and its clients; the service descriptions are governed by WSDL.

In the case of VirtualBox, this translates into the following three components:

1. The VirtualBox web service (the "server"): this is the `vboxwebsrv` executable shipped with VirtualBox. Once you start this executable (which acts as a HTTP server on a specific TCP/IP port), clients can connect to the web service and thus control a VirtualBox installation.

2. VirtualBox also comes with WSDL files that describe the services provided by the web service. You can find these files in the `sdk/bindings/webservice/` directory. These files are understood by the web service toolkits that are shipped with most programming languages and enable you to easily access a web service even if you don't use our object-oriented client layers. VirtualBox is shipped with pregenerated web service glue code for several languages (Python, Perl, Java).

3. A client that connects to the web service in order to control the VirtualBox installation.

   Unless you play with some of the samples shipped with VirtualBox, this needs to be written by you.

### Running the web service

The web service ships in an stand-alone executable, `vboxwebsrv`, that, when running, acts as a HTTP server, accepts SOAP connections and processes them -- remotely or from the same machine.

The web service executable is not contained with the VirtualBox SDK, but instead ships with the standard VirtualBox binary package for your specific platform. Since the SDK contains only platform-independent text files and documentation, the binaries are instead shipped with the platform-specific packages.

The `vboxwebsrv` program, which implements the web service, is a text-mode (console) program which, after being started, simply runs until it is interrupted with Ctrl-C or a kill command.

Once the web service is started, it acts as a front-end to the VirtualBox installation of the user account that it is running under. In other words, if the web service is run under the user account of `user1`, it will see and manipulate the virtual machines and other data represented by the VirtualBox data of that user (e.g., on a Linux machine, under `/home/user1/.VirtualBox`; see the VirtualBox User Manual for details on where this data is stored).

#### Command line options of vboxwebsrv

The web service supports the following command line options:

- `--help` (or `-h`): print a brief summary of command line options.

- `--background` (or `-b`): run the web service as a background daemon. This option is not supported on Windows hosts.

- `--host` (or `-H`): This specifies the host to bind to and defaults to "localhost".

- `--port` (or `-p`): This specifies which port to bind to on the host and defaults to 18083.

- `--timeout` (or `-t`): This specifies the session timeout, in seconds, and defaults to 300 (five minutes). A web service client that has logged on but makes no calls to the web service will automatically be disconnected after the number of seconds specified here, as if it had called the `IWebSessionManager::logoff()` method provided by the web service itself.

  It is normally vital that each web service client call this method, as the web service can accumulate large amounts of memory when running, especially if a web service client does not properly release managed object references. As a result, this timeout value should not be set too high, especially on machines with a high load on the web service, or the web service may eventually deny service.

- `--check-interval` (or `-i`): This specifies the interval in which the web service checks for timed-out clients, in seconds, and defaults to 5. This normally does not need to be changed.

- `--verbose` (or `-v`): Normally, the webservice outputs only brief messages to the console each time a request is served. With this option, the webservice prints much more detailed data about every request and the COM methods that those requests are mapped to internally, which can be useful for debugging client programs.

- `--logfile` (or `-F`) `<file>`: If this is specified, the webservice not only prints its output to the console, but also writes it to the specified file. The file is created if it does not exist; if it does exist, new output is appended to it. This is useful if you run the webservice unattended and need to debug problems after they have occurred.

#### Authenticating at web service logon

As opposed to the COM/XPCOM variant of the Main API, a client that wants to use the web service must first log on by calling the `IWebsessionManager::logon()` API (see ) that is specific to the web service. Logon is necessary for the web service to be stateful; internally, it maintains a session for each client that connects to it.

The `IWebsessionManager::logon()` API takes a user name and a password as arguments, which the web service then passes to a customizable authentication plugin that performs the actual authentication.

For testing purposes, it is recommended that you first disable authentication with this command:

    VBoxManage setproperty websrvauthlibrary null

This will cause all logons to succeed, regardless of user name or password. This should of course not be used in a production environment.

Generally, the mechanism by which clients are authenticated is configurable by way of the `VBoxManage` command:

    VBoxManage setproperty websrvauthlibrary default|null|<library>

This way you can specify any shared object/dynamic link module that conforms with the specifications for VirtualBox external authentication modules as laid out in section VRDE authentication of the VirtualBox User Manual; the web service uses the same kind of modules as the VirtualBox VRDE server. For technical details on VirtualBox external authentication modules see

By default, after installation, the web service uses the VBoxAuth module that ships with VirtualBox. This module uses PAM on Linux hosts to authenticate users. Any valid username/password combination is accepted, it does not have to be the username and password of the user running the webservice daemon. Unless `vboxwebsrv` runs as root, PAM authentication can fail, because sometimes the file `/etc/shadow`, which is used by PAM, is not readable. On most Linux distribution PAM uses a suid root helper internally, so make sure you test this before deploying it. One can override this behavior by setting the environment variable `VBOX_PAM_ALLOW_INACTIVE` which will suppress failures when unable to read the shadow password file. Please use this variable carefully, and only if you fully understand what you're doing.

#### Solaris host: starting the web service via SMF

On Solaris hosts, the VirtualBox web service daemon is integrated into the SMF framework. You can change the parameters, but don't have to if the defaults below already match your needs:

    svccfg -s svc:/application/virtualbox/webservice:default setprop config/host=localhost
    svccfg -s svc:/application/virtualbox/webservice:default setprop config/port=18083
    svccfg -s svc:/application/virtualbox/webservice:default setprop config/user=root

If you made any change, don't forget to run the following command to put the changes into effect immediately:

    svcadm refresh svc:/application/virtualbox/webservice:default

If you forget the above command then the previous settings will be used when enabling the service. Check the current property settings with:

    svcprop -p config svc:/application/virtualbox/webservice:default

When everything is configured correctly you can start the VirtualBox webservice with the following command:

    svcadm enable svc:/application/virtualbox/webservice:default

For more information about SMF, please refer to the Solaris documentation.

## Environment-specific notes

The Main API described in and is mostly identical in all the supported programming environments which have been briefly mentioned in the introduction of this book. As a result, the Main API's general concepts described in are the same whether you use the object-oriented web service (OOWS) for JAX-WS or a raw web service connection via, say, Perl, or whether you use C++ COM bindings.

Some things are different depending on your environment, however. These differences are explained in this chapter.

### Using the object-oriented web service (OOWS)

As explained in , VirtualBox ships with client-side libraries for Java, Python and PHP that allow you to use the VirtualBox web service in an intuitive, object-oriented way. These libraries shield you from the client-side complications of managed object references and other implementation details that come with the VirtualBox web service. (If you are interested in these complications, have a look at ).

We recommend that you start your experiments with the VirtualBox web service by using our object-oriented client libraries for JAX-WS, a web service toolkit for Java, which enables you to write code to interact with VirtualBox in the simplest manner possible.

As "interfaces", "attributes" and "methods" are COM concepts, please read the documentation in and with the following notes in mind.

The OOWS bindings attempt to map the Main API as closely as possible to the Java, Python and PHP languages. In other words, objects are objects, interfaces become classes, and you can call methods on objects as you would on local objects.

The main difference remains with attributes: to read an attribute, call a "getXXX" method, with "XXX" being the attribute name with a capitalized first letter. So when the Main API Reference says that `IMachine` has a "name" attribute (see ), call `getName()` on an IMachine object to obtain a machine's name. Unless the attribute is marked as read-only in the documentation, there will also be a corresponding "set" method.

#### The object-oriented web service for JAX-WS

JAX-WS is a powerful toolkit by Sun Microsystems to build both server and client code with Java. It is part of Java 6 (JDK 1.6), but can also be obtained separately for Java 5 (JDK 1.5). The VirtualBox SDK comes with precompiled OOWS bindings working with both Java 5 and 6.

The following sections explain how to get the JAX-WS sample code running and explain a few common practices when using the JAX-WS object-oriented web service.

##### Preparations

Since JAX-WS is already integrated into Java 6, no additional preparations are needed for Java 6.

If you are using Java 5 (JDK 1.5.x), you will first need to download and install an external JAX-WS implementation, as Java 5 does not support JAX-WS out of the box; for example, you can download one from here: https://jax-ws.dev.java.net/2.1.4/JAXWS2.1.4-20080502.jar. Then perform the installation (`java -jar JAXWS2.1.4-20080502.jar`).

##### Getting started: running the sample code

To run the OOWS for JAX-WS samples that we ship with the SDK, perform the following steps:

1. Open a terminal and change to the directory where the JAX-WS samples reside.

   In `sdk/bindings/glue/java/`.

   Examine the header of `Makefile` to see if the supplied variables (Java compiler, Java executable) and a few other details match your system settings.

2. To start the VirtualBox web service, open a second terminal and change to the directory where the VirtualBox executables are located. Then type:

       ./vboxwebsrv -v

   The web service now waits for connections and will run until you press Ctrl+C in this second terminal. The -v argument causes it to log all connections to the terminal. (See for details on how to run the web service.)

3. Back in the first terminal and still in the samples directory, to start a simple client example just type:

       make run16

   if you're on a Java 6 system; on a Java 5 system, run `make run15` instead.

   This should work on all Unix-like systems such as Linux and Solaris. For Windows systems, use commands similar to what is used in the Makefile.

   This will compile the `clienttest.java` code on the first call and then execute the resulting `clienttest` class to show the locally installed VMs (see below).

The `clienttest` sample imitates a few typical command line tasks that `VBoxManage`, VirtualBox's regular command-line front-end, would provide (see the VirtualBox User Manual for details). In particular, you can run:

- `java clienttest show vms`: show the virtual machines that are registered locally.

- `java clienttest list hostinfo`: show various information about the host this VirtualBox installation runs on.

- `java clienttest startvm <vmname|uuid>`: start the given virtual machine.

The `clienttest.java` sample code illustrates common basic practices how to use the VirtualBox OOWS for JAX-WS, which we will explain in more detail in the following chapters.

##### Logging on to the web service

Before a web service client can do anything useful, two objects need to be created, as can be seen in the `clienttest` constructor:

1. An instance of , which is an interface provided by the web service to manage "web sessions" -- that is, stateful connections to the web service with persistent objects upon which methods can be invoked.

   In the OOWS for JAX-WS, the IWebsessionManager class must be constructed explicitly, and a URL must be provided in the constructor that specifies where the web service (the server) awaits connections. The code in `clienttest.java` connects to "http://localhost:18083/", which is the default.

   The port number, by default 18083, must match the port number given to the `vboxwebsrv` command line; see .

2. After that, the code calls , which is the first call that actually communicates with the server. This authenticates the client with the web service and returns an instance of , the most fundamental interface of the VirtualBox web service, from which all other functionality can be derived.

   If logon doesn't work, please take another look at .

##### Object management

The current OOWS for JAX-WS has certain memory management related limitations. When you no longer need an object, call its method explicitly, which frees appropriate managed reference, as is required by the raw webservice; see for details. This limitation may be reconsidered in a future version of the VirtualBox SDK.

#### The object-oriented web service for Python

VirtualBox comes with two flavors of a Python API: one for web service, discussed here, and one for the COM/XPCOM API discussed in . The client code is mostly similar, except for the initialization part, so it is up to the application developer to choose the appropriate technology. Moreover, a common Python glue layer exists, abstracting out concrete platform access details, see .

As indicated in , the COM/XPCOM API gives better performance without the SOAP overhead, and does not require a web server to be running. On the other hand, the COM/XPCOM Python API requires a suitable Python bridge for your Python installation (VirtualBox ships the most important ones for each platform

On On Mac OS X only the Python versions bundled with the OS are officially supported. This means Python 2.3 for 10.4, Python 2.5 for 10.5 and Python 2.5 and 2.6 for 10.6.

). On Windows, you can use the Main API from Python if the Win32 extensions package for Python

See http://sourceforge.net/project/showfiles.php?group_id=78018.

is installed. Version of Python Win32 extensions earlier than 2.16 are known to have bugs, leading to issues with VirtualBox Python bindings, and also some early builds of Python 2.5 for Windows have issues with reporting platform name on some Windows versions, so please make sure to use latest available Python and Win32 extensions.

The VirtualBox OOWS for Python relies on the Python ZSI SOAP implementation (see http://pywebsvcs.sourceforge.net/zsi.html), which you will need to install locally before trying the examples. Most Linux distributions come with package for ZSI, such as `python-zsi` in Ubuntu.

To get started, open a terminal and change to the `bindings/glue/python/sample` directory, which contains an example of a simple interactive shell able to control a VirtualBox instance. The shell is written using the API layer, thereby hiding different implementation details, so it is actually an example of code share among XPCOM, MSCOM and web services. If you are interested in how to interact with the webservices layer directly, have a look at `install/vboxapi/__init__.py` which contains the glue layer for all target platforms (i.e. XPCOM, MSCOM and web services).

To start the shell, perform the following commands:

    /opt/VirtualBox/vboxwebsrv -t 0
                # start webservice with object autocollection disabled
    export VBOX_PROGRAM_PATH=/opt/VirtualBox
                # your VirtualBox installation directory
    export VBOX_SDK_PATH=/home/youruser/vbox-sdk
                # where you've extracted the SDK
    ./vboxshell.py -w

See for more details on the shell's functionality. For you, as a VirtualBox application developer, the vboxshell sample could be interesting as an example of how to write code targeting both local and remote cases (COM/XPCOM and SOAP). The common part of the shell is the same -- the only difference is how it interacts with the invocation layer. You can use the `connect` shell command to connect to remote VirtualBox servers; in this case you can skip starting the local webserver.

#### The object-oriented web service for PHP

VirtualBox also comes with object-oriented web service (OOWS) wrappers for PHP5. These wrappers rely on the PHP SOAP Extension

See http://www.php.net/soap.

, which can be installed by configuring PHP with `--enable-soap`.

### Using the raw web service with any language

The following examples show you how to use the raw web service, without the object-oriented client-side code that was described in the previous chapter.

Generally, when reading the documentation in and , due to the limitations of SOAP and WSDL lined out in , please have the following notes in mind:

1. Any COM method call becomes a plain function call in the raw web service, with the object as an additional first parameter (before the "real" parameters listed in the documentation). So when the documentation says that the `IVirtualBox` interface supports the `createMachine()` method (see ), the web service operation is `IVirtualBox_createMachine(...)`, and a managed object reference to an `IVirtualBox` object must be passed as the first argument.

2. For attributes in interfaces, there will be at least one "get" function; there will also be a "set" function, unless the attribute is "readonly". The attribute name will be appended to the "get" or "set" prefix, with a capitalized first letter. So, the "version" readonly attribute of the `IVirtualBox` interface can be retrieved by calling `IVirtualBox_getVersion(vbox)`, with `vbox` being the VirtualBox object.

3. Whenever the API documentation says that a method (or an attribute getter) returns an object, it will returned a managed object reference in the web service instead. As said above, managed object references should be released if the web service client does not log off again immediately!

#### Raw web service example for Java with Axis

Axis is an older web service toolkit created by the Apache foundation. If your distribution does not have it installed, you can get a binary from http://www.apache.org. The following examples assume that you have Axis 1.4 installed.

The VirtualBox SDK ships with an example for Axis that, again, is called `clienttest.java` and that imitates a few of the commands of `VBoxManage` over the wire.

Then perform the following steps:

1. Create a working directory somewhere. Under your VirtualBox installation directory, find the `sdk/webservice/samples/java/axis/` directory and copy the file `clienttest.java` to your working directory.

2. Open a terminal in your working directory. Execute the following command:

        java org.apache.axis.wsdl.WSDL2Java /path/to/vboxwebService.wsdl

   The `vboxwebService.wsdl` file should be located in the `sdk/webservice/` directory.

   If this fails, your Apache Axis may not be located on your system classpath, and you may have to adjust the CLASSPATH environment variable. Something like this:

       export CLASSPATH="/path-to-axis-1_4/lib/*":$CLASSPATH

   Use the directory where the Axis JAR files are located. Mind the quotes so that your shell passes the "*" character to the java executable without expanding. Alternatively, add a corresponding `-classpath` argument to the "java" call above.

   If the command executes successfully, you should see an "org" directory with subdirectories containing Java source files in your working directory. These classes represent the interfaces that the VirtualBox web service offers, as described by the WSDL file.

   This is the bit that makes using web services so attractive to client developers: if a language's toolkit understands WSDL, it can generate large amounts of support code automatically. Clients can then easily use this support code and can be done with just a few lines of code.

3. Next, compile the `clienttest.java` source:

       javac clienttest.java

   This should yield a "clienttest.class" file.

4. To start the VirtualBox web service, open a second terminal and change to the directory where the VirtualBox executables are located. Then type:

       ./vboxwebsrv -v

   The web service now waits for connections and will run until you press Ctrl+C in this second terminal. The -v argument causes it to log all connections to the terminal. (See for details on how to run the web service.)

5. Back in the original terminal where you compiled the Java source, run the resulting binary, which will then connect to the web service:

       java clienttest

   The client sample will connect to the web service (on localhost, but the code could be changed to connect remotely if the web service was running on a different machine) and make a number of method calls. It will output the version number of your VirtualBox installation and a list of all virtual machines that are currently registered (with a bit of seemingly random data, which will be explained later).

#### Raw web service example for Perl

We also ship a small sample for Perl. It uses the SOAP::Lite perl module to communicate with the VirtualBox web service.

The `sdk/bindings/webservice/perl/lib/` directory contains a pre-generated Perl module that allows for communicating with the web service from Perl. You can generate such a module yourself using the "stubmaker" tool that comes with SOAP::Lite, but since that tool is slow as well as sometimes unreliable, we are shipping a working module with the SDK for your convenience.

Perform the following steps:

1. If SOAP::Lite is not yet installed on your system, you will need to install the package first. On Debian-based systems, the package is called `libsoap-lite-perl`; on Gentoo, it's `dev-perl/SOAP-Lite`.

2. Open a terminal in the `sdk/bindings/webservice/perl/samples/` directory.

3. To start the VirtualBox web service, open a second terminal and change to the directory where the VirtualBox executables are located. Then type:

       ./vboxwebsrv -v

   The web service now waits for connections and will run until you press Ctrl+C in this second terminal. The -v argument causes it to log all connections to the terminal. (See for details on how to run the web service.)

4. In the first terminal with the Perl sample, run the clienttest.pl script:

       perl -I ../lib clienttest.pl

#### Programming considerations for the raw web service

If you use the raw web service, you need to keep a number of things in mind, or you will sooner or later run into issues that are not immediately obvious. By contrast, the object-oriented client-side libraries described in take care of these things automatically and thus greatly simplify using the web service.

##### Fundamental conventions

If you are familiar with other web services, you may find the VirtualBox web service to behave a bit differently to accommodate for the fact that VirtualBox web service more or less maps the VirtualBox Main COM API. The following main differences had to be taken care of:

- Web services, as expressed by WSDL, are not object-oriented. Even worse, they are normally stateless (or, in web services terminology, "loosely coupled"). Web service operations are entirely procedural, and one cannot normally make assumptions about the state of a web service between function calls.

  In particular, this normally means that you cannot work on objects in one method call that were created by another call.

- By contrast, the VirtualBox Main API, being expressed in COM, is object-oriented and works entirely on objects, which are grouped into public interfaces, which in turn have attributes and methods associated with them.

For the VirtualBox web service, this results in three fundamental conventions:

1. All function names in the VirtualBox web service consist of an interface name and a method name, joined together by an underscore. This is because there are only functions ("operations") in WSDL, but no classes, interfaces, or methods.

   In addition, all calls to the VirtualBox web service (except for logon, see below) take a managed object reference as the first argument, representing the object upon which the underlying method is invoked. (Managed object references are explained in detail below; see .)

   So, when one would normally code, in the pseudo-code of an object-oriented language, to invoke a method upon an object:

       IMachine machine;
       result = machine.getName();

   In the VirtualBox web service, this looks something like this (again, pseudo-code):

       IMachineRef machine;
       result = IMachine_getName(machine);

2. To make the web service stateful, and objects persistent between method calls, the VirtualBox web service introduces a session manager (by way of the interface), which manages object references. Any client wishing to interact with the web service must first log on to the session manager and in turn receives a managed object reference to an object that supports the interface (the basic interface in the Main API).

In other words, as opposed to other web services, the VirtualBox web service is both object-oriented and stateful.

##### Example: A typical web service client session

A typical short web service session to retrieve the version number of the VirtualBox web service (to be precise, the underlying Main API version number) looks like this:

1. A client logs on to the web service by calling with a valid user name and password. See for details about how authentication works.

2. On the server side, `vboxwebsrv` creates a session, which persists until the client calls or the session times out after a configurable period of inactivity (see ).

   For the new session, the web service creates an instance of . This interface is the most central one in the Main API and allows access to all other interfaces, either through attributes or method calls. For example, IVirtualBox contains a list of all virtual machines that are currently registered (as they would be listed on the left side of the VirtualBox main program).

   The web service then creates a managed object reference for this instance of IVirtualBox and returns it to the calling client, which receives it as the return value of the logon call. Something like this:

       string oVirtualBox;
       oVirtualBox = webservice.IWebsessionManager_logon("user", "pass");

   (The managed object reference "oVirtualBox" is just a string consisting of digits and dashes. However, it is a string with a meaning and will be checked by the web service. For details, see below. As hinted above, is the only operation provided by the web service which does not take a managed object reference as the first argument!)

3. The VirtualBox Main API documentation says that the `IVirtualBox` interface has a attribute, which is a string. For each attribute, there is a "get" and a "set" method in COM, which maps to according operations in the web service. So, to retrieve the "version" attribute of this `IVirtualBox` object, the web service client does this:

       string version;
       version = webservice.IVirtualBox_getVersion(oVirtualBox);

       print version;

   And it will print "$VBOX_VERSION_MAJOR.$VBOX_VERSION_MINOR.$VBOX_VERSION_BUILD".

4. The web service client calls with the VirtualBox managed object reference. This will clean up all allocated resources.

##### Managed object references

To a web service client, a managed object reference looks like a string: two 64-bit hex numbers separated by a dash. This string, however, represents a COM object that "lives" in the web service process. The two 64-bit numbers encoded in the managed object reference represent a session ID (which is the same for all objects in the same web service session, i.e. for all objects after one logon) and a unique object ID within that session.

Managed object references are created in two situations:

1. When a client logs on, by calling .

   Upon logon, the websession manager creates one instance of and another object of representing the web service session. This can be retrieved using .

   (Technically, there is always only one object, which is shared between all sessions and clients, as it is a COM singleton. However, each session receives its own managed object reference to it. The object, however, is created and destroyed for each session.)

2. Whenever a web service clients invokes an operation whose COM implementation creates COM objects.

   For example, creates a new instance of ; the COM object returned by the COM method call is then wrapped into a managed object reference by the web server, and this reference is returned to the web service client.

Internally, in the web service process, each managed object reference is simply a small data structure, containing a COM pointer to the "real" COM object, the web session ID and the object ID. This structure is allocated on creation and stored efficiently in hashes, so that the web service can look up the COM object quickly whenever a web service client wishes to make a method call. The random session ID also ensures that one web service client cannot intercept the objects of another.

Managed object references are not destroyed automatically and must be released by explicitly calling . This is important, as otherwise hundreds or thousands of managed object references (and corresponding COM objects, which can consume much more memory!) can pile up in the web service process and eventually cause it to deny service.

To reiterate: The underlying COM object, which the reference points to, is only freed if the managed object reference is released. It is therefore vital that web service clients properly clean up after the managed object references that are returned to them.

When a web service client calls , all managed object references created during the session are automatically freed. For short-lived sessions that do not create a lot of objects, logging off may therefore be sufficient, although it is certainly not "best practice".

##### Some more detail about web service operation

###### SOAP messages

Whenever a client makes a call to a web service, this involves a complicated procedure internally. These calls are remote procedure calls. Each such procedure call typically consists of two "message" being passed, where each message is a plain-text HTTP request with a standard HTTP header and a special XML document following. This XML document encodes the name of the procedure to call and the argument names and values passed to it.

To give you an idea of what such a message looks like, assuming that a web service provides a procedure called "SayHello", which takes a string "name" as an argument and returns "Hello" with a space and that name appended, the request message could look like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Envelope
     xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
     xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns:test="http://test/">
    <SOAP-ENV:Body>
       <test:SayHello>
        <name>Peter</name>
       </test:SayHello>
     </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

A similar message -- the "response" message -- would be sent back from the web service to the client, containing the return value "Hello Peter".

Most programming languages provide automatic support to generate such messages whenever code in that programming language makes such a request. In other words, these programming languages allow for writing something like this (in pseudo-C++ code):

    webServiceClass service("localhost", 18083); // server and port
    string result = service.SayHello("Peter");  // invoke remote procedure

and would, for these two pseudo-lines, automatically perform these steps:

1. prepare a connection to a web service running on port 18083 of "localhost";

2. for the `SayHello()` function of the web service, generate a SOAP message like in the above example by encoding all arguments of the remote procedure call (which could involve all kinds of type conversions and complex marshalling for arrays and structures);

3. connect to the web service via HTTP and send that message;

4. wait for the web service to send a response message;

5. decode that response message and put the return value of the remote procedure into the "result" variable.

###### Service descriptions in WSDL

In the above explanations about SOAP, it was left open how the programming language learns about how to translate function calls in its own syntax into proper SOAP messages. In other words, the programming language needs to know what operations the web service supports and what types of arguments are required for the operation's data in order to be able to properly serialize and deserialize the data to and from the web service. For example, if a web service operation expects a number in "double" floating point format for a particular parameter, the programming language cannot send to it a string instead.

For this, the Web Service Definition Language (WSDL) was invented, another XML substandard that describes exactly what operations the web service supports and, for each operation, which parameters and types are needed with each request and response message. WSDL descriptions can be incredibly verbose, and one of the few good things that can be said about this standard is that it is indeed supported by most programming languages.

So, if it is said that a programming language "supports" web services, this typically means that a programming language has support for parsing WSDL files and somehow integrating the remote procedure calls into the native language syntax -- for example, like in the Java sample shown in .

For details about how programming languages support web services, please refer to the documentation that comes with the individual languages. Here are a few pointers:

1. For C++, among many others, the gSOAP toolkit is a good option. Parts of gSOAP are also used in VirtualBox to implement the VirtualBox web service.

2. For Java, there are several implementations already described in this document (see and ).

3. Perl supports WSDL via the SOAP::Lite package. This in turn comes with a tool called `stubmaker.pl` that allows you to turn any WSDL file into a Perl package that you can import. (You can also import any WSDL file "live" by having it parsed every time the script runs, but that can take a while.) You can then code (again, assuming the above example):

       my $result = servicename->sayHello("Peter");

   A sample that uses SOAP::Lite was described in .

### Using COM/XPCOM directly

If you do not require remote procedure calls such as those offered by the VirtualBox web service, and if you know Python or C++ as well as COM, you might find it preferable to program VirtualBox's Main API directly via COM.

COM stands for "Component Object Model" and is a standard originally introduced by Microsoft in the 1990s for Microsoft Windows. It allows for organizing software in an object-oriented way and across processes; code in one process may access objects that live in another process.

COM has several advantages: it is language-neutral, meaning that even though all of VirtualBox is internally written in C++, programs written in other languages could communicate with it. COM also cleanly separates interface from implementation, so that external programs need not know anything about the messy and complicated details of VirtualBox internals.

On a Windows host, all parts of VirtualBox will use the COM functionality that is native to Windows. On other hosts (including Linux), VirtualBox comes with a built-in implementation of XPCOM, as originally created by the Mozilla project, which we have enhanced to support interprocess communication on a level comparable to Microsoft COM. Internally, VirtualBox has an abstraction layer that allows the same VirtualBox code to work both with native COM as well as our XPCOM implementation.

#### Python COM API

On Windows, Python scripts can use COM and VirtualBox interfaces to control almost all aspects of virtual machine execution. As an example, use the following commands to instantiate the VirtualBox object and start a VM:

           vbox = win32com.client.Dispatch("VirtualBox.VirtualBox")
           session = win32com.client.Dispatch("VirtualBox.Session")
           mach = vbox.findMachine("uuid or name  of machine to start")
           progress = mach.launchVMProcess(session, "gui", "")
           progress.waitForCompletion(-1)

Also, see `/bindings/glue/python/samples/vboxshell.py` for more advanced usage scenarious. However, unless you have specific requirements, we strongly recommend to use the generic glue layer described in the next section to access MS COM objects.

#### Common Python bindings layer

As different wrappers ultimately provide access to the same underlying API, and to simplify porting and development of Python application using the VirtualBox Main API, we developed a common glue layer that abstracts out most platform-specific details from the application and allows the developer to focus on application logic. The VirtualBox installer automatically sets up this glue layer for the system default Python install. See below for details on how to set up the glue layer if you want to use a different Python installation.

In this layer, the class `VirtualBoxManager` hides most platform-specific details. It can be used to access both the local (COM) and the webservice-based API. The following code can be used by an application to use the glue layer.

    # This code assumes vboxapi.py from VirtualBox distribution
    # being in PYTHONPATH, or installed system-wide
    from vboxapi import VirtualBoxManager

    # This code initializes VirtualBox manager with default style
    # and parameters
    virtualBoxManager = VirtualBoxManager(None, None)

    # Alternatively, one can be more verbose, and initialize
    # glue with webservice backend, and provide authentication
    # information
    virtualBoxManager = VirtualBoxManager("WEBSERVICE",
                                          {'url':'http://myhost.com::18083/',
                                          'user':'me',
                                          'password':'secret'})

We supply the `VirtualBoxManager` constructor with 2 arguments: style and parameters. Style defines which bindings style to use (could be "MSCOM", "XPCOM" or "WEBSERVICE"), and if set to `None` defaults to usable platform bindings (MS COM on Windows, XPCOM on other platforms). The second argument defines parameters, passed to the platform-specific module, as we do in the second example, where we pass username and password to be used to authenticate against the web service.

After obtaining the `VirtualBoxManager` instance, one can perform operations on the IVirtualBox class. For example, the following code will a start virtual machine by name or ID:

    from vboxapi import VirtualBoxManager
    mgr = VirtualBoxManager(None, None)
    vbox = mgr.vbox
    name = "Linux"
    mach = vbox.findMachine(name)
    session = mgr.mgr.getSessionObject(vbox)
    progress = mach.launchVMProcess(session, "gui", "")
    progress.waitForCompletion(-1)
    mgr.closeMachineSession(session)

Following code will print all registered machines and their log folders

    from vboxapi import VirtualBoxManager
    mgr = VirtualBoxManager(None, None)
    vbox = mgr.vbox

    for m in mgr.getArray(vbox, 'machines'):
    print "Machine '%s' logs in '%s'" %(m.name, m.logFolder)

Code above demonstartes cross-platform access to array properties (certain limitations prevent one from using `vbox.machines` to access a list of available virtual machines in case of XPCOM), and a mechanism of uniform session creation and closing (`mgr.mgr.getSessionObject()`).

In case you want to use the glue layer with a different Python installation, use these steps in a shell to add the necessary files:

        # cd VBOX_INSTALL_PATH/sdk/installer
        # PYTHON vboxapisetup.py install

#### C++ COM API

C++ is the language that VirtualBox itself is written in, so C++ is the most direct way to use the Main API -- but it is not necessarily the easiest, as using COM and XPCOM has its own set of complications.

VirtualBox ships with sample programs that demonstrate how to use the Main API to implement a number of tasks on your host platform. These samples can be found in the `/bindings/xpcom/samples` directory for Linux, Mac OS X and Solaris and `/bindings/mscom/samples` for Windows. The two samples are actually different, because the one for Windows uses native COM, whereas the other uses our XPCOM implementation, as described above.

Since COM and XPCOM are conceptually very similar but vary in the implementation details, we have created a "glue" layer that shields COM client code from these differences. All VirtualBox uses is this glue layer, so the same code written once works on both Windows hosts (with native COM) as well as on other hosts (with our XPCOM implementation). It is recommended to always use this glue code instead of using the COM and XPCOM APIs directly, as it is very easy to make your code completely independent from the platform it is running on.

In order to encapsulate platform differences between Microsoft COM and XPCOM, the following items should be kept in mind when using the glue layer:

1. Attribute getters and setters. COM has the notion of "attributes" in interfaces, which roughly compare to C++ member variables in classes. The difference is that for each attribute declared in an interface, COM automatically provides a "get" method to return the attribute's value. Unless the attribute has been marked as "readonly", a "set" attribute is also provided.

   To illustrate, the IVirtualBox interface has a "version" attribute, which is read-only and of the "wstring" type (the standard string type in COM). As a result, you can call the "get" method for this attribute to retrieve the version number of VirtualBox.

   Unfortunately, the implementation differs between COM and XPCOM. Microsoft COM names the "get" method like this: `get_Attribute()`, whereas XPCOM uses this syntax: `GetAttribute()` (and accordingly for "set" methods). To hide these differences, the VirtualBox glue code provides the `COMGETTER(attrib)` and `COMSETTER(attrib)` macros. So, `COMGETTER(version)()` (note, two pairs of brackets) expands to `get_Version()` on Windows and `GetVersion()` on other platforms.

2. Unicode conversions. While the rest of the modern world has pretty much settled on encoding strings in UTF-8, COM, unfortunately, uses UCS-16 encoding. This requires a lot of conversions, in particular between the VirtualBox Main API and the Qt GUI, which, like the rest of Qt, likes to use UTF-8.

   To facilitate these conversions, VirtualBox provides the `com::Bstr` and `com::Utf8Str` classes, which support all kinds of conversions back and forth.

3. COM autopointers. Possibly the greatest pain of using COM -- reference counting -- is alleviated by the `ComPtr<>` template provided by the `ptr.h` file in the glue layer.

#### Event queue processing

Both VirtualBox client programs and frontends should periodically perform processing of the main event queue, and do that on the application's main thread. In case of a typical GUI Windows/Mac OS application this happens automatically in the GUI's dispatch loop. However, for CLI only application, the appropriate actions have to be taken. For C++ applications, the VirtualBox SDK provided glue method

                int EventQueue::processEventQueue(uint32_t cMsTimeout)

can be used for both blocking and non-blocking operations. For the Python bindings, a common layer provides the method

              VirtualBoxManager.waitForEvents(ms)

with similar semantics.

Things get somewhat more complicated for situations where an application using VirtualBox cannot directly control the main event loop and the main event queue is separated from the event queue of the programming librarly (for example in case of Qt on Unix platforms). In such a case, the application developer is advised to use a platform/toolkit specific event injection mechanism to force event queue checks either based on periodical timer events delivered to the main thread, or by using custom platform messages to notify the main thread when events are available. See the VBoxSDL and Qt (VirtualBox) frontends as examples.

#### Visual Basic and Visual Basic Script (VBS) on Windows hosts

On Windows hosts, one can control some of the VirtualBox Main API functionality from VBS scripts, and pretty much everything from Visual Basic programs.

The difference results from the way VBS treats COM safearrays, which are used to keep lists in the Main API. VBS expects every array element to be a `VARIANT`, which is too strict a limitation for any high performance API. We may lift this restriction for interface APIs in a future version, or alternatively provide conversion APIs.

VBS is scripting language available in any recent Windows environment. As an example, the following VBS code will print VirtualBox version:

             set vb = CreateObject("VirtualBox.VirtualBox")
             Wscript.Echo "VirtualBox version " & vb.version

See `bindings/mscom/vbs/sample/vboxinfo.vbs` for the complete sample.

Visual Basic is a popular high level language capable of accessing COM objects. The following VB code will iterate over all available virtual machines:

             Dim vb As VirtualBox.IVirtualBox

             vb = CreateObject("VirtualBox.VirtualBox")
             machines = ""
             For Each m In vb.Machines
                m = m & " " & m.Name
             Next

See `bindings/mscom/vb/sample/vboxinfo.vb` for the complete sample.

#### C binding to XPCOM API

This section currently applies to Linux hosts only.

Starting with version 2.2, VirtualBox offers a C binding for the XPCOM API.

The C binding provides a layer enabling object creation, method invocation and attribute access from C.

##### Getting started

The following sections describe how to use the C binding in a C program.

For Linux, a sample program is provided which demonstrates use of the C binding to initialize XPCOM, get handles for VirtualBox and Session objects, make calls to list and start virtual machines, and uninitialize resources when done. The program uses the VBoxGlue library to open the C binding layer during runtime.

The sample program `tstXPCOMCGlue` is located in the bin directory and can be run without arguments. It lists registered machines on the host along with some additional information and ask for a machine to start. The source for this program is available in `sdk/bindings/xpcom/cbinding/samples/` directory. The source for the VBoxGlue library is available in the `sdk/bindings/xpcom/cbinding/` directory.

##### XPCOM initialization

Just like in C++, XPCOM needs to be initialized before it can be used. The `VBoxCAPI_v2_5.h` header provides the interface to the C binding. Here's how to initialize XPCOM:

    #include "VBoxCAPI_v2_5.h"
    ...
    PCVBOXXPCOM g_pVBoxFuncs = NULL;
    IVirtualBox *vbox        = NULL;
    ISession *session        = NULL;

    /*
     * VBoxGetXPCOMCFunctions() is the only function exported by
     * VBoxXPCOMC.so and the only one needed to make virtualbox
     * work with C. This functions gives you the pointer to the
     * function table (g_pVBoxFuncs).
     *
     * Once you get the function table, then how and which functions
     * to use is explained below.
     *
     * g_pVBoxFuncs->pfnComInitialize does all the necessary startup
     * action and provides us with pointers to vbox and session handles.
     * It should be matched by a call to g_pVBoxFuncs->pfnComUninitialize()
     * when done.
     */

    g_pVBoxFuncs = VBoxGetXPCOMCFunctions(VBOX_XPCOMC_VERSION);
    g_pVBoxFuncs->pfnComInitialize(&vbox, &session);

If either `vbox` or `session` is still `NULL`, initialization failed and the XPCOM API cannot be used.

##### XPCOM method invocation

Method invocation is straightforward. It looks pretty much like the C++ way, augmented with an extra indirection due to accessing the vtable and passing a pointer to the object as the first argument to serve as the `this` pointer.

Using the C binding, all method invocations return a numeric result code.

If an interface is specified as returning an object, a pointer to a pointer to the appropriate object must be passed as the last argument. The method will then store an object pointer in that location.

In other words, to call an object's method what you need is

    IObject *object;
    nsresult rc;
    ...
    /*
     * Calling void IObject::method(arg, ...)
     */
    rc = object->vtbl->Method(object, arg, ...);

    ...
    IFoo *foo;
    /*
     * Calling IFoo IObject::method(arg, ...)
     */
    rc = object->vtbl->Method(object, args, ..., &foo);

As a real-world example of a method invocation, let's call which returns an IProgress object. Note again that the method name is capitalized.

    IProgress *progress;
    ...
    rc = vbox->vtbl->LaunchVMProcess(
        machine,       /* this  */
        session,       /* arg 1 */
        sessionType,   /* arg 2 */
        env,           /* arg 3 */
        &progress      /* Out   */
    );

##### XPCOM attribute access

A construct similar to calling non-void methods is used to access object attributes. For each attribute there exists a getter method, the name of which is composed of `Get` followed by the capitalized attribute name. Unless the attribute is read-only, an analogous `Set` method exists. Let's apply these rules to read the attribute.

Using the `IVirtualBox` handle `vbox` obtained above, calling its `GetRevision` method looks like this:

    PRUint32   rev;

    rc = vbox->vtbl->GetRevision(vbox, &rev);
    if (NS_SUCCEEDED(rc))
    {
        printf("Revision: %u\n", (unsigned)rev);
    }

All objects with their methods and attributes are documented in .

##### String handling

When dealing with strings you have to be aware of a string's encoding and ownership.

Internally, XPCOM uses UTF-16 encoded strings. A set of conversion functions is provided to convert other encodings to and from UTF-16. The type of a UTF-16 character is `PRUnichar`. Strings of UTF-16 characters are arrays of that type. Most string handling functions take pointers to that type. Prototypes for the following conversion functions are declared in `VBoxCAPI_v2_5.h`.

###### Conversion of UTF-16 to and from UTF-8

    int (*pfnUtf16ToUtf8)(const PRUnichar *pwszString, char **ppszString);
    int (*pfnUtf8ToUtf16)(const char *pszString, PRUnichar **ppwszString);

###### Ownership

The ownership of a string determines who is responsible for releasing resources associated with the string. Whenever XPCOM creates a string, ownership is transferred to the caller. To avoid resource leaks, the caller should release resources once the string is no longer needed.

##### XPCOM uninitialization

Uninitialization is performed by `g_pVBoxFuncs->pfnComUninitialize().` If your program can exit from more than one place, it is a good idea to install this function as an exit handler with Standard C's `atexit()` just after calling `g_pVBoxFuncs->pfnComInitialize()` , e.g.

    #include <stdlib.h>
    #include <stdio.h>

    ...

    /*
     * Make sure g_pVBoxFuncs->pfnComUninitialize() is called at exit, no
     * matter if we return from the initial call to main or call exit()
     * somewhere else. Note that atexit registered functions are not
     * called upon abnormal termination, i.e. when calling abort() or
     * signal(). Separate provisions must be taken for these cases.
     */

    if (atexit(g_pVBoxFuncs->pfnComUninitialize()) != 0) {
        fprintf(stderr, "failed to register g_pVBoxFuncs->pfnComUninitialize()\n");
        exit(EXIT_FAILURE);
    }

Another idea would be to write your own `void myexit(int status)` function, calling `g_pVBoxFuncs->pfnComUninitialize()` followed by the real `exit()`, and use it instead of `exit()` throughout your program and at the end of `main.`

If you expect the program to be terminated by a signal (e.g. user types CTRL-C sending SIGINT) you might want to install a signal handler setting a flag noting that a signal was sent and then calling `g_pVBoxFuncs->pfnComUninitialize()` later on (usually not from the handler itself .)

That said, if a client program forgets to call `g_pVBoxFuncs->pfnComUninitialize()` before it terminates, there is a mechanism in place which will eventually release references held by the client. You should not rely on this, however.

##### Compiling and linking

A program using the C binding has to open the library during runtime using the help of glue code provided and as shown in the example `tstXPCOMCGlue.c`. Compilation and linking can be achieved, e.g., with a makefile fragment similar to

    # Where is the XPCOM include directory?
    INCS_XPCOM    = -I../../include
    # Where is the glue code directory?
    GLUE_DIR      = ..
    GLUE_INC      = -I..

    #Compile Glue Library
    VBoxXPCOMCGlue.o: $(GLUE_DIR)/VBoxXPCOMCGlue.c
        $(CC) $(CFLAGS) $(INCS_XPCOM) $(GLUE_INC) -o $@ -c $<

    # Compile.
    program.o: program.c VBoxCAPI_v2_5.h
        $(CC) $(CFLAGS) $(INCS_XPCOM) $(GLUE_INC) -o $@ -c $<

    # Link.
    program: program.o VBoxXPCOMCGlue.o
        $(CC) -o $@ $^ -ldl

## Basic VirtualBox concepts; some examples

The following explains some basic VirtualBox concepts such as the VirtualBox object, sessions and how virtual machines are manipulated and launched using the Main API. The coding examples use a pseudo-code style closely related to the object-oriented web service (OOWS) for JAX-WS. Depending on which environment you are using, you will need to adjust the examples.

### Obtaining basic machine information. Reading attributes

Any program using the Main API will first need access to the global VirtualBox object (see ), from which all other functionality of the API is derived. With the OOWS for JAX-WS, this is returned from the call.

To enumerate virtual machines, one would look at the "machines" array attribute in the VirtualBox object (see ). This array contains all virtual machines currently registered with the host, each of them being an instance of . From each such instance, one can query additional information, such as the UUID, the name, memory, operating system and more by looking at the attributes; see the attributes list in .

As mentioned in the preceding chapters, depending on your programming environment, attributes are mapped to corresponding "get" and (if the attribute is not read-only) "set" methods. So when the documentation says that IMachine has a "" attribute, this means you need to code something like the following to get the machine's name:

    IMachine machine = ...;
    String name = machine.getName();

Boolean attribute getters can sometimes be called `isAttribute()` due to JAX-WS naming conventions.

### Changing machine settings. Sessions

As said in the previous section, to read a machine's attribute, one invokes the corresponding "get" method. One would think that to change settings of a machine, it would suffice to call the corresponding "set" method -- for example, to set a VM's memory to 1024 MB, one would call `setMemorySize(1024)`. Try that, and you will get an error: "The machine is not mutable."

So unfortunately, things are not that easy. VirtualBox is a complicated environment in which multiple processes compete for possibly the same resources, especially machine settings. As a result, machines must be "locked" before they can either be modified or started. This is to prevent multiple processes from making conflicting changes to a machine: it should, for example, not be allowed to change the memory size of a virtual machine while it is running. (You can't add more memory to a real computer while it is running either, at least not to an ordinary PC.) Also, two processes must not change settings at the same time, or start a machine at the same time.

These requirements are implemented in the Main API by way of "sessions", in particular, the interface. Each process which talks to VirtualBox needs its own instance of ISession. In the web service, you cannot create such an object, but `vboxwebsrv` creates one for you when you log on, which you can obtain by calling .

This session object must then be used like a mutex semaphore in common programming environments. Before you can change machine settings, you must write-lock the machine by calling with your process's session object.

After the machine has been locked, the attribute contains a copy of the original IMachine object upon which the session was opened, but this copy is "mutable": you can invoke "set" methods on it.

When done making the changes to the machine, you must call , which will copy the changes you have made from your "mutable" machine back to the real machine and write them out to the machine settings XML file. This will make your changes permanent.

Finally, it is important to always unlock the machine again, by calling . Otherwise, when the calling process end, the machine will receive the "aborted" state, which can lead to loss of data.

So, as an example, the sequence to change a machine's memory to 1024 MB is something like this:

    IWebsessionManager mgr ...;
    IVirtualBox vbox = mgr.logon(user, pass);
    ...
    IMachine machine = ...;  // read-only machine
    ISession session = mgr.getSessionObject();
    machine.lockMachine(session, LockType.Write); // machine is now locked for writing
    IMachine mutable = session.getMachine();      // obtain the mutable machine copy
    mutable.setMemorySize(1024);
    mutable.saveSettings();                       // write settings to XML
    session.unlockMachine();

### Launching virtual machines

To launch a virtual machine, you call . In doing so, the caller instructs the VirtualBox engine to start a new process with the virtual machine in it, since to the host, each virtual machine looks like a single process, even if it has hundreds of its own processes inside. (This new VM process in turn obtains a write lock on the machine, as described above, to prevent conflicting changes from other processes; this is why opening another session will fail while the VM is running.)

Starting a machine looks something like this:

    IWebsessionManager mgr ...;
    IVirtualBox vbox = mgr.logon(user, pass);
    ...
    IMachine machine = ...;  // read-only machine
    ISession session = mgr.getSessionObject();
    IProgress prog = machine.launchVMProcess(session,
                                             "gui",  // session type
                                             "");    // possibly environment setting
    prog.waitForCompletion(10000);  // give the process 10 secs
    if (prog.getResultCode() != 0)  // check success
        System.out.println("Cannot launch VM!")

The caller's session object can then be used as a sort of remote control to the VM process that was launched. It contains a "console" object (see ) with which the VM can be paused, stopped, snapshotted or other things.

### VirtualBox events

In VirtualBox, "events" provide a uniform mechanism to register for and consume specific events. A VirtualBox client can register an "event listener" (represented by the interface), which will then get notified by the server when an event (represented by the interface) happens.

The IEvent interface is an abstract parent interface for all events that can occur in VirtualBox. The actual events that the server sends out are then of one of the specific subclasses, for example or .

As an example, the VirtualBox GUI waits for machine events and can thus update its display when the machine state changes or machine settings are modified, even if this happens in another client. This is how the GUI can automatically refresh its display even if you manipulate a machine from another client, for example, from VBoxManage.

To register an event listener to listen to events, use code like this:

    EventSource es = console.getEventSource();
    IEventListener listener = es.createListener();
    VBoxEventType aTypes[] = (VBoxEventType.OnMachineStateChanged);
            // list of event types to listen for
    es.registerListener(listener, aTypes, false /* active */);
            // register passive listener
    IEvent ev = es.getEvent(listener, 1000);
            // wait up to one second for event to happen
    if (ev != null)
    {
        // downcast to specific event interface (in this case we have only registered
        // for one type, otherwise IEvent::type would tell us)
        IMachineStateChangedEvent mcse = IMachineStateChangedEvent.queryInterface(ev);
        ... // inspect and do something
        es.eventProcessed(listener, ev);
    }
    ...
    es.unregisterListener(listener);

A graphical user interface would probably best start its own thread to wait for events and then process these in a loop.

The events mechanism was introduced with VirtualBox 3.3 and replaces various callback interfaces which were called for each event in the interface. The callback mechanism was not compatible with scripting languages, local Java bindings and remote web services as they do not support callbacks. The new mechanism with events and event listeners works with all of these.

To simplify developement of application using events, concept of event aggregator was introduced. Essentially it's mechanism to aggregate multiple event sources into single one, and then work with this single aggregated event source instead of original sources. As an example, one can evaluate demo recorder in VirtualBox Python shell, shipped with SDK - it records mouse and keyboard events, represented as separate event sources. Code is essentially like this:

              listener = console.eventSource.createListener()
              agg = console.eventSource.createAggregator([console.keyboard.eventSource, console.mouse.eventSource])
              agg.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], False)
              registered = True
              end = time.time() + dur
              while  time.time() < end:
                  ev = agg.getEvent(listener, 1000)
                  processEent(ev)
              agg.unregisterListener(listener)

Without using aggregators consumer have to poll on both sources, or start multiple threads to block on those sources.

## The VirtualBox shell

VirtualBox comes with an extensible shell, which allows you to control your virtual machines from the command line. It is also a nontrivial example of how to use the VirtualBox APIs from Python, for all three COM/XPCOM/WS styles of the API.

You can easily extend this shell with your own commands. Create a subdirectory named `.VirtualBox/shexts` below your home directory and put a Python file implementing your shell extension commands in this directory. This file must contain an array named `commands` containing your command definitions:

            commands = {
            'cmd1': ['Command cmd1 help', cmd1],
            'cmd2': ['Command cmd2 help', cmd2]
            }

For example, to create a command for creating hard drive images, the following code can be used:

            def createHdd(ctx,args):
              # Show some meaningful error message on wrong input
              if (len(args) < 3):
                print "usage: createHdd sizeM location type"
                return 0

              # Get arguments
              size = int(args[1])
              loc = args[2]
              if len(args) > 3:
                format = args[3]
              else:
                # And provide some meaningful defaults
                format = "vdi"

            # Call VirtualBox API, using context's fields
            hdd = ctx['vb'].createHardDisk(format, loc)
            # Access constants using ctx['global'].constants
            progress = hdd.createBaseStorage(size, ctx['global'].constants.HardDiskVariant_Standard)
            # use standard progress bar mechanism
            ctx['progressBar'](progress)

            # Report errors
            if not hdd.id:
               print "cannot create disk (file %s exist?)" %(loc)
               return 0

            # Give user some feedback on success too
            print "created HDD with id: %s" %(hdd.id)

            # 0 means continue execution, other values mean exit from the interpreter
            return 0

          commands = {
            'myCreateHDD': ['Create virtual HDD, createHdd size location type', createHdd]
            }

Just store the above text in the file `createHdd` (or any other meaningful name) in `.VirtualBox/shexts/`. Start the VirtualBox shell, or just issue the `reloadExts` command, if the shell is already running. Your new command will now be available.

## Host-Guest Communication Manager

The VirtualBox Host-Guest Communication Manager (HGCM) allows a guest application or a guest driver to call a host shared library. The following features of VirtualBox are implemented using HGCM:

- Shared Folders

- Shared Clipboard

- Guest configuration interface

The shared library contains a so called HGCM service. The guest HGCM clients establish connections to the service to call it. When calling a HGCM service the client supplies a function code and a number of parameters for the function.

### Virtual hardware implementation

HGCM uses the VMM virtual PCI device to exchange data between the guest and the host. The guest always acts as an initiator of requests. A request is constructed in the guest physical memory, which must be locked by the guest. The physical address is passed to the VMM device using a 32 bit `out edx, eax` instruction. The physical memory must be allocated below 4GB by 64 bit guests.

The host parses the request header and data and queues the request for a host HGCM service. The guest continues execution and usually waits on a HGCM event semaphore.

When the request has been processed by the HGCM service, the VMM device sets the completion flag in the request header, sets the HGCM event and raises an IRQ for the guest. The IRQ handler signals the HGCM event semaphore and all HGCM callers check the completion flag in the corresponding request header. If the flag is set, the request is considered completed.

### Protocol specification

The HGCM protocol definitions are contained in the `VBox/VBoxGuest.h`

#### Request header

HGCM request structures contains a generic header (VMMDevHGCMRequestHeader):

HGCM Request Generic Header

Name | Description
size | Size of the entire request.
version | Version of the header, must be set to `0x10001`.
type | Type of the request.
rc | HGCM return code, which will be set by the VMM device.
reserved1 | A reserved field 1.
reserved2 | A reserved field 2.
flags | HGCM flags, set by the VMM device.
result | The HGCM result code, set by the VMM device.

- All fields are 32 bit.

- Fields from `size` to `reserved2` are a standard VMM device request header, which is used for other interfaces as well.

The type field indicates the type of the HGCM request:

Request Types

Name (decimal value) | Description
VMMDevReq_HGCMConnect (`60`) | Connect to a HGCM service.
VMMDevReq_HGCMDisconnect (`61`) | Disconnect from the service.
VMMDevReq_HGCMCall32 (`62`) | Call a HGCM function using the 32 bit interface.
VMMDevReq_HGCMCall64 (`63`) | Call a HGCM function using the 64 bit interface.
VMMDevReq_HGCMCancel (`64`) | Cancel a HGCM request currently being processed by a host HGCM service.

The flags field may contain:

Flags

Name (hexadecimal value) | Description
VBOX_HGCM_REQ_DONE (`0x00000001`) | The request has been processed by the host service.
VBOX_HGCM_REQ_CANCELLED (`0x00000002`) | This request was cancelled.

#### Connect

The connection request must be issued by the guest HGCM client before it can call the HGCM service (VMMDevHGCMConnect):

Connect request

Name | Description
header | The generic HGCM request header with type equal to VMMDevReq_HGCMConnect (`60`).
type | The type of the service location information (32 bit).
location | The service location information (128 bytes).
clientId | The client identifier assigned to the connecting client by the HGCM subsystem (32 bit).

The type field tells the HGCM how to look for the requested service:

Location Information Types

Name (hexadecimal value) | Description
VMMDevHGCMLoc_LocalHost (`0x1`) | The requested service is a shared library located on the host and the location information contains the library name.
VMMDevHGCMLoc_LocalHost_Existing (`0x2`) | The requested service is a preloaded one and the location information contains the service name.

Currently preloaded HGCM services are hard-coded in VirtualBox:

- VBoxSharedFolders

- VBoxSharedClipboard

- VBoxGuestPropSvc

- VBoxSharedOpenGL

There is no difference between both types of HGCM services, only the location mechanism is different.

The client identifier is returned by the host and must be used in all subsequent requests by the client.

#### Disconnect

This request disconnects the client and makes the client identifier invalid (VMMDevHGCMDisconnect):

Disconnect request

Name | Description
header | The generic HGCM request header with type equal to VMMDevReq_HGCMDisconnect (`61`).
clientId | The client identifier previously returned by the connect request (32 bit).

#### Call32 and Call64

Calls the HGCM service entry point (VMMDevHGCMCall) using 32 bit or 64 bit addresses:

Call request

Name | Description
header | The generic HGCM request header with type equal to either VMMDevReq_HGCMCall32 (`62`) or VMMDevReq_HGCMCall64 (`63`).
clientId | The client identifier previously returned by the connect request (32 bit).
function | The function code to be processed by the service (32 bit).
cParms | The number of following parameters (32 bit). This value is 0 if the function requires no parameters.
parms | An array of parameter description structures (HGCMFunctionParameter32 or HGCMFunctionParameter64).

The 32 bit parameter description (HGCMFunctionParameter32) consists of 32 bit type field and 8 bytes of an opaque value, so 12 bytes in total. The 64 bit variant (HGCMFunctionParameter64) consists of the type and 12 bytes of a value, so 16 bytes in total.

Parameter types

Type | Format of the value
VMMDevHGCMParmType_32bit (1) | A 32 bit value.
VMMDevHGCMParmType_64bit (2) | A 64 bit value.
VMMDevHGCMParmType_PhysAddr (3) | A 32 bit size followed by a 32 bit or 64 bit guest physical address.
VMMDevHGCMParmType_LinAddr (4) | A 32 bit size followed by a 32 bit or 64 bit guest linear address. The buffer is used both for guest to host and for host to guest data.
VMMDevHGCMParmType_LinAddr_In (5) | Same as VMMDevHGCMParmType_LinAddr but the buffer is used only for host to guest data.
VMMDevHGCMParmType_LinAddr_Out (6) | Same as VMMDevHGCMParmType_LinAddr but the buffer is used only for guest to host data.
VMMDevHGCMParmType_LinAddr_Locked (7) | Same as VMMDevHGCMParmType_LinAddr but the buffer is already locked by the guest.
VMMDevHGCMParmType_LinAddr_Locked_In (1) | Same as VMMDevHGCMParmType_LinAddr_In but the buffer is already locked by the guest.
VMMDevHGCMParmType_LinAddr_Locked_Out (1) | Same as VMMDevHGCMParmType_LinAddr_Out but the buffer is already locked by the guest.

The

#### Cancel

This request cancels a call request (VMMDevHGCMCancel):

Cancel request

Name | Description
header | The generic HGCM request header with type equal to VMMDevReq_HGCMCancel (`64`).

### Guest software interface

The guest HGCM clients can call HGCM services from both drivers and applications.

#### The guest driver interface

The driver interface is implemented in the VirtualBox guest additions driver (VBoxGuest), which works with the VMM virtual device. Drivers must use the VBox Guest Library (VBGL), which provides an API for HGCM clients (`VBox/VBoxGuestLib.h` and `VBox/VBoxGuest.h`).

    DECLVBGL(int) VbglHGCMConnect (VBGLHGCMHANDLE *pHandle, VBoxGuestHGCMConnectInfo *pData);

Connects to the service:

        VBoxGuestHGCMConnectInfo data;

        memset (&data, sizeof (VBoxGuestHGCMConnectInfo));

        data.result   = VINF_SUCCESS;
        data.Loc.type = VMMDevHGCMLoc_LocalHost_Existing;
        strcpy (data.Loc.u.host.achName, "VBoxSharedFolders");

        rc = VbglHGCMConnect (&handle, &data);

        if (RT_SUCCESS (rc))
        {
            rc = data.result;
        }

        if (RT_SUCCESS (rc))
        {
            /* Get the assigned client identifier. */
            ulClientID = data.u32ClientID;
        }

    DECLVBGL(int) VbglHGCMDisconnect (VBGLHGCMHANDLE handle, VBoxGuestHGCMDisconnectInfo *pData);

Disconnects from the service.

        VBoxGuestHGCMDisconnectInfo data;

        RtlZeroMemory (&data, sizeof (VBoxGuestHGCMDisconnectInfo));

        data.result      = VINF_SUCCESS;
        data.u32ClientID = ulClientID;

        rc = VbglHGCMDisconnect (handle, &data);

    DECLVBGL(int) VbglHGCMCall (VBGLHGCMHANDLE handle, VBoxGuestHGCMCallInfo *pData, uint32_t cbData);

Calls a function in the service.

    typedef struct _VBoxSFRead
    {
        VBoxGuestHGCMCallInfo callInfo;

        /** pointer, in: SHFLROOT
         * Root handle of the mapping which name is queried.
         */
        HGCMFunctionParameter root;

        /** value64, in:
         * SHFLHANDLE of object to read from.
         */
        HGCMFunctionParameter handle;

        /** value64, in:
         * Offset to read from.
         */
        HGCMFunctionParameter offset;

        /** value64, in/out:
         * Bytes to read/How many were read.
         */
        HGCMFunctionParameter cb;

        /** pointer, out:
         * Buffer to place data to.
         */
        HGCMFunctionParameter buffer;

    } VBoxSFRead;

    /** Number of parameters */
    #define SHFL_CPARMS_READ (5)

    ...

        VBoxSFRead data;

        /* The call information. */
        data.callInfo.result      = VINF_SUCCESS;     /* Will be returned by HGCM. */
        data.callInfo.u32ClientID = ulClientID;       /* Client identifier. */
        data.callInfo.u32Function = SHFL_FN_READ;     /* The function code. */
        data.callInfo.cParms      = SHFL_CPARMS_READ; /* Number of parameters. */

        /* Initialize parameters. */
        data.root.type                      = VMMDevHGCMParmType_32bit;
        data.root.u.value32                 = pMap->root;

        data.handle.type                    = VMMDevHGCMParmType_64bit;
        data.handle.u.value64               = hFile;

        data.offset.type                    = VMMDevHGCMParmType_64bit;
        data.offset.u.value64               = offset;

        data.cb.type                        = VMMDevHGCMParmType_32bit;
        data.cb.u.value32                   = *pcbBuffer;

        data.buffer.type                    = VMMDevHGCMParmType_LinAddr_Out;
        data.buffer.u.Pointer.size          = *pcbBuffer;
        data.buffer.u.Pointer.u.linearAddr  = (uintptr_t)pBuffer;

        rc = VbglHGCMCall (handle, &data.callInfo, sizeof (data));

        if (RT_SUCCESS (rc))
        {
            rc = data.callInfo.result;
            *pcbBuffer = data.cb.u.value32; /* This is returned by the HGCM service. */
        }

#### Guest application interface

Applications call the VirtualBox Guest Additions driver to utilize the HGCM interface. There are IOCTL's which correspond to the `Vbgl*` functions:

- `VBOXGUEST_IOCTL_HGCM_CONNECT`

- `VBOXGUEST_IOCTL_HGCM_DISCONNECT`

- `VBOXGUEST_IOCTL_HGCM_CALL`

These IOCTL's get the same input buffer as `VbglHGCM*` functions and the output buffer has the same format as the input buffer. The same address can be used as the input and output buffers.

For example see the guest part of shared clipboard, which runs as an application and uses the HGCM interface.

### HGCM Service Implementation

The HGCM service is a shared library with a specific set of entry points. The library must export the `VBoxHGCMSvcLoad` entry point:

    extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad (VBOXHGCMSVCFNTABLE *ptable)

The service must check the `ptable->cbSize` and `ptable->u32Version` fields of the input structure and fill the remaining fields with function pointers of entry points and the size of the required client buffer size.

The HGCM service gets a dedicated thread, which calls service entry points synchronously, that is the service will be called again only when a previous call has returned. However, the guest calls can be processed asynchronously. The service must call a completion callback when the operation is actually completed. The callback can be issued from another thread as well.

Service entry points are listed in the `VBox/hgcmsvc.h` in the `VBOXHGCMSVCFNTABLE` structure.

Service entry points

Entry | Description
pfnUnload | The service is being unloaded.
pfnConnect | A client `u32ClientID` is connected to the service. The `pvClient` parameter points to an allocated memory buffer which can be used by the service to store the client information.
pfnDisconnect | A client is being disconnected.
pfnCall | A guest client calls a service function. The `callHandle` must be used in the VBOXHGCMSVCHELPERS::pfnCallComplete callback when the call has been processed.
pfnHostCall | Called by the VirtualBox host components to perform functions which should be not accessible by the guest. Usually this entry point is used by VirtualBox to configure the service.
pfnSaveState | The VM state is being saved and the service must save relevant information using the SSM API (`VBox/ssm.h`).
pfnLoadState | The VM is being restored from the saved state and the service must load the saved information and be able to continue operations from the saved state.

## RDP Web Control

The VirtualBox RDP Web Control (RDPWeb) provides remote access to a running VM. RDPWeb is a RDP (Remote Desktop Protocol) client based on Flash technology and can be used from a Web browser with a Flash plugin.

### RDPWeb features

RDPWeb is embedded into a Web page and can connect to VRDP server in order to displays the VM screen and pass keyboard and mouse events to the VM.

### RDPWeb reference

RDPWeb consists of two required components:

- Flash movie `RDPClientUI.swf`

- JavaScript helpers `webclient.js`

The VirtualBox SDK contains sample HTML code including:

- JavaScript library for embedding Flash content `SWFObject.js`

- Sample HTML page `webclient3.html`

#### RDPWeb functions

`RDPClientUI.swf` and `webclient.js` work with each other. JavaScript code is responsible for a proper SWF initialization, delivering mouse events to the SWF and processing resize requests from the SWF. On the other hand, the SWF contains a few JavaScript callable methods, which are used both from `webclient.js` and the user HTML page.

##### JavaScript functions

`webclient.js` contains helper functions. In the following table ElementId refers to an HTML element name or attribute, and Element to the HTML element itself. HTML code

        <div id="FlashRDP">
        </div>

would have ElementId equal to FlashRDP and Element equal to the div element.

-     RDPWebClient.embedSWF(SWFFileName, ElementId)

  Uses SWFObject library to replace the HTML element with the Flash movie.

-     RDPWebClient.isRDPWebControlById(ElementId)

  Returns true if the given id refers to a RDPWeb Flash element.

-     RDPWebClient.isRDPWebControlByElement(Element)

  Returns true if the given element is a RDPWeb Flash element.

-     RDPWebClient.getFlashById(ElementId)

  Returns an element, which is referenced by the given id. This function will try to resolve any element, event if it is not a Flash movie.

##### Flash methods callable from JavaScript

`RDPWebClienUI.swf` methods can be called directly from JavaScript code on a HTML page.

- getProperty(Name)

- setProperty(Name)

- connect()

- disconnect()

- keyboardSendCAD()

##### Flash JavaScript callbacks

`RDPWebClienUI.swf` calls JavaScript functions provided by the HTML page.

#### Embedding RDPWeb in an HTML page

It is necessary to include `webclient.js` helper script. If SWFObject library is used, the `swfobject.js` must be also included and RDPWeb flash content can be embedded to a Web page using dynamic HTML. The HTML must include a "placeholder", which consists of 2 `div` elements.

### RDPWeb change log

#### Version 1.2.28

- `keyboardLayout`, `keyboardLayouts`, `UUID` properties.

- Support for German keyboard layout on the client.

- Rebranding to Oracle.

#### Version 1.1.26

- `webclient.js` is a part of the distribution package.

- `lastError` property.

- `keyboardSendScancodes` and `keyboardSendCAD` methods.

#### Version 1.0.24

- Initial release.

## VirtualBox external authentication modules

VirtualBox supports arbitrary external modules to perform authentication. The module is used when the authentication method is set to "external" for a particular VM VRDE access and the library was specified with `VBoxManage setproperty vrdeauthlibrary`. Web service also use the authentication module which was specified with `VBoxManage setproperty websrvauthlibrary`.

This library will be loaded by the VM or web service process on demand, i.e. when the first remote desktop connection is made by a client or when a client that wants to use the web service logs on.

External authentication is the most flexible as the external handler can both choose to grant access to everyone (like the "null" authentication method would) and delegate the request to the guest authentication component. When delegating the request to the guest component, the handler will still be called afterwards with the option to override the result.

An authentication library is required to implement exactly one entry point:

    #include "VBoxAuth.h"

    /**
     * Authentication library entry point.
     *
     * Parameters:
     *
     *   szCaller         The name of the component which calls the library (UTF8).
     *   pUuid            Pointer to the UUID of the accessed virtual machine. Can be NULL.
     *   guestJudgement   Result of the guest authentication.
     *   szUser           User name passed in by the client (UTF8).
     *   szPassword       Password passed in by the client (UTF8).
     *   szDomain         Domain passed in by the client (UTF8).
     *   fLogon           Boolean flag. Indicates whether the entry point is called
     *                    for a client logon or the client disconnect.
     *   clientId         Server side unique identifier of the client.
     *
     * Return code:
     *
     *   AuthResultAccessDenied    Client access has been denied.
     *   AuthResultAccessGranted   Client has the right to use the
     *                             virtual machine.
     *   AuthResultDelegateToGuest Guest operating system must
     *                             authenticate the client and the
     *                             library must be called again with
     *                             the result of the guest
     *                             authentication.
     *
     * Note: When 'fLogon' is 0, only pszCaller, pUuid and clientId are valid and the return
     *       code is ignored.
     */
    AuthResult AUTHCALL AuthEntry(
        const char *szCaller,
        PAUTHUUID pUuid,
        AuthGuestJudgement guestJudgement,
        const char *szUser,
        const char *szPassword
        const char *szDomain
        int fLogon,
        unsigned clientId)
    {
        /* Process request against your authentication source of choice. */
        // if (authSucceeded(...))
        //     return AuthResultAccessGranted;
        return AuthResultAccessDenied;
    }

A note regarding the UUID implementation of the `pUuid` argument: VirtualBox uses a consistent binary representation of UUIDs on all platforms. For this reason the integer fields comprising the UUID are stored as little endian values. If you want to pass such UUIDs to code which assumes that the integer fields are big endian (often also called network byte order), you need to adjust the contents of the UUID to e.g. achieve the same string representation. The required changes are:

- reverse the order of byte 0, 1, 2 and 3

- reverse the order of byte 4 and 5

- reverse the order of byte 6 and 7.

Using this conversion you will get identical results when converting the binary UUID to the string representation.

The `guestJudgement` argument contains information about the guest authentication status. For the first call, it is always set to `AuthGuestNotAsked`. In case the `AuthEntry` function returns `AuthResultDelegateToGuest`, a guest authentication will be attempted and another call to the `AuthEntry` is made with its result. This can be either granted / denied or no judgement (the guest component chose for whatever reason to not make a decision). In case there is a problem with the guest authentication module (e.g. the Additions are not installed or not running or the guest did not respond within a timeout), the "not reacted" status will be returned.

## Using Java API

### Introduction

VirtualBox can be controlled by a Java API, both locally (COM/XPCOM) and from remote (SOAP) clients. As with the Python bindings, a generic glue layer tries to hide all platform differences, allowing for source and binary compatibility on different platforms.

### Requirements

To use the Java bindings, there are certain requirements depending on the platform. First of all, you need JDK 1.5 (Java 5) or later. Also please make sure that the version of the VirtualBox API .jar file exactly matches the version of VirtualBox you use. To avoid confusion, the VirtualBox API provides versioning in the Java package name, e.g. the package is named `org.virtualbox_3_2` for VirtualBox version 3.2.

- XPCOM: - for all platforms, but Microsoft Windows. A Java bridge based on JavaXPCOM is shipped with VirtualBox. The classpath must contain `vboxjxpcom.jar` and the `vbox.home` property must be set to location where the VirtualBox binaries are. Please make sure that the JVM bitness matches bitness of VirtualBox you use as the XPCOM bridge relies on native libraries.

  Start your application like this:

       java -cp vboxjxpcom.jar -Dvbox.home=/opt/virtualbox MyProgram

- COM: - for Microsoft Windows. We rely on `Jacob` - a generic Java to COM bridge - which has to be installed seperately. See http://sourceforge.net/projects/jacob-project/ for installation instructions. Also, the VirtualBox provided `vboxjmscom.jar` must be in the class path.

  Start your application like this:

       java -cp vboxjmscom.jar;c:\jacob\jacob.jar -Djava.library.path=c:\jacob MyProgram

- SOAP - all platforms. Java 6 is required, as it comes with builtin support for SOAP via the JAX-WS library. Also, the VirtualBox provided `vbojws.jar` must be in the class path. In the SOAP case it's possible to create several VirtualBoxManager instances to communicate with multiple VirtualBox hosts.

  Start your application like this:

       java -cp vboxjws.jar MyProgram

Exception handling is also generalized by the generic glue layer, so that all methods could throw `VBoxException` containing human-readable text message (see `getMessage()` method) along with wrapped original exception (see `getWrapped()` method).

### Example

This example shows a simple use case of the Java API. Differences for SOAP vs. local version are minimal, and limited to the connection setup phase (see `ws` variable). In the SOAP case it's possible to create several VirtualBoxManager instances to communicate with multiple VirtualBox hosts.

              import org.virtualbox_3_3.*;
              ....
              VirtualBoxManager mgr = VirtualBoxManager.createInstance(null);
              boolean ws = false; // or true, if we need the SOAP version
              if (ws)
              {
                  String url = "http://myhost:18034";
                  String user = "test";
                  String passwd = "test";
                  mgr.connect(url, user, passwd);
              }
              IVirtualBox vbox = mgr.getVBox();
              System.out.println("VirtualBox version: " + vbox.getVersion() + "\n");
              // get first VM name
              String m =  vbox.getMachines().get(0).getName();
              System.out.println("\nAttempting to start VM '" + m + "'");
              // start it
              mgr.startVm(m, null, 7000);

              if (ws)
                  mgr.disconnect();

              mgr.cleanup();

For more a complete example, see `TestVBox.java`, shipped with the SDK.

## License information

The sample code files shipped with the SDK are generally licensed liberally to make it easy for anyone to use this code for their own application code.

The Java files under `bindings/webservice/java/jax-ws/` (library files for the object-oriented web service) are, by contrast, licensed under the GNU Lesser General Public License (LGPL) V2.1.

See `sdk/bindings/webservice/java/jax-ws/src/COPYING.LIB` for the full text of the LGPL 2.1.

When in doubt, please refer to the individual source code files shipped with this SDK.

## Main API change log

Generally, VirtualBox will maintain API compatibility within a major release; a major release occurs when the first or the second of the three version components of VirtualBox change (that is, in the x.y.z scheme, a major release is one where x or y change, but not when only z changes).

In other words, updates like those from 2.0.0 to 2.0.2 will not come with API breakages.

Migration between major releases most likely will lead to API breakage, so please make sure you updated code accordingly. The OOWS Java wrappers enforce that mechanism by putting VirtualBox classes into version-specific packages such as `org.virtualbox_2_2`. This approach allows for connecting to multiple VirtualBox versions simultaneously from the same Java application.

The following sections list incompatible changes that the Main API underwent since the original release of this SDK Reference with VirtualBox 2.0. A change is deemed "incompatible" only if it breaks existing client code (e.g. changes in method parameter lists, renamed or removed interfaces and similar). In other words, the list does not contain new interfaces, methods or attributes or other changes that do not affect existing client code.

### Incompatible API changes with version 4.1

- The method has one more parameter now, which allows to configure the import process in more detail.

- The method has one more parameter now, which allows resolving duplicate medium UUIDs without the need for external tools.

- The interface has been cleaned up. The various methods to activate an attachment type have been replaced by the setter.

  Additionally each attachment mode now has its own attribute, which means that host only networks no longer share the settings with bridged interfaces.

  To allow introducing new network attachment implementations without making API changes, the concept of a generic network attachment driver has been introduced, which is configurable through key/value properties.

- This version introduces the guest facilities concept. A guest facility either represents a module or feature the guest is running or offering, which is defined by . Each facility is member of a and has a current status indicated by , together with a timestamp (in ms) of the last status update.

  To address the above concept, the following changes were made:

  - In the interface, the following were removed:

    - the `supportsSeamless` attribute;

    - the `supportsGraphics` attribute;

  - The function was added. It quickly provides a facility's status without the need to get the facility collection with .

  - The attribute was added to provide an easy to access collection of all currently known guest facilities, that is, it contains all facilies where at least one status update was made since the guest was started.

  - The interface was added to represent a single facility returned by .

  - was added to represent a facility's overall status.

  - and were added to represent the facility's type and class.

### Incompatible API changes with version 4.0

- A new Java glue layer replacing the previous OOWS JAX-WS bindings was introduced. The new library allows for uniform code targeting both local (COM/XPCOM) and remote (SOAP) transports. Now, instead of `IWebsessionManager`, the new class `VirtualBoxManager` must be used. See for details.

- The confusingly named and impractical session APIs were changed. In existing client code, the following changes need to be made:

  - Replace any `IVirtualBox::openSession(uuidMachine, ...)` API call with the machine's call and a `LockType.Write` argument. The functionality is unchanged, but instead of "opening a direct session on a machine" all documentation now refers to "obtaining a write lock on a machine for the client session".

  - Similarly, replace any `IVirtualBox::openExistingSession(uuidMachine, ...)` call with the machine's call and a `LockType.Shared` argument. Whereas it was previously impossible to connect a client session to a running VM process in a race-free manner, the new API will atomically either write-lock the machine for the current session or establish a remote link to an existing session. Existing client code which tried calling both `openSession()` and `openExistingSession()` can now use this one call instead.

  - Third, replace any `IVirtualBox::openRemoteSession(uuidMachine, ...)` call with the machine's call. The functionality is unchanged.

  - The enum was adjusted accordingly: "Open" is now "Locked", "Closed" is now "Unlocked", "Closing" is now "Unlocking".

- Virtual machines created with VirtualBox 4.0 or later no longer register their media in the global media registry in the `VirtualBox.xml` file. Instead, such machines list all their media in their own machine XML files. As a result, a number of media-related APIs had to be modified again.

  - Neither nor register media automatically any more.

  - and now take an IMedium object instead of a UUID as an argument. It is these two calls which add media to a registry now (either a machine registry for machines created with VirtualBox 4.0 or later or the global registry otherwise). As a consequence, if a medium is opened but never attached to a machine, it is no longer added to any registry any more.

  - To reduce code duplication, the APIs IVirtualBox::findHardDisk(), getHardDisk(), findDVDImage(), getDVDImage(), findFloppyImage() and getFloppyImage() have all been merged into , and IVirtualBox::openHardDisk(), openDVDImage() and openFloppyImage() have all been merged into .

  - The rare use case of changing the UUID and parent UUID of a medium previously handled by `openHardDisk()` is now in a separate method.

  - `ISystemProperties::get/setDefaultHardDiskFolder()` have been removed since disk images are now by default placed in each machine's folder.

  - The attribute replaces the `getMaxVDISize()` API call; this now uses bytes instead of megabytes.

- Machine management APIs were enhanced as follows:

  - is no longer restricted to creating machines in the default "Machines" folder, but can now create machines at arbitrary locations. For this to work, the parameter list had to be changed.

  - The long-deprecated `IVirtualBox::createLegacyMachine()` API has been removed.

  - To reduce code duplication and for consistency with the aforementioned media APIs, `IVirtualBox::getMachine()` has been merged with , and `IMachine::getSnapshot()` has been merged with .

  - `IVirtualBox::unregisterMachine()` was replaced with with additional functionality for cleaning up machine files.

  - `IConsole::forgetSavedState` has been renamed to .

- All event callbacks APIs were replaced with a new, generic event mechanism that can be used both locally (COM, XPCOM) and remotely (web services). Also, the new mechanism is usable from scripting languages and a local Java. See for details. The new concept will require changes to all clients that used event callbacks.

- `additionsActive()` was replaced with and in order to support a more detailed status of the current Guest Additions loading/readiness state. no longer returns the Guest Additions interface version but the installed Guest Additions version and revision in form of `3.3.0r12345`.

- To address shared folders auto-mounting support, the following APIs were extended to require an additional `automount` parameter:

  Also, a new property named `autoMount` was added to the interface.

- The appliance (OVF) APIs were enhanced as follows:

  - received an extra parameter `location`, which is used to decide for the disk naming.

  - received an extra parameter `manifest`, which can suppress creating the manifest file on export.

  - received two extra parameters `sizes` and `modes`, which contains the sizes (in bytes) and the file access modes (in octal form) of the returned files.

- Support for remote desktop access to virtual machines has been cleaned up to allow third party implementations of the remote desktop server. This is called the VirtualBox Remote Desktop Extension (VRDE) and can be added to VirtualBox by installing the corresponding extension package; see the VirtualBox User Manual for details.

  The following API changes were made to support the VRDE interface:

  - `IVRDPServer` has been renamed to .

  - `IRemoteDisplayInfo` has been renamed to .

  - replaces `VRDPServer.`

  - replaces `RemoteDisplayInfo`.

  - replaces `RemoteDisplayAuthLibrary`.

  - The following methods have been implemented in `IVRDEServer` to support generic VRDE properties:

    A few implementation-specific attributes of the old `IVRDPServer` interface have been removed and replaced with properties:

    - `IVRDPServer::Ports` has been replaced with the `"TCP/Ports"` property. The property value is a string, which contains a comma-separated list of ports or ranges of ports. Use a dash between two port numbers to specify a range. Example: `"5000,5010-5012"`

    - `IVRDPServer::NetAddress` has been replaced with the `"TCP/Address"` property. The property value is an IP address string. Example: `"127.0.0.1"`

    - `IVRDPServer::VideoChannel` has been replaced with the `"VideoChannel/Enabled"` property. The property value is either `"true"` or `"false"`

    - `IVRDPServer::VideoChannelQuality` has been replaced with the `"VideoChannel/Quality"` property. The property value is a string which contain a decimal number in range 10..100. Invalid values are ignored and the quality is set to the default value 75. Example: `"50"`

- The VirtualBox external authentication module interface has been updated and made more generic. Because of that, `VRDPAuthType` enumeration has been renamed to .

### Incompatible API changes with version 3.2

- The following interfaces were renamed for consistency:

  - IMachine::getCpuProperty() is now ;

  - IMachine::setCpuProperty() is now ;

  - IMachine::getCpuIdLeaf() is now ;

  - IMachine::setCpuIdLeaf() is now ;

  - IMachine::removeCpuIdLeaf() is now ;

  - IMachine::removeAllCpuIdLeafs() is now ;

  - the CpuPropertyType enum is now .

  - IVirtualBoxCallback::onSnapshotDiscarded() is now IVirtualBoxCallback::onSnapshotDeleted.

- When creating a VM configuration with ) it is now possible to ignore existing configuration files which would previously have caused a failure. For this the `override` parameter was added.

- Deleting snapshots via is now possible while the associated VM is running in almost all cases. The API is unchanged, but client code that verifies machine states to determine whether snapshots can be deleted may need to be adjusted.

- The IoBackendType enumeration was replaced with a boolean flag (see ).

- To address multi-monitor support, the following APIs were extended to require an additional `screenId` parameter:

- The `shape` parameter of IConsoleCallback::onMousePointerShapeChange was changed from a implementation-specific pointer to a safearray, enabling scripting languages to process pointer shapes.

### Incompatible API changes with version 3.1

- Due to the new flexibility in medium attachments that was introduced with version 3.1 (in particular, full flexibility with attaching CD/DVD drives to arbitrary controllers), we seized the opportunity to rework all interfaces dealing with storage media to make the API more flexible as well as logical. The , , and, interfaces were affected the most. Existing code using them to configure storage and media needs to be carefully checked.

  All media (hard disks, floppies and CDs/DVDs) are now uniformly handled through the interface. The device-specific interfaces (`IHardDisk`, `IDVDImage`, `IHostDVDDrive`, `IFloppyImage` and `IHostFloppyDrive`) have been merged into IMedium; CD/DVD and floppy media no longer need special treatment. The device type of a medium determines in which context it can be used. Some functionality was moved to the other storage-related interfaces.

  `IMachine::attachHardDisk` and similar methods have been renamed and generalized to deal with any type of drive and medium. is the API method for adding any drive to a storage controller. The floppy and DVD/CD drives are no longer handled specially, and that means you can have more than one of them. As before, drives can only be changed while the VM is powered off. Mounting (or unmounting) removable media at runtime is possible with .

  Newly created virtual machines have no storage controllers associated with them. Even the IDE Controller needs to be created explicitly. The floppy controller is now visible as a separate controller, with a new storage bus type. For each storage bus type you can query the device types which can be attached, so that it is not necessary to hardcode any attachment rules.

  This required matching changes e.g. in the callback interfaces (the medium specific change notification was replaced by a generic medium change notification) and removing associated enums (e.g. `DriveState`). In many places the incorrect use of the plural form "media" was replaced by "medium", to improve consistency.

- Reading the attribute no longer automatically performs an accessibility check; a new method does this. The attribute only returns the state any more.

- There were substantial changes related to snapshots, triggered by the "branched snapshots" functionality introduced with version 3.1. IConsole::discardSnapshot was renamed to . IConsole::discardCurrentState and IConsole::discardCurrentSnapshotAndState were removed; corresponding new functionality is in . Also, when is called on a running virtual machine, a live snapshot will be created. The old behavior was to temporarily pause the virtual machine while creating an online snapshot.

- The `IVRDPServer`, `IRemoteDisplayInfo"` and `IConsoleCallback` interfaces were changed to reflect VRDP server ability to bind to one of available ports from a list of ports.

  The `IVRDPServer::port` attribute has been replaced with `IVRDPServer::ports`, which is a comma-separated list of ports or ranges of ports.

  An `IRemoteDisplayInfo::port"` attribute has been added for querying the actual port VRDP server listens on.

  An IConsoleCallback::onRemoteDisplayInfoChange() notification callback has been added.

- The parameter lists for the following functions were modified:

- In the OOWS bindings for JAX-WS, the behavior of structures changed: for one, we implemented natural structures field access so you can just call a "get" method to obtain a field. Secondly, setters in structures were disabled as they have no expected effect and were at best misleading.

### Incompatible API changes with version 3.0

- In the object-oriented web service bindings for JAX-WS, proper inheritance has been introduced for some classes, so explicit casting is no longer needed to call methods from a parent class. In particular, IHardDisk and other classes now properly derive from .

- All object identifiers (machines, snapshots, disks, etc) switched from GUIDs to strings (now still having string representation of GUIDs inside). As a result, no particular internal structure can be assumed for object identifiers; instead, they should be treated as opaque unique handles. This change mostly affects Java and C++ programs; for other languages, GUIDs are transparently converted to strings.

- The uses of NULL strings have been changed greatly. All out parameters now use empty strings to signal a null value. For in parameters both the old NULL and empty string is allowed. This change was necessary to support more client bindings, especially using the webservice API. Many of them either have no special NULL value or have trouble dealing with it correctly in the respective library code.

- Accidentally, the `TSBool` interface still appeared in 3.0.0, and was removed in 3.0.2. This is an SDK bug, do not use the SDK for VirtualBox 3.0.0 for developing clients.

- The type of changed from `result` to `long`.

- The parameter list of IVirtualBox::openHardDisk was changed.

- The method IConsole::discardSavedState was renamed to IConsole::forgetSavedState, and a parameter was added.

- The method IConsole::powerDownAsync was renamed to , and the previous method with that name was deleted. So effectively a parameter was added.

- In the interface, the following were removed:

  - the `operationSupported` attribute;

    (as a result, the `FramebufferAccelerationOperation` enum was no longer needed and removed as well);

  - the `solidFill()` method;

  - the `copyScreenBits()` method.

- In the interface, the following were removed:

  - the `setupInternalFramebuffer()` method;

  - the `lockFramebuffer()` method;

  - the `unlockFramebuffer()` method;

  - the `registerExternalFramebuffer()` method.

### Incompatible API changes with version 2.2

- Added explicit version number into JAX-WS Java package names, such as `org.virtualbox_2_2`, allowing connect to multiple VirtualBox clients from single Java application.

- The interfaces having a "2" suffix attached to them with version 2.1 were renamed again to have that suffix removed. This time around, this change involves only the name, there are no functional differences.

  As a result, IDVDImage2 is now IDVDImage; IHardDisk2 is now IHardDisk; IHardDisk2Attachment is now IHardDiskAttachment.

  Consequentially, all related methods and attributes that had a "2" suffix have been renamed; for example, IMachine::attachHardDisk2 now becomes IMachine::attachHardDisk().

- IVirtualBox::openHardDisk has an extra parameter for opening a disk read/write or read-only.

- The remaining collections were replaced by more performant safe-arrays. This affects the following collections:

  - IGuestOSTypeCollection

  - IHostDVDDriveCollection

  - IHostFloppyDriveCollection

  - IHostUSBDeviceCollection

  - IHostUSBDeviceFilterCollection

  - IProgressCollection

  - ISharedFolderCollection

  - ISnapshotCollection

  - IUSBDeviceCollection

  - IUSBDeviceFilterCollection

- Since "Host Interface Networking" was renamed to "bridged networking" and host-only networking was introduced, all associated interfaces needed renaming as well. In detail:

  - The HostNetworkInterfaceType enum has been renamed to

  - The IHostNetworkInterface::type attribute has been renamed to

  - INetworkAdapter::attachToHostInterface() has been renamed to INetworkAdapter::attachToBridgedInterface

  - In the IHost interface, createHostNetworkInterface() has been renamed to

  - Similarly, removeHostNetworkInterface() has been renamed to

### Incompatible API changes with version 2.1

- With VirtualBox 2.1, error codes were added to many error infos that give the caller a machine-readable (numeric) feedback in addition to the error string that has always been available. This is an ongoing process, and future versions of this SDK reference will document the error codes for each method call.

- The hard disk and other media interfaces were completely redesigned. This was necessary to account for the support of VMDK, VHD and other image types; since backwards compatibility had to be broken anyway, we seized the moment to redesign the interfaces in a more logical way.

  - Previously, the old IHardDisk interface had several derivatives called IVirtualDiskImage, IVMDKImage, IVHDImage, IISCSIHardDisk and ICustomHardDisk for the various disk formats supported by VirtualBox. The new IHardDisk2 interface that comes with version 2.1 now supports all hard disk image formats itself.

  - IHardDiskFormat is a new interface to describe the available back-ends for hard disk images (e.g. VDI, VMDK, VHD or iSCSI). The IHardDisk2::format attribute can be used to find out the back-end that is in use for a particular hard disk image. ISystemProperties::hardDiskFormats[] contains a list of all back-ends supported by the system. contains the default system format.

  - In addition, the new interface is a generic interface for hard disk, DVD and floppy images that contains the attributes and methods shared between them. It can be considered a parent class of the more specific interfaces for those images, which are now IHardDisk2, IDVDImage2 and IFloppyImage2.

    In each case, the "2" versions of these interfaces replace the earlier versions that did not have the "2" suffix. Previously, the IDVDImage and IFloppyImage interfaces were entirely unrelated to IHardDisk.

  - As a result, all parts of the API that previously referenced IHardDisk, IDVDImage or IFloppyImage or any of the old subclasses are gone and will have replacements that use IHardDisk2, IDVDImage2 and IFloppyImage2; see, for example, IMachine::attachHardDisk2.

  - In particular, the IVirtualBox::hardDisks2 array replaces the earlier IVirtualBox::hardDisks collection.

- was extended to group operating systems into families and for 64-bit support.

- The interface was completely rewritten to account for the changes in how Host Interface Networking is now implemented in VirtualBox 2.1.

- The IVirtualBox::machines2[] array replaces the former IVirtualBox::machines collection.

- Added and enumeration.

- The parameter list for was modified.

- Added IMachine::pushGuestProperty.

- New attributes in IMachine: , HWVirtExVPIDEnabled, , .

- Added and .

- Removed ResourceUsage enumeration.