ia64/xen-unstable

changeset 15659:4492a0285bae

merge with xen-unstable.hg
author Alex Williamson <alex.williamson@hp.com>
date Fri Jul 27 08:15:16 2007 -0600 (2007-07-27)
parents 37833b33ae77 5682f899c7ae
children 32825349924d
files xen/arch/x86/mm/hap/support.c xen/include/xen/shadow.h
line diff
     1.1 --- a/.hgignore	Thu Jul 26 14:35:01 2007 -0600
     1.2 +++ b/.hgignore	Fri Jul 27 08:15:16 2007 -0600
     1.3 @@ -62,14 +62,11 @@
     1.4  ^extras/mini-os/h/xen-public$
     1.5  ^extras/mini-os/mini-os.*$
     1.6  ^install/.*$
     1.7 -^linux-[^/]*-native/.*$
     1.8 -^linux-[^/]*-xen/.*$
     1.9 -^linux-[^/]*-xen0/.*$
    1.10 -^linux-[^/]*-xenU/.*$
    1.11  ^linux-[^/]*-paravirt/.*$
    1.12 -^linux-[^/]*-mm/.*$
    1.13 +^linux-2.6[^/]*/.*$
    1.14  ^linux-[^/]*-rc/.*$
    1.15  ^linux-[^/]*-tip/.*$
    1.16 +^linux-[^/]*-git/.*$
    1.17  ^linux-[^/]*\.patch$
    1.18  ^mkddbxen$
    1.19  ^netbsd-[^/]*-tools/.*$
     2.1 --- a/Config.mk	Thu Jul 26 14:35:01 2007 -0600
     2.2 +++ b/Config.mk	Fri Jul 27 08:15:16 2007 -0600
     2.3 @@ -81,14 +81,6 @@ CFLAGS += $(foreach i, $(EXTRA_INCLUDES)
     2.4  #        n - Do not build the Xen ACM framework
     2.5  ACM_SECURITY ?= n
     2.6  
     2.7 -# If ACM_SECURITY = y and no boot policy file is installed,
     2.8 -# then the ACM defaults to the security policy set by
     2.9 -# ACM_DEFAULT_SECURITY_POLICY
    2.10 -# Supported models are:
    2.11 -#	ACM_NULL_POLICY
    2.12 -#	ACM_CHINESE_WALL_AND_SIMPLE_TYPE_ENFORCEMENT_POLICY
    2.13 -ACM_DEFAULT_SECURITY_POLICY ?= ACM_NULL_POLICY
    2.14 -
    2.15  # Optional components
    2.16  XENSTAT_XENTOP     ?= y
    2.17  VTPM_TOOLS         ?= n
     3.1 --- a/buildconfigs/enable-xen-config	Thu Jul 26 14:35:01 2007 -0600
     3.2 +++ b/buildconfigs/enable-xen-config	Fri Jul 27 08:15:16 2007 -0600
     3.3 @@ -28,9 +28,13 @@ setopt()
     3.4  setopt CONFIG_PARAVIRT y
     3.5  setopt CONFIG_XEN y
     3.6  setopt CONFIG_VMI y
     3.7 +setopt CONFIG_KVM y
     3.8 +setopt CONFIG_KVM_INTEL y
     3.9 +setopt CONFIG_KVM_AMD y
    3.10  setopt CONFIG_LGUEST n
    3.11  setopt CONFIG_XEN_BLKDEV_FRONTEND y
    3.12  setopt CONFIG_XEN_NETDEV_FRONTEND y
    3.13  setopt CONFIG_HVC_XEN y
    3.14 +setopt CONFIG_NUMA n
    3.15  
    3.16  exit 0
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/buildconfigs/mk.linux-2.6	Fri Jul 27 08:15:16 2007 -0600
     4.3 @@ -0,0 +1,14 @@
     4.4 +XEN_LINUX_SOURCE ?= tarball
     4.5 +LINUX_VER ?= 2.6
     4.6 +
     4.7 +XEN_LINUX_TARBALL_KETCHUP := y
     4.8 +
     4.9 +IMAGE_TARGET ?= vmlinux bzImage
    4.10 +
    4.11 +XEN_LINUX_ALLOW_INTERFACE_MISMATCH := y
    4.12 +
    4.13 +XEN_LINUX_CONFIG_UPDATE := buildconfigs/enable-xen-config
    4.14 +
    4.15 +EXTRAVERSION ?=
    4.16 +
    4.17 +include buildconfigs/mk.linux-2.6-xen
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/buildconfigs/mk.linux-2.6-git	Fri Jul 27 08:15:16 2007 -0600
     5.3 @@ -0,0 +1,2 @@
     5.4 +LINUX_VER ?= 2.6-git
     5.5 +include buildconfigs/mk.linux-2.6
     6.1 --- a/buildconfigs/mk.linux-2.6-mm	Thu Jul 26 14:35:01 2007 -0600
     6.2 +++ b/buildconfigs/mk.linux-2.6-mm	Fri Jul 27 08:15:16 2007 -0600
     6.3 @@ -1,14 +1,2 @@
     6.4 -XEN_LINUX_SOURCE ?= tarball
     6.5  LINUX_VER ?= 2.6-mm
     6.6 -
     6.7 -XEN_LINUX_TARBALL_KETCHUP := y
     6.8 -
     6.9 -IMAGE_TARGET ?= vmlinux bzImage
    6.10 -
    6.11 -XEN_LINUX_ALLOW_INTERFACE_MISMATCH := y
    6.12 -
    6.13 -XEN_LINUX_CONFIG_UPDATE := buildconfigs/enable-xen-config
    6.14 -
    6.15 -EXTRAVERSION ?=
    6.16 -
    6.17 -include buildconfigs/mk.linux-2.6-xen
    6.18 +include buildconfigs/mk.linux-2.6
     7.1 --- a/buildconfigs/mk.linux-2.6-rc	Thu Jul 26 14:35:01 2007 -0600
     7.2 +++ b/buildconfigs/mk.linux-2.6-rc	Fri Jul 27 08:15:16 2007 -0600
     7.3 @@ -1,14 +1,2 @@
     7.4 -XEN_LINUX_SOURCE ?= tarball
     7.5  LINUX_VER ?= 2.6-rc
     7.6 -
     7.7 -XEN_LINUX_TARBALL_KETCHUP := y
     7.8 -
     7.9 -IMAGE_TARGET ?= vmlinux bzImage
    7.10 -
    7.11 -XEN_LINUX_ALLOW_INTERFACE_MISMATCH := y
    7.12 -
    7.13 -XEN_LINUX_CONFIG_UPDATE := buildconfigs/enable-xen-config
    7.14 -
    7.15 -EXTRAVERSION ?=
    7.16 -
    7.17 -include buildconfigs/mk.linux-2.6-xen
    7.18 +include buildconfigs/mk.linux-2.6
     8.1 --- a/buildconfigs/mk.linux-2.6-tip	Thu Jul 26 14:35:01 2007 -0600
     8.2 +++ b/buildconfigs/mk.linux-2.6-tip	Fri Jul 27 08:15:16 2007 -0600
     8.3 @@ -1,14 +1,2 @@
     8.4 -XEN_LINUX_SOURCE ?= tarball
     8.5  LINUX_VER ?= 2.6-tip
     8.6 -
     8.7 -XEN_LINUX_TARBALL_KETCHUP := y
     8.8 -
     8.9 -IMAGE_TARGET ?= vmlinux bzImage
    8.10 -
    8.11 -XEN_LINUX_ALLOW_INTERFACE_MISMATCH := y
    8.12 -
    8.13 -XEN_LINUX_CONFIG_UPDATE := buildconfigs/enable-xen-config
    8.14 -
    8.15 -EXTRAVERSION ?=
    8.16 -
    8.17 -include buildconfigs/mk.linux-2.6-xen
    8.18 +include buildconfigs/mk.linux-2.6
     9.1 --- a/docs/man/xm.pod.1	Thu Jul 26 14:35:01 2007 -0600
     9.2 +++ b/docs/man/xm.pod.1	Fri Jul 27 08:15:16 2007 -0600
     9.3 @@ -822,13 +822,15 @@ security in Xen, you must compile Xen wi
     9.4  described under "Configuring Security" below. There, you will find
     9.5  also examples of each subcommand described here.
     9.6  
     9.7 -=item B<makepolicy> I<policy>
     9.8 +=item B<setpolicy> ACM I<policy> I<[--load|--boot]>
     9.9  
    9.10 -Compiles the XML source representation of the security I<policy>. It
    9.11 -creates a mapping (.map) as well as a binary (.bin) version of the
    9.12 -policy. The compiled policy can be loaded into Xen with the
    9.13 -B<loadpolicy> subcommand or can be configured to be loaded at boot
    9.14 -time with the B<cfgbootpolicy> subcommand.
    9.15 +Makes the given ACM policy available to xend as a I<xend-managed policy>.
    9.16 +The policy is compiled and a mapping (.map) as well as a binary (.bin)
    9.17 +version of the policy is created. If the option I<--load> is provided
    9.18 +the policy is loaded into Xen. If the option I<--boot> is provided the
    9.19 +system is configure to be loaded with the policy at boot time. If these
    9.20 +options are not provided with the B<setpolicy> subcommand, the
    9.21 +B<activatepolicy> subcommand provides this functionality.
    9.22  
    9.23  =over 4
    9.24  
    9.25 @@ -843,18 +845,26 @@ global policy root directory.
    9.26  
    9.27  =back
    9.28  
    9.29 -=item B<loadpolicy> I<policy>
    9.30 -
    9.31 -Loads the binary representation of the I<policy> into Xen. The binary
    9.32 -representation can be created with the B<makepolicy> subcommand.
    9.33 +=item B<activatepolicy> I<[--load|--boot]>
    9.34  
    9.35 -=item B<cfgbootpolicy> I<policy> [I<boot title>]
    9.36 +Activates the xend-managed policy by loading it into Xen using the
    9.37 +I<--load> option or configures the system to boot with the
    9.38 +xend-managed policy during the next reboot as a result of the
    9.39 +I<--boot> option. The latter is only supported if the system is booted
    9.40 +with the grub boot loader and the default boot title is modified.
    9.41 +It copies the binary policy representation into the /boot directory and
    9.42 +adds a module line specifying the binary policy to the /boot/grub/menu.lst
    9.43 +or /boot/grub/grub.conf file.
    9.44  
    9.45 -Configures I<policy> as the boot policy for Xen. It copies the binary
    9.46 -policy representation into the /boot directory and adds a module line
    9.47 -specifying the binary policy to the /boot/grub/menu.lst file. If your
    9.48 -boot configuration includes multiple Xen boot titles, then use the
    9.49 -I<boot title> parameter to specify a unique part of the proper title.
    9.50 +=item B<getpolicy> [--dumpxml]
    9.51 +
    9.52 +Displays information about the current xend-managed policy, such as
    9.53 +name and type of the policy, the uuid xend has assigned to it on the
    9.54 +local system, the version of the XML representation and the status
    9.55 +of the policy, such as whether it is currently loaded into Xen or
    9.56 +whether the policy is automatically loaded during system boot. With
    9.57 +the I<--dumpxml> option, the XML representation of the policy is
    9.58 +displayed.
    9.59  
    9.60  =item B<dumppolicy>
    9.61  
    9.62 @@ -869,28 +879,47 @@ is 'dom'. The labels are arranged in alp
    9.63  
    9.64  =item B<addlabel> I<label> B<dom> I<configfile> [I<policy>]
    9.65  
    9.66 +=item B<addlabel> I<label> B<mgt> I<domain name> [I<policy type>:I<policy>]
    9.67 +
    9.68  =item B<addlabel> I<label> B<res> I<resource> [I<policy>]
    9.69  
    9.70 +=item B<addlabel> I<label> B<vif-idx> I<domain name> [I<policy type>:I<policy>]
    9.71 +
    9.72 +
    9.73  Adds the security label with name I<label> to a domain
    9.74 -I<configfile> (dom) or to the global resource label file for the
    9.75 -given I<resource> (res). Unless specified, the default I<policy> is the
    9.76 -currently enforced access control policy. This subcommand also
    9.77 -verifies that the I<policy> definition supports the specified I<label>
    9.78 -name.
    9.79 +I<configfile> (dom), a Xend-managed domain (mgt), to the global resource label
    9.80 +file for the given I<resource> (res), or to a managed domain's virtual network
    9.81 +interface (vif) that is specified by its index. Unless specified,
    9.82 +the default I<policy> is the currently enforced access control policy.
    9.83 +This subcommand also verifies that the I<policy> definition supports the
    9.84 +specified I<label> name.
    9.85 +
    9.86 +The only I<policy type> that is currently supported is I<ACM>.
    9.87  
    9.88  =item B<rmlabel> B<dom> I<configfile>
    9.89  
    9.90 +=item B<rmlabel> B<mgt> I<domain name>
    9.91 +
    9.92  =item B<rmlabel> B<res> I<resource>
    9.93  
    9.94 +=item B<rmlabel> B<vif-idx> I<domain name>
    9.95 +
    9.96  Works the same as the B<addlabel> command (above), except that this
    9.97 -command will remove the label from the domain I<configfile> (dom) or
    9.98 -the global resource label file (res).
    9.99 +command will remove the label from the domain I<configfile> (dom),
   9.100 +a Xend-managed domain (mgt), the global resource label file (res),
   9.101 +or a managed domain's network interface (vif).
   9.102  
   9.103  =item B<getlabel> B<dom> I<configfile>
   9.104  
   9.105 +=item B<getlabel> B<mgt> I<domain name>
   9.106 +
   9.107  =item B<getlabel> B<res> I<resource>
   9.108  
   9.109 -Shows the label for the given I<configfile> or I<resource>
   9.110 +=item B<getlabel> B<vif-idx> I<domain name>
   9.111 +
   9.112 +Shows the label for a domain's configuration in the given I<configfile>,
   9.113 +a xend-managed domain (mgt), a resource, or a managed domain's network
   9.114 +interface (vif).
   9.115  
   9.116  =item B<resources>
   9.117  
   9.118 @@ -908,12 +937,9 @@ B<CONFIGURING SECURITY>
   9.119  
   9.120  =over 4
   9.121  
   9.122 -In xen_source_dir/Config.mk set the following parameters:
   9.123 +In xen_source_dir/Config.mk set the following parameter:
   9.124  
   9.125      ACM_SECURITY ?= y
   9.126 -    ACM_DEFAULT_SECURITY_POLICY ?= \
   9.127 -        ACM_CHINESE_WALL_AND_SIMPLE_TYPE_ENFORCEMENT_POLICY
   9.128 -
   9.129  Then recompile and install xen and the security tools and then reboot:
   9.130  
   9.131      cd xen_source_dir/xen; make clean; make; cp xen.gz /boot;
   9.132 @@ -922,26 +948,26 @@ Then recompile and install xen and the s
   9.133  
   9.134  =back
   9.135  
   9.136 -B<COMPILING A SECURITY POLICY>
   9.137 +B<SETTING A SECURITY POLICY>
   9.138  
   9.139  =over 4
   9.140  
   9.141 -This step creates client_v1.map and client_v1.bin files in
   9.142 -/etc/xen/acm-security/policies/example/chwall_ste.
   9.143 +This step makes the policy available to xend and creates the client_v1.map and
   9.144 +client_v1.bin files in /etc/xen/acm-security/policies/example/chwall_ste.
   9.145  
   9.146 -    xm makepolicy example.chwall_ste.client_v1
   9.147 +    xm setpolicy ACM example.client_v1
   9.148  
   9.149  =back
   9.150  
   9.151 -B<LOADING A SECURITY POLICY>
   9.152 +B<ACTIVATING THE XEND-MANAGED SECURITY POLICY>
   9.153  
   9.154  =over 4
   9.155  
   9.156 -This step activates client_v1.bin as new security policy in Xen. You
   9.157 -can use the dumppolicy subcommand before and afterwards to see the
   9.158 +This step activates the xend-manged policy as new security policy in Xen.
   9.159 +You can use the dumppolicy subcommand before and afterwards to see the
   9.160  change in the Xen policy state.
   9.161  
   9.162 -    xm loadpolicy example.chwall_ste.client_v1
   9.163 +    xm activatpolicy --load
   9.164  
   9.165  =back
   9.166  
   9.167 @@ -949,11 +975,11 @@ B<CONFIGURING A BOOT SECURITY POLICY>
   9.168  
   9.169  =over 4
   9.170  
   9.171 -This configures the boot loader to load client_v1.bin at boot
   9.172 -time. During system start, the ACM configures Xen with this policy and
   9.173 +This configures the boot loader to load the current xend-managed policy at
   9.174 +boot time. During system start, the ACM configures Xen with this policy and
   9.175  Xen enforces this policy from then on.
   9.176  
   9.177 -    xm cfgbootpolicy example.chwall_ste.client_v1
   9.178 +    xm activatepolicy --boot
   9.179  
   9.180  =back
   9.181  
   9.182 @@ -964,7 +990,7 @@ B<LISTING SECURITY LABELS>
   9.183  This subcommand shows all labels that are defined and which can be
   9.184  attached to domains.
   9.185  
   9.186 -    xm labels example.chwall_ste.client_v1 type=dom
   9.187 +    xm labels example.client_v1 type=dom
   9.188  
   9.189  will print for our example policy:
   9.190  
   9.191 @@ -1019,6 +1045,28 @@ permitted".
   9.192  
   9.193  =back
   9.194  
   9.195 +B<ATTACHING A SECURITY LABEL TO A XEND-MANAGED DOMAIN>
   9.196 +
   9.197 +=over 4
   9.198 +
   9.199 +The addlabel subcommand supports labeling of domains that are managed
   9.200 +by xend. This includes domains that are currently running, such as for
   9.201 +example Domain-0, or those that are in a dormant state.
   9.202 +Depending on the state of the system, it is possible that the new label
   9.203 +is rejected. An example for a reason for the rejection of the relabeling
   9.204 +of a domain would be if a domain is currently allowed to
   9.205 +access its labeled resources but due to the new label would be prevented
   9.206 +from accessing one or more of them.
   9.207 +
   9.208 +    xm addlabel dom_Fun mgt Domain-0
   9.209 +
   9.210 +This changes the label of Domain-0 to dom_Fun under the condition that
   9.211 +this new label of Domain-0 would not prevent any other domain from
   9.212 +accessing its resources that are provided through Domain-0, such as for
   9.213 +example network or block device access.
   9.214 +
   9.215 +=back
   9.216 +
   9.217  B<ATTACHING A SECURITY LABEL TO A RESOURCE>
   9.218  
   9.219  =over 4
   9.220 @@ -1072,9 +1120,11 @@ B<LISTING LABELED RESOURCES>
   9.221      xm resources
   9.222  
   9.223        phy:hda6
   9.224 +            type: ACM
   9.225            policy: example.chwall_ste.client_v1
   9.226            label:  res_LogicalDiskPartition1(hda1)
   9.227        file:/xen/disk_image/disk.img
   9.228 +            type: ACM
   9.229            policy: example.chwall_ste.client_v1
   9.230            label:  res_LogicalDiskPartition2(hda2)
   9.231  
   9.232 @@ -1094,19 +1144,19 @@ consistent to achieve predictable securi
   9.233  The XML version is the version that users are supposed to create or
   9.234  change, either by manually editing the XML file or by using the Xen
   9.235  policy generation tool (B<xensec_gen>). After changing the XML file,
   9.236 -run the B<makepolicy> subcommand to ensure that these changes are
   9.237 -reflected in the other versions. Use, for example, the subcommand
   9.238 -B<cfgbootpolicy> to activate the changes during the next system
   9.239 +run the B<setpolicy> subcommand to ensure that the new policy is
   9.240 +available to xend. Use, for example, the subcommand
   9.241 +B<activatepolicy> to activate the changes during the next system
   9.242  reboot.
   9.243  
   9.244  The binary version of the policy is derived from the XML policy by
   9.245  tokenizing the specified labels and is used inside Xen only. It is
   9.246 -created with the B<makepolicy> subcommand. Essentially, the binary
   9.247 +created with the B<setpolicy> subcommand. Essentially, the binary
   9.248  version is much more compact than the XML version and is easier to
   9.249  evaluate during access control decisions.
   9.250  
   9.251  The mapping version of the policy is created during the XML-to-binary
   9.252 -policy translation (B<makepolicy>) and is used by the Xen management
   9.253 +policy translation (B<setpolicy>) and is used by xend and the management
   9.254  tools to translate between label names used as input to the tools and
   9.255  their binary identifiers (ssidrefs) used inside Xen.
   9.256  
   9.257 @@ -1121,5 +1171,6 @@ B<xmdomain.cfg>(5), B<xentop>(1)
   9.258    Sean Dague <sean at dague dot net>
   9.259    Daniel Stekloff <dsteklof at us dot ibm dot com>
   9.260    Reiner Sailer <sailer at us dot ibm dot com>
   9.261 +  Stefan Berger <stefanb at us dot ibm dot com>
   9.262  
   9.263  =head1 BUGS
    10.1 --- a/docs/xen-api/xenapi-datamodel-graph.dot	Thu Jul 26 14:35:01 2007 -0600
    10.2 +++ b/docs/xen-api/xenapi-datamodel-graph.dot	Fri Jul 27 08:15:16 2007 -0600
    10.3 @@ -12,7 +12,7 @@
    10.4  digraph "Xen-API Class Diagram" {
    10.5  fontname="Verdana";
    10.6  
    10.7 -node [ shape=box ]; session VM host network VIF PIF SR VDI VBD PBD user;
    10.8 +node [ shape=box ]; session VM host network VIF PIF SR VDI VBD PBD user XSPolicy ACMPolicy;
    10.9  node [shape=ellipse]; PIF_metrics VIF_metrics VM_metrics VBD_metrics PBD_metrics VM_guest_metrics host_metrics;
   10.10  node [shape=box]; host_cpu console
   10.11  session -> host [ arrowhead="none" ]
   10.12 @@ -36,4 +36,6 @@ VDI -> VBD [ arrowhead="crow", arrowtail
   10.13  VBD -> VM [ arrowhead="none", arrowtail="crow" ]
   10.14  VTPM -> VM [ arrowhead="none", arrowtail="crow" ]
   10.15  VBD -> VBD_metrics [ arrowhead="none" ]
   10.16 +XSPolicy -> host [ arrowhead="none" ]
   10.17 +XSPolicy -> ACMPolicy [ arrowhead="none" ]
   10.18  }
    11.1 --- a/docs/xen-api/xenapi-datamodel.tex	Thu Jul 26 14:35:01 2007 -0600
    11.2 +++ b/docs/xen-api/xenapi-datamodel.tex	Fri Jul 27 08:15:16 2007 -0600
    11.3 @@ -46,6 +46,8 @@ Name & Description \\
    11.4  {\tt console} & A console \\
    11.5  {\tt user} & A user of the system \\
    11.6  {\tt debug} & A basic class for testing \\
    11.7 +{\tt XSPolicy} & A class for handling Xen Security Policies \\
    11.8 +{\tt ACMPolicy} & A class for handling ACM-type policies \\
    11.9  \hline
   11.10  \end{tabular}\end{center}
   11.11  \section{Relationships Between Classes}
   11.12 @@ -225,6 +227,261 @@ The following enumeration types are used
   11.13  \end{longtable}
   11.14  
   11.15  \vspace{1cm}
   11.16 +\newpage
   11.17 +
   11.18 +\section{Error Handling}
   11.19 +When a low-level transport error occurs, or a request is malformed at the HTTP
   11.20 +or XML-RPC level, the server may send an XML-RPC Fault response, or the client
   11.21 +may simulate the same.  The client must be prepared to handle these errors,
   11.22 +though they may be treated as fatal.  On the wire, these are transmitted in a
   11.23 +form similar to this:
   11.24 +
   11.25 +\begin{verbatim}
   11.26 +    <methodResponse>
   11.27 +      <fault>
   11.28 +        <value>
   11.29 +          <struct>
   11.30 +            <member>
   11.31 +                <name>faultCode</name>
   11.32 +                <value><int>-1</int></value>
   11.33 +              </member>
   11.34 +              <member>
   11.35 +                <name>faultString</name>
   11.36 +                <value><string>Malformed request</string></value>
   11.37 +            </member>
   11.38 +          </struct>
   11.39 +        </value>
   11.40 +      </fault>
   11.41 +    </methodResponse>
   11.42 +\end{verbatim}
   11.43 +
   11.44 +All other failures are reported with a more structured error response, to
   11.45 +allow better automatic response to failures, proper internationalisation of
   11.46 +any error message, and easier debugging.  On the wire, these are transmitted
   11.47 +like this:
   11.48 +
   11.49 +\begin{verbatim}
   11.50 +    <struct>
   11.51 +      <member>
   11.52 +        <name>Status</name>
   11.53 +        <value>Failure</value>
   11.54 +      </member>
   11.55 +      <member>
   11.56 +        <name>ErrorDescription</name>
   11.57 +        <value>
   11.58 +          <array>
   11.59 +            <data>
   11.60 +              <value>MAP_DUPLICATE_KEY</value>
   11.61 +              <value>Customer</value>
   11.62 +              <value>eSpeil Inc.</value>
   11.63 +              <value>eSpeil Incorporated</value>
   11.64 +            </data>
   11.65 +          </array>
   11.66 +        </value>
   11.67 +      </member>
   11.68 +    </struct>
   11.69 +\end{verbatim}
   11.70 +
   11.71 +Note that {\tt ErrorDescription} value is an array of string values. The
   11.72 +first element of the array is an error code; the remainder of the array are
   11.73 +strings representing error parameters relating to that code.  In this case,
   11.74 +the client has attempted to add the mapping {\tt Customer $\rightarrow$
   11.75 +eSpiel Incorporated} to a Map, but it already contains the mapping
   11.76 +{\tt Customer $\rightarrow$ eSpiel Inc.}, and so the request has failed.
   11.77 +
   11.78 +The reference below lists each possible error returned by each method.
   11.79 +As well as the errors explicitly listed, any method may return low-level
   11.80 +errors as described above, or any of the following generic errors:
   11.81 +
   11.82 +\begin{itemize}
   11.83 +\item HANDLE\_INVALID
   11.84 +\item INTERNAL\_ERROR
   11.85 +\item MAP\_DUPLICATE\_KEY
   11.86 +\item MESSAGE\_METHOD\_UNKNOWN
   11.87 +\item MESSAGE\_PARAMETER\_COUNT\_MISMATCH
   11.88 +\item OPERATION\_NOT\_ALLOWED
   11.89 +\item PERMISSION\_DENIED
   11.90 +\item SESSION\_INVALID
   11.91 +\end{itemize}
   11.92 +
   11.93 +Each possible error code is documented in the following section.
   11.94 +
   11.95 +\subsection{Error Codes}
   11.96 +
   11.97 +\subsubsection{HANDLE\_INVALID}
   11.98 +
   11.99 +You gave an invalid handle.  The object may have recently been deleted. 
  11.100 +The class parameter gives the type of reference given, and the handle
  11.101 +parameter echoes the bad value given.
  11.102 +
  11.103 +\vspace{0.3cm}
  11.104 +{\bf Signature:}
  11.105 +\begin{verbatim}HANDLE_INVALID(class, handle)\end{verbatim}
  11.106 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.107 +
  11.108 +\subsubsection{INTERNAL\_ERROR}
  11.109 +
  11.110 +The server failed to handle your request, due to an internal error.  The
  11.111 +given message may give details useful for debugging the problem.
  11.112 +
  11.113 +\vspace{0.3cm}
  11.114 +{\bf Signature:}
  11.115 +\begin{verbatim}INTERNAL_ERROR(message)\end{verbatim}
  11.116 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.117 +
  11.118 +\subsubsection{MAP\_DUPLICATE\_KEY}
  11.119 +
  11.120 +You tried to add a key-value pair to a map, but that key is already there. 
  11.121 +The key, current value, and the new value that you tried to set are all
  11.122 +echoed.
  11.123 +
  11.124 +\vspace{0.3cm}
  11.125 +{\bf Signature:}
  11.126 +\begin{verbatim}MAP_DUPLICATE_KEY(key, current value, new value)\end{verbatim}
  11.127 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.128 +
  11.129 +\subsubsection{MESSAGE\_METHOD\_UNKNOWN}
  11.130 +
  11.131 +You tried to call a method that does not exist.  The method name that you
  11.132 +used is echoed.
  11.133 +
  11.134 +\vspace{0.3cm}
  11.135 +{\bf Signature:}
  11.136 +\begin{verbatim}MESSAGE_METHOD_UNKNOWN(method)\end{verbatim}
  11.137 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.138 +
  11.139 +\subsubsection{MESSAGE\_PARAMETER\_COUNT\_MISMATCH}
  11.140 +
  11.141 +You tried to call a method with the incorrect number of parameters.  The
  11.142 +fully-qualified method name that you used, and the number of received and
  11.143 +expected parameters are returned.
  11.144 +
  11.145 +\vspace{0.3cm}
  11.146 +{\bf Signature:}
  11.147 +\begin{verbatim}MESSAGE_PARAMETER_COUNT_MISMATCH(method, expected, received)\end{verbatim}
  11.148 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.149 +
  11.150 +\subsubsection{NETWORK\_ALREADY\_CONNECTED}
  11.151 +
  11.152 +You tried to create a PIF, but the network you tried to attach it to is
  11.153 +already attached to some other PIF, and so the creation failed.
  11.154 +
  11.155 +\vspace{0.3cm}
  11.156 +{\bf Signature:}
  11.157 +\begin{verbatim}NETWORK_ALREADY_CONNECTED(network, connected PIF)\end{verbatim}
  11.158 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.159 +
  11.160 +\subsubsection{OPERATION\_NOT\_ALLOWED}
  11.161 +
  11.162 +You attempted an operation that was not allowed.
  11.163 +
  11.164 +\vspace{0.3cm}
  11.165 +No parameters.
  11.166 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.167 +
  11.168 +\subsubsection{PERMISSION\_DENIED}
  11.169 +
  11.170 +You do not have the required permissions to perform the operation.
  11.171 +
  11.172 +\vspace{0.3cm}
  11.173 +No parameters.
  11.174 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.175 +
  11.176 +\subsubsection{PIF\_IS\_PHYSICAL}
  11.177 +
  11.178 +You tried to destroy a PIF, but it represents an aspect of the physical
  11.179 +host configuration, and so cannot be destroyed.  The parameter echoes the
  11.180 +PIF handle you gave.
  11.181 +
  11.182 +\vspace{0.3cm}
  11.183 +{\bf Signature:}
  11.184 +\begin{verbatim}PIF_IS_PHYSICAL(PIF)\end{verbatim}
  11.185 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.186 +
  11.187 +\subsubsection{SESSION\_AUTHENTICATION\_FAILED}
  11.188 +
  11.189 +The credentials given by the user are incorrect, so access has been denied,
  11.190 +and you have not been issued a session handle.
  11.191 +
  11.192 +\vspace{0.3cm}
  11.193 +No parameters.
  11.194 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.195 +
  11.196 +\subsubsection{SESSION\_INVALID}
  11.197 +
  11.198 +You gave an invalid session handle.  It may have been invalidated by a
  11.199 +server restart, or timed out.  You should get a new session handle, using
  11.200 +one of the session.login\_ calls.  This error does not invalidate the
  11.201 +current connection.  The handle parameter echoes the bad value given.
  11.202 +
  11.203 +\vspace{0.3cm}
  11.204 +{\bf Signature:}
  11.205 +\begin{verbatim}SESSION_INVALID(handle)\end{verbatim}
  11.206 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.207 +
  11.208 +\subsubsection{SESSION\_NOT\_REGISTERED}
  11.209 +
  11.210 +This session is not registered to receive events.  You must call
  11.211 +event.register before event.next.  The session handle you are using is
  11.212 +echoed.
  11.213 +
  11.214 +\vspace{0.3cm}
  11.215 +{\bf Signature:}
  11.216 +\begin{verbatim}SESSION_NOT_REGISTERED(handle)\end{verbatim}
  11.217 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.218 +
  11.219 +\subsubsection{VALUE\_NOT\_SUPPORTED}
  11.220 +
  11.221 +You attempted to set a value that is not supported by this implementation. 
  11.222 +The fully-qualified field name and the value that you tried to set are
  11.223 +returned.  Also returned is a developer-only diagnostic reason.
  11.224 +
  11.225 +\vspace{0.3cm}
  11.226 +{\bf Signature:}
  11.227 +\begin{verbatim}VALUE_NOT_SUPPORTED(field, value, reason)\end{verbatim}
  11.228 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.229 +
  11.230 +\subsubsection{VLAN\_TAG\_INVALID}
  11.231 +
  11.232 +You tried to create a VLAN, but the tag you gave was invalid -- it mmust be
  11.233 +between 0 and 4095.  The parameter echoes the VLAN tag you gave.
  11.234 +
  11.235 +\vspace{0.3cm}
  11.236 +{\bf Signature:}
  11.237 +\begin{verbatim}VLAN_TAG_INVALID(VLAN)\end{verbatim}
  11.238 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.239 +
  11.240 +\subsubsection{VM\_BAD\_POWER\_STATE}
  11.241 +
  11.242 +You attempted an operation on a VM that was not in an appropriate power
  11.243 +state at the time; for example, you attempted to start a VM that was
  11.244 +already running.  The parameters returned are the VM's handle, and the
  11.245 +expected and actual VM state at the time of the call.
  11.246 +
  11.247 +\vspace{0.3cm}
  11.248 +{\bf Signature:}
  11.249 +\begin{verbatim}VM_BAD_POWER_STATE(vm, expected, actual)\end{verbatim}
  11.250 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.251 +
  11.252 +\subsubsection{VM\_HVM\_REQUIRED}
  11.253 +
  11.254 +HVM is required for this operation
  11.255 +
  11.256 +\vspace{0.3cm}
  11.257 +{\bf Signature:}
  11.258 +\begin{verbatim}VM_HVM_REQUIRED(vm)\end{verbatim}
  11.259 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.260 +
  11.261 +\subsubsection{SECURITY\_ERROR}
  11.262 +
  11.263 +A security error occurred. The parameter provides the xen security
  11.264 +error code and a message describing the error.
  11.265 +
  11.266 +\vspace{0.3cm}
  11.267 +{\bf Signature:}
  11.268 +\begin{verbatim}SECURITY_ERROR(xserr, message)\end{verbatim}
  11.269 +\begin{center}\rule{10em}{0.1pt}\end{center}
  11.270 +
  11.271  
  11.272  \newpage
  11.273  \section{Class: session}
  11.274 @@ -275,6 +532,11 @@ session ref
  11.275  
  11.276  
  11.277  ID of newly created session
  11.278 +
  11.279 +\vspace{0.3cm}
  11.280 +
  11.281 +\noindent{\bf Possible Error Codes:} {\tt SESSION\_AUTHENTICATION\_FAILED}
  11.282 +
  11.283  \vspace{0.3cm}
  11.284  \vspace{0.3cm}
  11.285  \vspace{0.3cm}
  11.286 @@ -1153,6 +1415,7 @@ Quals & Field & Type & Description \\
  11.287  $\mathit{RO}_\mathit{run}$ &  {\tt is\_control\_domain} & bool & true if this is a control domain (domain 0 or a driver domain) \\
  11.288  $\mathit{RO}_\mathit{run}$ &  {\tt metrics} & VM\_metrics ref & metrics associated with this VM \\
  11.289  $\mathit{RO}_\mathit{run}$ &  {\tt guest\_metrics} & VM\_guest\_metrics ref & metrics associated with the running guest \\
  11.290 +$\mathit{RO}_\mathit{run}$ &  {\tt security/label} & string & the VM's security label \\
  11.291  \hline
  11.292  \end{longtable}
  11.293  \subsection{RPCs associated with class: VM}
  11.294 @@ -4150,6 +4413,82 @@ value of the field
  11.295  \vspace{0.3cm}
  11.296  \vspace{0.3cm}
  11.297  \vspace{0.3cm}
  11.298 +\subsubsection{RPC name:~get\_security\_label}
  11.299 +
  11.300 +{\bf Overview:}
  11.301 +Get the security label field of the given VM. Refer to the XSPolicy class
  11.302 +for the format of the security label.
  11.303 +
  11.304 + \noindent {\bf Signature:}
  11.305 +\begin{verbatim} string get_security_label (session_id s, VM ref self)\end{verbatim}
  11.306 +
  11.307 +
  11.308 +\noindent{\bf Arguments:}
  11.309 +
  11.310 +
  11.311 +\vspace{0.3cm}
  11.312 +\begin{tabular}{|c|c|p{7cm}|}
  11.313 + \hline
  11.314 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.315 +{\tt VM ref } & self & reference to the object \\ \hline
  11.316 +
  11.317 +\end{tabular}
  11.318 +
  11.319 +\vspace{0.3cm}
  11.320 +
  11.321 + \noindent {\bf Return Type:}
  11.322 +{\tt
  11.323 +string
  11.324 +}
  11.325 +
  11.326 +
  11.327 +value of the field
  11.328 +\vspace{0.3cm}
  11.329 +\vspace{0.3cm}
  11.330 +\vspace{0.3cm}
  11.331 +\subsubsection{RPC name:~set\_security\_label}
  11.332 +
  11.333 +{\bf Overview:}
  11.334 +Set the security label field of the given VM. Refer to the XSPolicy class
  11.335 +for the format of the security label.
  11.336 +
  11.337 + \noindent {\bf Signature:}
  11.338 +\begin{verbatim} int set_security_label (session_id s, VM ref self, string
  11.339 +security_label, string old_label)\end{verbatim}
  11.340 +
  11.341 +
  11.342 +\noindent{\bf Arguments:}
  11.343 +
  11.344 +
  11.345 +\vspace{0.3cm}
  11.346 +\begin{tabular}{|c|c|p{7cm}|}
  11.347 + \hline
  11.348 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.349 +{\tt VM ref } & self & reference to the object \\ \hline
  11.350 +{\tt string } & security\_label & security label for the VM \\ \hline
  11.351 +{\tt string } & old\_label & Optional label value that the security label \\
  11.352 +& & must currently have for the change to succeed.\\ \hline
  11.353 +
  11.354 +\end{tabular}
  11.355 +
  11.356 +\vspace{0.3cm}
  11.357 +
  11.358 + \noindent {\bf Return Type:}
  11.359 +{\tt
  11.360 +int
  11.361 +}
  11.362 +
  11.363 +
  11.364 +Returns the ssidref in case of an VM that is currently running or
  11.365 +paused, zero in case of a dormant VM (halted, suspended).
  11.366 +
  11.367 +\vspace{0.3cm}
  11.368 +
  11.369 +\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
  11.370 +
  11.371 +\vspace{0.3cm}
  11.372 +\vspace{0.3cm}
  11.373 +\vspace{0.3cm}
  11.374  \subsubsection{RPC name:~create}
  11.375  
  11.376  {\bf Overview:} 
  11.377 @@ -7100,7 +7439,9 @@ value of the field
  11.378  \subsubsection{RPC name:~get\_flags}
  11.379  
  11.380  {\bf Overview:} 
  11.381 -Get the flags field of the given host\_cpu.
  11.382 +Get the flags field of the given host\_cpu.  As of this version of the
  11.383 +API, the semantics of the returned string are explicitly unspecified,
  11.384 +and may change in the future.
  11.385  
  11.386   \noindent {\bf Signature:} 
  11.387  \begin{verbatim} string get_flags (session_id s, host_cpu ref self)\end{verbatim}
  11.388 @@ -7132,7 +7473,9 @@ value of the field
  11.389  \subsubsection{RPC name:~get\_features}
  11.390  
  11.391  {\bf Overview:} 
  11.392 -Get the features field of the given host\_cpu.
  11.393 +Get the features field of the given host\_cpu. As of this version of the
  11.394 +API, the semantics of the returned string are explicitly unspecified,
  11.395 +and may change in the future.
  11.396  
  11.397   \noindent {\bf Signature:} 
  11.398  \begin{verbatim} string get_features (session_id s, host_cpu ref self)\end{verbatim}
  11.399 @@ -8634,6 +8977,79 @@ value of the field
  11.400  \vspace{0.3cm}
  11.401  \vspace{0.3cm}
  11.402  \vspace{0.3cm}
  11.403 +\subsubsection{RPC name:~set\_security\_label}
  11.404 +
  11.405 +{\bf Overview:}
  11.406 +Set the security label of the given VIF. Refer to the XSPolicy class
  11.407 +for the format of the security label.
  11.408 +
  11.409 + \noindent {\bf Signature:}
  11.410 +\begin{verbatim} void set_security_label (session_id s, VIF ref self, string
  11.411 +security_label, string old_label)\end{verbatim}
  11.412 +
  11.413 +
  11.414 +\noindent{\bf Arguments:}
  11.415 +
  11.416 +
  11.417 +\vspace{0.3cm}
  11.418 +\begin{tabular}{|c|c|p{7cm}|}
  11.419 + \hline
  11.420 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.421 +{\tt VIF ref } & self & reference to the object \\ \hline
  11.422 +
  11.423 +{\tt string } & security\_label & New value of the security label \\ \hline
  11.424 +{\tt string } & old\_label & Optional label value that the security label \\
  11.425 +& & must currently have for the change to succeed.\\ \hline
  11.426 +\end{tabular}
  11.427 +
  11.428 +\vspace{0.3cm}
  11.429 +
  11.430 + \noindent {\bf Return Type:}
  11.431 +{\tt
  11.432 +void
  11.433 +}
  11.434 +
  11.435 +
  11.436 +\vspace{0.3cm}
  11.437 +
  11.438 +\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
  11.439 +
  11.440 +\vspace{0.3cm}
  11.441 +\vspace{0.3cm}
  11.442 +\vspace{0.3cm}
  11.443 +\subsubsection{RPC name:~get\_security\_label}
  11.444 +
  11.445 +{\bf Overview:}
  11.446 +Get the security label of the given VIF.
  11.447 +
  11.448 + \noindent {\bf Signature:}
  11.449 +\begin{verbatim} string get_security_label (session_id s, VIF ref self)\end{verbatim}
  11.450 +
  11.451 +
  11.452 +\noindent{\bf Arguments:}
  11.453 +
  11.454 +
  11.455 +
  11.456 +\vspace{0.3cm}
  11.457 +\begin{tabular}{|c|c|p{7cm}|}
  11.458 + \hline
  11.459 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.460 +{\tt VIF ref } & self & reference to the object \\ \hline
  11.461 +
  11.462 +\end{tabular}
  11.463 +
  11.464 +\vspace{0.3cm}
  11.465 +
  11.466 + \noindent {\bf Return Type:}
  11.467 +{\tt
  11.468 +string
  11.469 +}
  11.470 +
  11.471 +
  11.472 +value of the given field
  11.473 +\vspace{0.3cm}
  11.474 +\vspace{0.3cm}
  11.475 +\vspace{0.3cm}
  11.476  \subsubsection{RPC name:~create}
  11.477  
  11.478  {\bf Overview:} 
  11.479 @@ -10382,6 +10798,7 @@ Quals & Field & Type & Description \\
  11.480  $\mathit{RW}$ &  {\tt sharable} & bool & true if this disk may be shared \\
  11.481  $\mathit{RW}$ &  {\tt read\_only} & bool & true if this disk may ONLY be mounted read-only \\
  11.482  $\mathit{RW}$ &  {\tt other\_config} & (string $\rightarrow$ string) Map & additional configuration \\
  11.483 +$\mathit{RO}_\mathit{run}$ &  {\tt security/label} & string & the VM's security label \\
  11.484  \hline
  11.485  \end{longtable}
  11.486  \subsection{RPCs associated with class: VDI}
  11.487 @@ -11065,6 +11482,79 @@ void
  11.488  \vspace{0.3cm}
  11.489  \vspace{0.3cm}
  11.490  \vspace{0.3cm}
  11.491 +\subsubsection{RPC name:~set\_security\_label}
  11.492 +
  11.493 +{\bf Overview:}
  11.494 +Set the security label of the given VDI. Refer to the XSPolicy class
  11.495 +for the format of the security label.
  11.496 +
  11.497 + \noindent {\bf Signature:}
  11.498 +\begin{verbatim} void set_security_label (session_id s, VDI ref self, string
  11.499 +security_label, string old_label)\end{verbatim}
  11.500 +
  11.501 +
  11.502 +\noindent{\bf Arguments:}
  11.503 +
  11.504 +
  11.505 +\vspace{0.3cm}
  11.506 +\begin{tabular}{|c|c|p{7cm}|}
  11.507 + \hline
  11.508 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.509 +{\tt VDI ref } & self & reference to the object \\ \hline
  11.510 +
  11.511 +{\tt string } & security\_label & New value of the security label \\ \hline
  11.512 +{\tt string } & old\_label & Optional label value that the security label \\
  11.513 +& & must currently have for the change to succeed.\\ \hline
  11.514 +\end{tabular}
  11.515 +
  11.516 +\vspace{0.3cm}
  11.517 +
  11.518 + \noindent {\bf Return Type:}
  11.519 +{\tt
  11.520 +void
  11.521 +}
  11.522 +
  11.523 +
  11.524 +\vspace{0.3cm}
  11.525 +
  11.526 +\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
  11.527 +
  11.528 +\vspace{0.3cm}
  11.529 +\vspace{0.3cm}
  11.530 +\vspace{0.3cm}
  11.531 +\subsubsection{RPC name:~get\_security\_label}
  11.532 +
  11.533 +{\bf Overview:}
  11.534 +Get the security label of the given VDI.
  11.535 +
  11.536 + \noindent {\bf Signature:}
  11.537 +\begin{verbatim} string get_security_label (session_id s, VDI ref self)\end{verbatim}
  11.538 +
  11.539 +
  11.540 +\noindent{\bf Arguments:}
  11.541 +
  11.542 +
  11.543 +
  11.544 +\vspace{0.3cm}
  11.545 +\begin{tabular}{|c|c|p{7cm}|}
  11.546 + \hline
  11.547 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.548 +{\tt VDI ref } & self & reference to the object \\ \hline
  11.549 +
  11.550 +\end{tabular}
  11.551 +
  11.552 +\vspace{0.3cm}
  11.553 +
  11.554 + \noindent {\bf Return Type:}
  11.555 +{\tt
  11.556 +string
  11.557 +}
  11.558 +
  11.559 +
  11.560 +value of the given field
  11.561 +\vspace{0.3cm}
  11.562 +\vspace{0.3cm}
  11.563 +\vspace{0.3cm}
  11.564  \subsubsection{RPC name:~create}
  11.565  
  11.566  {\bf Overview:} 
  11.567 @@ -13172,6 +13662,38 @@ value of the field
  11.568  \vspace{0.3cm}
  11.569  \vspace{0.3cm}
  11.570  \vspace{0.3cm}
  11.571 +\subsubsection{RPC name:~get\_runtime\_properties}
  11.572 +
  11.573 +{\bf Overview:}
  11.574 +Get the runtime\_properties field of the given VTPM.
  11.575 +
  11.576 +\noindent {\bf Signature:}
  11.577 +\begin{verbatim} ((string -> string) Map) get_runtime_properties (session_id s, VTPM ref self)\end{verbatim}
  11.578 +
  11.579 +
  11.580 +\noindent{\bf Arguments:}
  11.581 +
  11.582 +
  11.583 +\vspace{0.3cm}
  11.584 +\begin{tabular}{|c|c|p{7cm}|}
  11.585 + \hline
  11.586 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.587 +{\tt VTPM ref } & self & reference to the object \\ \hline
  11.588 +
  11.589 +\end{tabular}
  11.590 +
  11.591 +\vspace{0.3cm}
  11.592 +
  11.593 + \noindent {\bf Return Type:}
  11.594 +{\tt
  11.595 +(string $\rightarrow$ string) Map
  11.596 +}
  11.597 +
  11.598 +
  11.599 +value of the field
  11.600 +\vspace{0.3cm}
  11.601 +\vspace{0.3cm}
  11.602 +\vspace{0.3cm}
  11.603  \subsubsection{RPC name:~create}
  11.604  
  11.605  {\bf Overview:} 
  11.606 @@ -14017,6 +14539,634 @@ all fields from the object
  11.607  
  11.608  \vspace{1cm}
  11.609  \newpage
  11.610 +\section{Class: XSPolicy}
  11.611 +\subsection{Fields for class: XSPolicy}
  11.612 +\begin{longtable}{|lllp{0.38\textwidth}|}
  11.613 +\hline
  11.614 +\multicolumn{1}{|l}{Name} & \multicolumn{3}{l|}{\bf XSPolicy} \\
  11.615 +\multicolumn{1}{|l}{Description} & \multicolumn{3}{l|}{\parbox{11cm}{\em A Xen Security Policy}} \\
  11.616 +\hline
  11.617 +Quals & Field & Type & Description \\
  11.618 +\hline
  11.619 +$\mathit{RO}_\mathit{run}$ &  {\tt uuid} & string  & unique identifier / object reference \\
  11.620 +$\mathit{RW}$              &  {\tt repr} & string  & representation of policy, i.e., XML \\
  11.621 +$\mathit{RO}_\mathit{run}$ &  {\tt type} & xs\_type & type of the policy \\
  11.622 +$\mathit{RO}_\mathit{run}$ & {\tt flags} & xs\_instantiationflags & policy
  11.623 +status flags \\
  11.624 +\hline
  11.625 +\end{longtable}
  11.626 +\subsection{Semantics of the class: XSPolicy}
  11.627 +
  11.628 +The XSPolicy class is used for administering Xen Security policies. Through
  11.629 +this class a new policy can be uploaded to the system, loaded into the
  11.630 +Xen hypervisor for enforcement and be set as the policy that the
  11.631 +system is automatically loading when the machine is started.
  11.632 +
  11.633 +This class returns information about the currently administered policy,
  11.634 +including a reference to the policy. This reference can then be used with
  11.635 +policy-specific classes, i.e., the ACMPolicy class, to allow retrieval of
  11.636 +information or changes to be made to a particular policy.
  11.637 +
  11.638 +\subsection{Structure and datatypes of class: XSPolicy}
  11.639 +
  11.640 +Format of the security label:
  11.641 +
  11.642 +A security label consist of the three different parts {\it policy type},
  11.643 +{\it policy name} and {\it label} separated with colons. To specify
  11.644 +the virtual machine label for an ACM-type policy {\it xm-test}, the
  11.645 +security label string would be {\it ACM:xm-test:blue}, where blue
  11.646 +denotes the virtual machine's label. The format of resource labels is
  11.647 +the same.\\[0.5cm]
  11.648 +The following flags are used by this class:
  11.649 +
  11.650 +\begin{longtable}{|l|l|l|}
  11.651 +\hline
  11.652 +{\tt xs\_type} & value & meaning \\
  11.653 +\hline
  11.654 +\hspace{0.5cm}{\tt XS\_POLICY\_ACM} & (1 $<<$ 0) & ACM-type policy \\
  11.655 +\hline
  11.656 +\end{longtable}
  11.657 +
  11.658 +\begin{longtable}{|l|l|l|}
  11.659 +\hline
  11.660 +{\tt xs\_instantiationflags} & value & meaning \\
  11.661 +\hline
  11.662 +\hspace{0.5cm}{\tt XS\_INST\_NONE} & 0 & do nothing \\
  11.663 +\hspace{0.5cm}{\tt XS\_INST\_BOOT} & (1 $<<$ 0) & make system boot with this policy \\
  11.664 +\hspace{0.5cm}{\tt XS\_INST\_LOAD} & (1 $<<$ 1) & load policy immediately \\
  11.665 +\hline
  11.666 +\end{longtable}
  11.667 +
  11.668 +\begin{longtable}{|l|l|l|}
  11.669 +\hline
  11.670 +{\tt xs\_policystate} & type & meaning \\
  11.671 +\hline
  11.672 +\hspace{0.5cm}{\tt xserr} & int & Error code from operation (if applicable) \\
  11.673 +\hspace{0.5cm}{\tt xs\_ref}  & XSPolicy ref & reference to the XS policy as returned by the API \\
  11.674 +\hspace{0.5cm}{\tt repr} & string & representation of the policy, i.e., XML \\
  11.675 +\hspace{0.5cm}{\tt type} & xs\_type & the type of the policy \\
  11.676 +\hspace{0.5cm}{\tt flags } & xs\_instantiationflags  & instantiation flags of the policy \\
  11.677 +\hspace{0.5cm}{\tt version} & string & version of the policy \\
  11.678 +\hspace{0.5cm}{\tt errors} & string & Base64-encoded sequence of integer tuples consisting \\
  11.679 +& & of (error code, detail); will be returned as part  \\
  11.680 +& & of the xs\_setpolicy function. \\
  11.681 +\hline
  11.682 +\end{longtable}
  11.683 +
  11.684 +\subsection{Additional RPCs associated with class: XSPolicy}
  11.685 +\subsubsection{RPC name:~get\_xstype}
  11.686 +
  11.687 +{\bf Overview:}
  11.688 +Return the Xen Security Policy types supported by this system
  11.689 +
  11.690 + \noindent {\bf Signature:}
  11.691 +\begin{verbatim} xs_type get_xstype (session_id s)\end{verbatim}
  11.692 +
  11.693 + \noindent {\bf Return Type:}
  11.694 +{\tt
  11.695 +xs\_type
  11.696 +}
  11.697 +
  11.698 +flags representing the supported Xen security policy types
  11.699 + \vspace{0.3cm}
  11.700 +\vspace{0.3cm}
  11.701 +\vspace{0.3cm}
  11.702 +\subsubsection{RPC name:~set\_xspolicy}
  11.703 +
  11.704 +{\bf Overview:}
  11.705 +Set the current XSPolicy. This function can also be be used for updating of
  11.706 +an existing policy whose name must be equivalent to the one of the
  11.707 +currently running policy.
  11.708 +
  11.709 +\noindent {\bf Signature:}
  11.710 +\begin{verbatim} xs_policystate set_xspolicy (session_id s, xs_type type, string repr,
  11.711 +xs_instantiationflags flags, bool overwrite)\end{verbatim}
  11.712 +
  11.713 +\noindent{\bf Arguments:}
  11.714 +
  11.715 +\vspace{0.3cm}
  11.716 +
  11.717 +\begin{tabular}{|c|c|p{7cm}|}
  11.718 + \hline
  11.719 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.720 +{\tt xs\_type } & type & the type of policy \\ \hline
  11.721 +{\tt string} & repr & representation of the policy, i.e., XML \\ \hline
  11.722 +{\tt xs\_instantiationflags}    & flags & flags for the setting of the policy \\ \hline
  11.723 +{\tt bool}   & overwrite & whether to overwrite an existing policy \\ \hline
  11.724 +
  11.725 +\end{tabular}
  11.726 +
  11.727 +\vspace{0.3cm}
  11.728 +
  11.729 +
  11.730 + \noindent {\bf Return Type:}
  11.731 +{\tt
  11.732 +xs\_policystate
  11.733 +}
  11.734 +
  11.735 +
  11.736 +State information about the policy. In case an error occurred, the 'xs\_err'
  11.737 +field contains the error code. The 'errors' may contain further information
  11.738 +about the error.
  11.739 +\vspace{0.3cm}
  11.740 +\vspace{0.3cm}
  11.741 +\vspace{0.3cm}
  11.742 +\subsubsection{RPC name:~get\_xspolicy}
  11.743 +
  11.744 +{\bf Overview:}
  11.745 +Get information regarding the currently set Xen Security Policy
  11.746 +
  11.747 + \noindent {\bf Signature:}
  11.748 +\begin{verbatim} xs_policystate get_xspolicy (session_id s)\end{verbatim}
  11.749 +
  11.750 +\vspace{0.3cm}
  11.751 +
  11.752 + \noindent {\bf Return Type:}
  11.753 +{\tt
  11.754 +xs\_policystate
  11.755 +}
  11.756 +
  11.757 +
  11.758 +Policy state information.
  11.759 +\vspace{0.3cm}
  11.760 +\vspace{0.3cm}
  11.761 +\vspace{0.3cm}
  11.762 +\subsubsection{RPC name:~rm\_xsbootpolicy}
  11.763 +
  11.764 +{\bf Overview:}
  11.765 +Remove any policy from the default boot configuration.
  11.766 +
  11.767 + \noindent {\bf Signature:}
  11.768 +\begin{verbatim} void rm_xsbootpolicy (session_id s)\end{verbatim}
  11.769 +
  11.770 +\vspace{0.3cm}
  11.771 +
  11.772 +\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
  11.773 +
  11.774 +\vspace{0.3cm}
  11.775 +\vspace{0.3cm}
  11.776 +\vspace{0.3cm}
  11.777 +\subsubsection{RPC name:~get\_labeled\_resources}
  11.778 +
  11.779 +{\bf Overview:}
  11.780 +Get a list of resources that have been labeled.
  11.781 +
  11.782 + \noindent {\bf Signature:}
  11.783 +\begin{verbatim} ((string -> string) Map) get_labeled_resources (session_id s)\end{verbatim}
  11.784 +
  11.785 +
  11.786 +\vspace{0.3cm}
  11.787 +
  11.788 + \noindent {\bf Return Type:}
  11.789 +{\tt
  11.790 +(string $\rightarrow$ string) Map
  11.791 +}
  11.792 +
  11.793 +
  11.794 +A map of resources with their labels.
  11.795 +\vspace{0.3cm}
  11.796 +\vspace{0.3cm}
  11.797 +\vspace{0.3cm}
  11.798 +\subsubsection{RPC name:~set\_resource\_label}
  11.799 +
  11.800 +{\bf Overview:}
  11.801 +Label the given resource with the given label. An empty label removes any label
  11.802 +from the resource.
  11.803 +
  11.804 + \noindent {\bf Signature:}
  11.805 +\begin{verbatim} void set_resource_label (session_id s, string resource, string
  11.806 +label, string old_label)\end{verbatim}
  11.807 +
  11.808 +
  11.809 +\noindent{\bf Arguments:}
  11.810 +
  11.811 +
  11.812 +\vspace{0.3cm}
  11.813 +\begin{tabular}{|c|c|p{7cm}|}
  11.814 + \hline
  11.815 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.816 +{\tt string } & resource & resource to label \\ \hline
  11.817 +{\tt string } & label & label for the resource \\ \hline
  11.818 +{\tt string } & old\_label & Optional label value that the security label \\
  11.819 +& & must currently have for the change to succeed. \\ \hline
  11.820 +
  11.821 +\end{tabular}
  11.822 +
  11.823 +\vspace{0.3cm}
  11.824 +
  11.825 +\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
  11.826 +
  11.827 +\vspace{0.3cm}
  11.828 +\vspace{0.3cm}
  11.829 +\vspace{0.3cm}
  11.830 +\subsubsection{RPC name:~get\_resource\_label}
  11.831 +
  11.832 +{\bf Overview:}
  11.833 +Get the label of the given resource.
  11.834 +
  11.835 + \noindent {\bf Signature:}
  11.836 +\begin{verbatim} string get_resource_label (session_id s, string resource)\end{verbatim}
  11.837 +
  11.838 +
  11.839 +\noindent{\bf Arguments:}
  11.840 +
  11.841 +
  11.842 +\vspace{0.3cm}
  11.843 +\begin{tabular}{|c|c|p{7cm}|}
  11.844 + \hline
  11.845 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.846 +{\tt string } & resource & resource to label \\ \hline
  11.847 +
  11.848 +\end{tabular}
  11.849 +
  11.850 +\vspace{0.3cm}
  11.851 +
  11.852 + \noindent {\bf Return Type:}
  11.853 +{\tt
  11.854 +string
  11.855 +}
  11.856 +
  11.857 +
  11.858 +The label of the given resource.
  11.859 +\vspace{0.3cm}
  11.860 +\vspace{0.3cm}
  11.861 +\vspace{0.3cm}
  11.862 +\subsubsection{RPC name:~activate\_xspolicy}
  11.863 +
  11.864 +{\bf Overview:}
  11.865 +Load the referenced policy into the hypervisor.
  11.866 +
  11.867 + \noindent {\bf Signature:}
  11.868 +\begin{verbatim} xs_instantiationflags activate_xspolicy (session_id s, xs_ref xspolicy,
  11.869 +xs_instantiationflags flags)\end{verbatim}
  11.870 +
  11.871 +
  11.872 +\noindent{\bf Arguments:}
  11.873 +
  11.874 +
  11.875 +\vspace{0.3cm}
  11.876 +\begin{tabular}{|c|c|p{7cm}|}
  11.877 + \hline
  11.878 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.879 +{\tt xs ref } & self & reference to the object \\ \hline
  11.880 +{\tt xs\_instantiationflags } & flags & flags to activate on a policy; flags
  11.881 +  can only be set \\ \hline
  11.882 +
  11.883 +\end{tabular}
  11.884 +
  11.885 +\vspace{0.3cm}
  11.886 +
  11.887 +
  11.888 + \noindent {\bf Return Type:}
  11.889 +{\tt
  11.890 +xs\_instantiationflags
  11.891 +}
  11.892 +
  11.893 +
  11.894 +Currently active instantiation flags.
  11.895 +\vspace{0.3cm}
  11.896 +
  11.897 +\noindent{\bf Possible Error Codes:} {\tt SECURITY\_ERROR}
  11.898 +
  11.899 +\vspace{0.3cm}
  11.900 +\vspace{0.3cm}
  11.901 +\vspace{0.3cm}
  11.902 +\subsubsection{RPC name:~get\_all}
  11.903 +
  11.904 +{\bf Overview:}
  11.905 +Return a list of all the XSPolicies known to the system.
  11.906 +
  11.907 + \noindent {\bf Signature:}
  11.908 +\begin{verbatim} ((XSPolicy ref) Set) get_all (session_id s)\end{verbatim}
  11.909 +
  11.910 +
  11.911 +\vspace{0.3cm}
  11.912 +
  11.913 + \noindent {\bf Return Type:}
  11.914 +{\tt
  11.915 +(XSPolicy ref) Set
  11.916 +}
  11.917 +
  11.918 +
  11.919 +A list of all the IDs of all the XSPolicies
  11.920 +\vspace{0.3cm}
  11.921 +\vspace{0.3cm}
  11.922 +\vspace{0.3cm}
  11.923 +\subsubsection{RPC name:~get\_uuid}
  11.924 +
  11.925 +{\bf Overview:}
  11.926 +Get the uuid field of the given XSPolicy.
  11.927 +
  11.928 + \noindent {\bf Signature:}
  11.929 +\begin{verbatim} string get_uuid (session_id s, XSPolicy ref self)\end{verbatim}
  11.930 +
  11.931 +
  11.932 +\noindent{\bf Arguments:}
  11.933 +
  11.934 +
  11.935 +\vspace{0.3cm}
  11.936 +\begin{tabular}{|c|c|p{7cm}|}
  11.937 + \hline
  11.938 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.939 +{\tt XSPolicy ref } & self & reference to the object \\ \hline
  11.940 +
  11.941 +\end{tabular}
  11.942 +
  11.943 +\vspace{0.3cm}
  11.944 +
  11.945 + \noindent {\bf Return Type:}
  11.946 +{\tt
  11.947 +string
  11.948 +}
  11.949 +
  11.950 +
  11.951 +value of the field
  11.952 +\vspace{0.3cm}
  11.953 +\vspace{0.3cm}
  11.954 +\vspace{0.3cm}
  11.955 +\subsubsection{RPC name:~get\_record}
  11.956 +
  11.957 +{\bf Overview:}
  11.958 +Get a record of the referenced XSPolicy.
  11.959 +
  11.960 + \noindent {\bf Signature:}
  11.961 +\begin{verbatim} (XSPolicy record) get_record (session_id s, xs_ref xspolicy)\end{verbatim}
  11.962 +
  11.963 +
  11.964 +\noindent{\bf Arguments:}
  11.965 +
  11.966 +
  11.967 +\vspace{0.3cm}
  11.968 +\begin{tabular}{|c|c|p{7cm}|}
  11.969 + \hline
  11.970 +{\bf type} & {\bf name} & {\bf description} \\ \hline
  11.971 +{\tt xs ref } & self & reference to the object \\ \hline
  11.972 +
  11.973 +\end{tabular}
  11.974 +
  11.975 +\vspace{0.3cm}
  11.976 +
  11.977 + \noindent {\bf Return Type:}
  11.978 +{\tt
  11.979 +XSPolicy record
  11.980 +}
  11.981 +
  11.982 +
  11.983 +all fields from the object
  11.984 +\vspace{0.3cm}
  11.985 +\vspace{0.3cm}
  11.986 +\vspace{0.3cm}
  11.987 +\newpage
  11.988 +\section{Class: ACMPolicy}
  11.989 +\subsection{Fields for class: ACMPolicy}
  11.990 +\begin{longtable}{|lllp{0.38\textwidth}|}
  11.991 +\hline
  11.992 +\multicolumn{1}{|l}{Name} & \multicolumn{3}{l|}{\bf ACMPolicy} \\
  11.993 +\multicolumn{1}{|l}{Description} & \multicolumn{3}{l|}{\parbox{11cm}{\em An ACM Security Policy}} \\
  11.994 +\hline
  11.995 +Quals & Field & Type & Description \\
  11.996 +\hline
  11.997 +$\mathit{RO}_\mathit{run}$ &  {\tt uuid} & string & unique identifier / object reference \\
  11.998 +$\mathit{RW}$              &  {\tt repr} & string & representation of policy, in XML \\
  11.999 +$\mathit{RO}_\mathit{run}$ &  {\tt type} & xs\_type & type of the policy \\
 11.1000 +$\mathit{RO}_\mathit{run}$ & {\tt flags} & xs\_instantiationflags & policy
 11.1001 +status flags \\
 11.1002 +\hline
 11.1003 +\end{longtable}
 11.1004 +
 11.1005 +\subsection{Structure and datatypes of class: ACMPolicy}
 11.1006 +
 11.1007 +\vspace{0.5cm}
 11.1008 +The following data structures are used:
 11.1009 +
 11.1010 +\begin{longtable}{|l|l|l|}
 11.1011 +\hline
 11.1012 +{\tt RIP acm\_policyheader} & type & meaning \\
 11.1013 +\hline
 11.1014 +\hspace{0.5cm}{\tt policyname}   & string & name of the policy \\
 11.1015 +\hspace{0.5cm}{\tt policyurl }   & string & URL of the policy \\
 11.1016 +\hspace{0.5cm}{\tt date}         & string & data of the policy \\
 11.1017 +\hspace{0.5cm}{\tt reference}    & string & reference of the policy \\
 11.1018 +\hspace{0.5cm}{\tt namespaceurl} & string & namespaceurl of the policy \\
 11.1019 +\hspace{0.5cm}{\tt version}      & string & version of the policy \\
 11.1020 +\hline
 11.1021 +\end{longtable}
 11.1022 +
 11.1023 +\vspace{0.3cm}
 11.1024 +\vspace{0.3cm}
 11.1025 +\vspace{0.3cm}
 11.1026 +\subsubsection{RPC name:~get\_header}
 11.1027 +
 11.1028 +{\bf Overview:}
 11.1029 +Get the referenced policy's header information.
 11.1030 +
 11.1031 + \noindent {\bf Signature:}
 11.1032 +\begin{verbatim} acm_policyheader get_header (session_id s, xs ref self)\end{verbatim}
 11.1033 +
 11.1034 +
 11.1035 +\noindent{\bf Arguments:}
 11.1036 +
 11.1037 +
 11.1038 +\vspace{0.3cm}
 11.1039 +\begin{tabular}{|c|c|p{7cm}|}
 11.1040 + \hline
 11.1041 +{\bf type} & {\bf name} & {\bf description} \\ \hline
 11.1042 +{\tt xs ref } & self & reference to the object \\ \hline
 11.1043 +
 11.1044 +\end{tabular}
 11.1045 +
 11.1046 +\vspace{0.3cm}
 11.1047 +
 11.1048 + \noindent {\bf Return Type:}
 11.1049 +{\tt
 11.1050 +acm\_policyheader
 11.1051 +}
 11.1052 +
 11.1053 +
 11.1054 +The policy's header information.
 11.1055 +\vspace{0.3cm}
 11.1056 +\vspace{0.3cm}
 11.1057 +\vspace{0.3cm}
 11.1058 +\subsubsection{RPC name:~get\_xml}
 11.1059 +
 11.1060 +{\bf Overview:}
 11.1061 +Get the XML representation of the given policy.
 11.1062 +
 11.1063 + \noindent {\bf Signature:}
 11.1064 +\begin{verbatim} string get_XML (session_id s, xs ref self)\end{verbatim}
 11.1065 +
 11.1066 +
 11.1067 +\noindent{\bf Arguments:}
 11.1068 +
 11.1069 +
 11.1070 +\vspace{0.3cm}
 11.1071 +\begin{tabular}{|c|c|p{7cm}|}
 11.1072 + \hline
 11.1073 +{\bf type} & {\bf name} & {\bf description} \\ \hline
 11.1074 +{\tt xs ref } & self & reference to the object \\ \hline
 11.1075 +
 11.1076 +\end{tabular}
 11.1077 +
 11.1078 +\vspace{0.3cm}
 11.1079 +
 11.1080 + \noindent {\bf Return Type:}
 11.1081 +{\tt
 11.1082 +string
 11.1083 +}
 11.1084 +
 11.1085 +
 11.1086 +XML representation of the referenced policy
 11.1087 +\vspace{0.3cm}
 11.1088 +\vspace{0.3cm}
 11.1089 +\vspace{0.3cm}
 11.1090 +\subsubsection{RPC name:~get\_map}
 11.1091 +
 11.1092 +{\bf Overview:}
 11.1093 +Get the mapping information of the given policy.
 11.1094 +
 11.1095 + \noindent {\bf Signature:}
 11.1096 +\begin{verbatim} string get_map (session_id s, xs ref self)\end{verbatim}
 11.1097 +
 11.1098 +
 11.1099 +\noindent{\bf Arguments:}
 11.1100 +
 11.1101 +
 11.1102 +\vspace{0.3cm}
 11.1103 +\begin{tabular}{|c|c|p{7cm}|}
 11.1104 + \hline
 11.1105 +{\bf type} & {\bf name} & {\bf description} \\ \hline
 11.1106 +{\tt xs ref } & self & reference to the object \\ \hline
 11.1107 +
 11.1108 +\end{tabular}
 11.1109 +
 11.1110 +\vspace{0.3cm}
 11.1111 +
 11.1112 + \noindent {\bf Return Type:}
 11.1113 +{\tt
 11.1114 +string
 11.1115 +}
 11.1116 +
 11.1117 +
 11.1118 +Mapping information of the referenced policy.
 11.1119 +\vspace{0.3cm}
 11.1120 +\vspace{0.3cm}
 11.1121 +\vspace{0.3cm}
 11.1122 +\subsubsection{RPC name:~get\_binary}
 11.1123 +
 11.1124 +{\bf Overview:}
 11.1125 +Get the binary policy representation of the referenced policy.
 11.1126 +
 11.1127 + \noindent {\bf Signature:}
 11.1128 +\begin{verbatim} string get_map (session_id s, xs ref self)\end{verbatim}
 11.1129 +
 11.1130 +
 11.1131 +\noindent{\bf Arguments:}
 11.1132 +
 11.1133 +
 11.1134 +\vspace{0.3cm}
 11.1135 +\begin{tabular}{|c|c|p{7cm}|}
 11.1136 + \hline
 11.1137 +{\bf type} & {\bf name} & {\bf description} \\ \hline
 11.1138 +{\tt xs ref } & self & reference to the object \\ \hline
 11.1139 +
 11.1140 +\end{tabular}
 11.1141 +
 11.1142 +\vspace{0.3cm}
 11.1143 +
 11.1144 + \noindent {\bf Return Type:}
 11.1145 +{\tt
 11.1146 +string
 11.1147 +}
 11.1148 +
 11.1149 +
 11.1150 +Base64-encoded representation of the binary policy.
 11.1151 +\vspace{0.3cm}
 11.1152 +\vspace{0.3cm}
 11.1153 +\vspace{0.3cm}
 11.1154 +\subsubsection{RPC name:~get\_all}
 11.1155 +
 11.1156 +{\bf Overview:}
 11.1157 +Return a list of all the ACMPolicies known to the system.
 11.1158 +
 11.1159 + \noindent {\bf Signature:}
 11.1160 +\begin{verbatim} ((ACMPolicy ref) Set) get_all (session_id s)\end{verbatim}
 11.1161 +
 11.1162 +
 11.1163 +\vspace{0.3cm}
 11.1164 +
 11.1165 + \noindent {\bf Return Type:}
 11.1166 +{\tt
 11.1167 +(ACMPolicy ref) Set
 11.1168 +}
 11.1169 +
 11.1170 +
 11.1171 +A list of all the IDs of all the ACMPolicies
 11.1172 +\vspace{0.3cm}
 11.1173 +\vspace{0.3cm}
 11.1174 +\vspace{0.3cm}
 11.1175 +\subsubsection{RPC name:~get\_uuid}
 11.1176 +
 11.1177 +{\bf Overview:}
 11.1178 +Get the uuid field of the given ACMPolicy.
 11.1179 +
 11.1180 + \noindent {\bf Signature:}
 11.1181 +\begin{verbatim} string get_uuid (session_id s, ACMPolicy ref self)\end{verbatim}
 11.1182 +
 11.1183 +
 11.1184 +\noindent{\bf Arguments:}
 11.1185 +
 11.1186 +
 11.1187 +\vspace{0.3cm}
 11.1188 +\begin{tabular}{|c|c|p{7cm}|}
 11.1189 + \hline
 11.1190 +{\bf type} & {\bf name} & {\bf description} \\ \hline
 11.1191 +{\tt ACMPolicy ref } & self & reference to the object \\ \hline
 11.1192 +
 11.1193 +\end{tabular}
 11.1194 +
 11.1195 +\vspace{0.3cm}
 11.1196 +
 11.1197 + \noindent {\bf Return Type:}
 11.1198 +{\tt
 11.1199 +string
 11.1200 +}
 11.1201 +
 11.1202 +
 11.1203 +value of the field
 11.1204 +\vspace{0.3cm}
 11.1205 +\vspace{0.3cm}
 11.1206 +\vspace{0.3cm}
 11.1207 +\subsubsection{RPC name:~get\_record}
 11.1208 +
 11.1209 +{\bf Overview:}
 11.1210 +Get a record of the referenced ACMPolicy.
 11.1211 +
 11.1212 + \noindent {\bf Signature:}
 11.1213 +\begin{verbatim} (XSPolicy record) get_record (session_id s, xs_ref xspolicy)\end{verbatim}
 11.1214 +
 11.1215 +
 11.1216 +\noindent{\bf Arguments:}
 11.1217 +
 11.1218 +
 11.1219 +\vspace{0.3cm}
 11.1220 +\begin{tabular}{|c|c|p{7cm}|}
 11.1221 + \hline
 11.1222 +{\bf type} & {\bf name} & {\bf description} \\ \hline
 11.1223 +{\tt xs ref } & self & reference to the object \\ \hline
 11.1224 +
 11.1225 +\end{tabular}
 11.1226 +
 11.1227 +\vspace{0.3cm}
 11.1228 +
 11.1229 + \noindent {\bf Return Type:}
 11.1230 +{\tt
 11.1231 +XSPolicy record
 11.1232 +}
 11.1233 +
 11.1234 +
 11.1235 +all fields from the object
 11.1236 +
 11.1237 +\newpage
 11.1238  \section{Class: debug}
 11.1239  \subsection{Fields for class: debug}
 11.1240  {\bf Class debug has no fields.}
 11.1241 @@ -14192,224 +15342,3 @@ all fields from the object
 11.1242  \vspace{0.3cm}
 11.1243  \vspace{0.3cm}
 11.1244  
 11.1245 -\vspace{1cm}
 11.1246 -\newpage
 11.1247 -\section{Error Handling}
 11.1248 -When a low-level transport error occurs, or a request is malformed at the HTTP
 11.1249 -or XML-RPC level, the server may send an XML-RPC Fault response, or the client
 11.1250 -may simulate the same.  The client must be prepared to handle these errors,
 11.1251 -though they may be treated as fatal.  On the wire, these are transmitted in a
 11.1252 -form similar to this:
 11.1253 -
 11.1254 -\begin{verbatim}
 11.1255 -    <methodResponse>
 11.1256 -      <fault>
 11.1257 -        <value>
 11.1258 -          <struct>
 11.1259 -            <member>
 11.1260 -                <name>faultCode</name>
 11.1261 -                <value><int>-1</int></value>
 11.1262 -              </member>
 11.1263 -              <member>
 11.1264 -                <name>faultString</name>
 11.1265 -                <value><string>Malformed request</string></value>
 11.1266 -            </member>
 11.1267 -          </struct>
 11.1268 -        </value>
 11.1269 -      </fault>
 11.1270 -    </methodResponse>
 11.1271 -\end{verbatim}
 11.1272 -
 11.1273 -All other failures are reported with a more structured error response, to
 11.1274 -allow better automatic response to failures, proper internationalisation of
 11.1275 -any error message, and easier debugging.  On the wire, these are transmitted
 11.1276 -like this:
 11.1277 -
 11.1278 -\begin{verbatim}
 11.1279 -    <struct>
 11.1280 -      <member>
 11.1281 -        <name>Status</name>
 11.1282 -        <value>Failure</value>
 11.1283 -      </member>
 11.1284 -      <member>
 11.1285 -        <name>ErrorDescription</name>
 11.1286 -        <value>
 11.1287 -          <array>
 11.1288 -            <data>
 11.1289 -              <value>MAP_DUPLICATE_KEY</value>
 11.1290 -              <value>Customer</value>
 11.1291 -              <value>eSpeil Inc.</value>
 11.1292 -              <value>eSpeil Incorporated</value>
 11.1293 -            </data>
 11.1294 -          </array>
 11.1295 -        </value>
 11.1296 -      </member>
 11.1297 -    </struct>
 11.1298 -\end{verbatim}
 11.1299 -
 11.1300 -Note that {\tt ErrorDescription} value is an array of string values. The
 11.1301 -first element of the array is an error code; the remainder of the array are
 11.1302 -strings representing error parameters relating to that code.  In this case,
 11.1303 -the client has attempted to add the mapping {\tt Customer $\rightarrow$
 11.1304 -eSpiel Incorporated} to a Map, but it already contains the mapping
 11.1305 -{\tt Customer $\rightarrow$ eSpiel Inc.}, and so the request has failed.
 11.1306 -
 11.1307 -Each possible error code is documented in the following section.
 11.1308 -
 11.1309 -\subsection{Error Codes}
 11.1310 -
 11.1311 -\subsubsection{HANDLE\_INVALID}
 11.1312 -
 11.1313 -You gave an invalid handle.  The object may have recently been deleted. 
 11.1314 -The class parameter gives the type of reference given, and the handle
 11.1315 -parameter echoes the bad value given.
 11.1316 -
 11.1317 -\vspace{0.3cm}
 11.1318 -{\bf Signature:}
 11.1319 -\begin{verbatim}HANDLE_INVALID(class, handle)\end{verbatim}
 11.1320 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1321 -
 11.1322 -\subsubsection{INTERNAL\_ERROR}
 11.1323 -
 11.1324 -The server failed to handle your request, due to an internal error.  The
 11.1325 -given message may give details useful for debugging the problem.
 11.1326 -
 11.1327 -\vspace{0.3cm}
 11.1328 -{\bf Signature:}
 11.1329 -\begin{verbatim}INTERNAL_ERROR(message)\end{verbatim}
 11.1330 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1331 -
 11.1332 -\subsubsection{MAP\_DUPLICATE\_KEY}
 11.1333 -
 11.1334 -You tried to add a key-value pair to a map, but that key is already there. 
 11.1335 -The key, current value, and the new value that you tried to set are all
 11.1336 -echoed.
 11.1337 -
 11.1338 -\vspace{0.3cm}
 11.1339 -{\bf Signature:}
 11.1340 -\begin{verbatim}MAP_DUPLICATE_KEY(key, current value, new value)\end{verbatim}
 11.1341 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1342 -
 11.1343 -\subsubsection{MESSAGE\_METHOD\_UNKNOWN}
 11.1344 -
 11.1345 -You tried to call a method that does not exist.  The method name that you
 11.1346 -used is echoed.
 11.1347 -
 11.1348 -\vspace{0.3cm}
 11.1349 -{\bf Signature:}
 11.1350 -\begin{verbatim}MESSAGE_METHOD_UNKNOWN(method)\end{verbatim}
 11.1351 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1352 -
 11.1353 -\subsubsection{MESSAGE\_PARAMETER\_COUNT\_MISMATCH}
 11.1354 -
 11.1355 -You tried to call a method with the incorrect number of parameters.  The
 11.1356 -fully-qualified method name that you used, and the number of received and
 11.1357 -expected parameters are returned.
 11.1358 -
 11.1359 -\vspace{0.3cm}
 11.1360 -{\bf Signature:}
 11.1361 -\begin{verbatim}MESSAGE_PARAMETER_COUNT_MISMATCH(method, expected, received)\end{verbatim}
 11.1362 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1363 -
 11.1364 -\subsubsection{NETWORK\_ALREADY\_CONNECTED}
 11.1365 -
 11.1366 -You tried to create a PIF, but the network you tried to attach it to is
 11.1367 -already attached to some other PIF, and so the creation failed.
 11.1368 -
 11.1369 -\vspace{0.3cm}
 11.1370 -{\bf Signature:}
 11.1371 -\begin{verbatim}NETWORK_ALREADY_CONNECTED(network, connected PIF)\end{verbatim}
 11.1372 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1373 -
 11.1374 -\subsubsection{OPERATION\_NOT\_ALLOWED}
 11.1375 -
 11.1376 -You attempted an operation that was not allowed.
 11.1377 -
 11.1378 -\vspace{0.3cm}
 11.1379 -No parameters.
 11.1380 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1381 -
 11.1382 -\subsubsection{PIF\_IS\_PHYSICAL}
 11.1383 -
 11.1384 -You tried to destroy a PIF, but it represents an aspect of the physical
 11.1385 -host configuration, and so cannot be destroyed.  The parameter echoes the
 11.1386 -PIF handle you gave.
 11.1387 -
 11.1388 -\vspace{0.3cm}
 11.1389 -{\bf Signature:}
 11.1390 -\begin{verbatim}PIF_IS_PHYSICAL(PIF)\end{verbatim}
 11.1391 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1392 -
 11.1393 -\subsubsection{SESSION\_AUTHENTICATION\_FAILED}
 11.1394 -
 11.1395 -The credentials given by the user are incorrect, so access has been denied,
 11.1396 -and you have not been issued a session handle.
 11.1397 -
 11.1398 -\vspace{0.3cm}
 11.1399 -No parameters.
 11.1400 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1401 -
 11.1402 -\subsubsection{SESSION\_INVALID}
 11.1403 -
 11.1404 -You gave an invalid session handle.  It may have been invalidated by a
 11.1405 -server restart, or timed out.  You should get a new session handle, using
 11.1406 -one of the session.login\_ calls.  This error does not invalidate the
 11.1407 -current connection.  The handle parameter echoes the bad value given.
 11.1408 -
 11.1409 -\vspace{0.3cm}
 11.1410 -{\bf Signature:}
 11.1411 -\begin{verbatim}SESSION_INVALID(handle)\end{verbatim}
 11.1412 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1413 -
 11.1414 -\subsubsection{SESSION\_NOT\_REGISTERED}
 11.1415 -
 11.1416 -This session is not registered to receive events.  You must call
 11.1417 -event.register before event.next.  The session handle you are using is
 11.1418 -echoed.
 11.1419 -
 11.1420 -\vspace{0.3cm}
 11.1421 -{\bf Signature:}
 11.1422 -\begin{verbatim}SESSION_NOT_REGISTERED(handle)\end{verbatim}
 11.1423 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1424 -
 11.1425 -\subsubsection{VALUE\_NOT\_SUPPORTED}
 11.1426 -
 11.1427 -You attempted to set a value that is not supported by this implementation. 
 11.1428 -The fully-qualified field name and the value that you tried to set are
 11.1429 -returned.  Also returned is a developer-only diagnostic reason.
 11.1430 -
 11.1431 -\vspace{0.3cm}
 11.1432 -{\bf Signature:}
 11.1433 -\begin{verbatim}VALUE_NOT_SUPPORTED(field, value, reason)\end{verbatim}
 11.1434 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1435 -
 11.1436 -\subsubsection{VLAN\_TAG\_INVALID}
 11.1437 -
 11.1438 -You tried to create a VLAN, but the tag you gave was invalid -- it mmust be
 11.1439 -between 0 and 4095.  The parameter echoes the VLAN tag you gave.
 11.1440 -
 11.1441 -\vspace{0.3cm}
 11.1442 -{\bf Signature:}
 11.1443 -\begin{verbatim}VLAN_TAG_INVALID(VLAN)\end{verbatim}
 11.1444 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1445 -
 11.1446 -\subsubsection{VM\_BAD\_POWER\_STATE}
 11.1447 -
 11.1448 -You attempted an operation on a VM that was not in an appropriate power
 11.1449 -state at the time; for example, you attempted to start a VM that was
 11.1450 -already running.  The parameters returned are the VM's handle, and the
 11.1451 -expected and actual VM state at the time of the call.
 11.1452 -
 11.1453 -\vspace{0.3cm}
 11.1454 -{\bf Signature:}
 11.1455 -\begin{verbatim}VM_BAD_POWER_STATE(vm, expected, actual)\end{verbatim}
 11.1456 -\begin{center}\rule{10em}{0.1pt}\end{center}
 11.1457 -
 11.1458 -\subsubsection{VM\_HVM\_REQUIRED}
 11.1459 -
 11.1460 -HVM is required for this operation
 11.1461 -
 11.1462 -\vspace{0.3cm}
 11.1463 -{\bf Signature:}
 11.1464 -\begin{verbatim}VM_HVM_REQUIRED(vm)\end{verbatim}
 11.1465 -\begin{center}\rule{10em}{0.1pt}\end{center}
    12.1 --- a/tools/examples/vtpm-common.sh	Thu Jul 26 14:35:01 2007 -0600
    12.2 +++ b/tools/examples/vtpm-common.sh	Fri Jul 27 08:15:16 2007 -0600
    12.3 @@ -20,7 +20,7 @@ dir=$(dirname "$0")
    12.4  . "$dir/logging.sh"
    12.5  . "$dir/locking.sh"
    12.6  
    12.7 -VTPMDB="/etc/xen/vtpm.db"
    12.8 +VTPMDB="/var/vtpm/vtpm.db"
    12.9  
   12.10  #In the vtpm-impl file some commands should be defined:
   12.11  #      vtpm_create, vtpm_setup, vtpm_start, etc. (see below)
   12.12 @@ -241,12 +241,21 @@ function vtpm_get_create_reason () {
   12.13  # If no entry in the TPM database is found, the instance is
   12.14  # created and an entry added to the database.
   12.15  function vtpm_create_instance () {
   12.16 -	local res instance domname reason
   12.17 -	domname=$(xenstore_read "$XENBUS_PATH"/domain)
   12.18 +	local res instance domname reason uuid
   12.19 +	uuid=$(xenstore_read "$XENBUS_PATH"/uuid)
   12.20  	reason=$(vtpm_get_create_reason)
   12.21  
   12.22  	claim_lock vtpmdb
   12.23 -	instance=$(vtpmdb_find_instance $domname)
   12.24 +
   12.25 +	instance="0"
   12.26 +
   12.27 +	if [ "$uuid" != "" ]; then
   12.28 +		instance=$(vtpmdb_find_instance $uuid)
   12.29 +	fi
   12.30 +	if [ "$instance" == "0" ]; then
   12.31 +		domname=$(xenstore_read "$XENBUS_PATH"/domain)
   12.32 +		instance=$(vtpmdb_find_instance $domname)
   12.33 +	fi
   12.34  
   12.35  	if [ "$instance" == "0" -a "$reason" != "create" ]; then
   12.36  		release_lock vtpmdb
   12.37 @@ -268,7 +277,11 @@ function vtpm_create_instance () {
   12.38  		vtpm_create $instance
   12.39  
   12.40  		if [ $vtpm_fatal_error -eq 0 ]; then
   12.41 -			vtpmdb_add_instance $domname $instance
   12.42 +			if [ "$uuid" != "" ]; then
   12.43 +				vtpmdb_add_instance $uuid $instance
   12.44 +			else
   12.45 +				vtpmdb_add_instance $domname $instance
   12.46 +			fi
   12.47  		fi
   12.48  	else
   12.49  		if [ "$reason" == "resume" ]; then
   12.50 @@ -288,22 +301,29 @@ function vtpm_create_instance () {
   12.51  #Since it is assumed that the VM will appear again, the
   12.52  #entry is kept in the VTPMDB file.
   12.53  function vtpm_remove_instance () {
   12.54 -	local instance reason domname
   12.55 +	local instance reason domname uuid
   12.56  	#Stop script execution quietly if path does not exist (anymore)
   12.57  	xenstore-exists "$XENBUS_PATH"/domain
   12.58 -	domname=$(xenstore_read "$XENBUS_PATH"/domain)
   12.59 +	uuid=$(xenstore_read "$XENBUS_PATH"/uuid)
   12.60 +
   12.61 +	claim_lock vtpmdb
   12.62  
   12.63 -	if [ "$domname" != "" ]; then
   12.64 -		claim_lock vtpmdb
   12.65 +	instance="0"
   12.66  
   12.67 -		instance=$(vtpmdb_find_instance $domname)
   12.68 +	if [ "$uuid != "" ]; then
   12.69 +		instance=$(vtpmdb_find_instance $uuid)
   12.70 +	fi
   12.71  
   12.72 -		if [ "$instance" != "0" ]; then
   12.73 -			vtpm_suspend $instance
   12.74 -		fi
   12.75 +	if [ "$instance == "0" ]; then
   12.76 +		domname=$(xenstore_read "$XENBUS_PATH"/domain)
   12.77 +		instance=$(vtpmdb_find_instance $domname)
   12.78 +	fi
   12.79  
   12.80 -		release_lock vtpmdb
   12.81 +	if [ "$instance" != "0" ]; then
   12.82 +		vtpm_suspend $instance
   12.83  	fi
   12.84 +
   12.85 +	release_lock vtpmdb
   12.86  }
   12.87  
   12.88  
    13.1 --- a/tools/firmware/hvmloader/acpi/dsdt.asl	Thu Jul 26 14:35:01 2007 -0600
    13.2 +++ b/tools/firmware/hvmloader/acpi/dsdt.asl	Fri Jul 27 08:15:16 2007 -0600
    13.3 @@ -123,11 +123,12 @@ DefinitionBlock ("DSDT.aml", "DSDT", 2, 
    13.4              }
    13.5  
    13.6              Name(BUFA, ResourceTemplate() {
    13.7 -                IRQ(Level, ActiveLow, Shared) { 5, 7, 10, 11 }
    13.8 +                IRQ(Level, ActiveLow, Shared) { 5, 10, 11 }
    13.9              })
   13.10  
   13.11              Name(BUFB, Buffer() {
   13.12 -                0x23, 0x00, 0x00, 0x18, 0x79, 0
   13.13 +                0x23, 0x00, 0x00, 0x18, /* IRQ descriptor */
   13.14 +                0x79, 0                 /* End tag, null checksum */
   13.15              })
   13.16  
   13.17              CreateWordField(BUFB, 0x01, IRQV)
   13.18 @@ -643,6 +644,22 @@ DefinitionBlock ("DSDT.aml", "DSDT", 2, 
   13.19                          IRQNoFlags () {4}
   13.20                      })
   13.21                  }
   13.22 +
   13.23 +                Device (LTP1)
   13.24 +                {
   13.25 +                    Name (_HID, EisaId ("PNP0400"))
   13.26 +                    Name (_UID, 0x02)
   13.27 +                    Method (_STA, 0, NotSerialized)
   13.28 +                    {
   13.29 +                        Return (0x0F)
   13.30 +                    }
   13.31 +
   13.32 +                    Name (_CRS, ResourceTemplate()
   13.33 +                    {
   13.34 +                        IO (Decode16, 0x0378, 0x0378, 0x08, 0x08)
   13.35 +                        IRQNoFlags () {7}
   13.36 +                    })
   13.37 +                } 
   13.38              }
   13.39          }
   13.40      }
    14.1 --- a/tools/firmware/hvmloader/acpi/dsdt.c	Thu Jul 26 14:35:01 2007 -0600
    14.2 +++ b/tools/firmware/hvmloader/acpi/dsdt.c	Fri Jul 27 08:15:16 2007 -0600
    14.3 @@ -1,19 +1,19 @@
    14.4  /*
    14.5   * 
    14.6   * Intel ACPI Component Architecture
    14.7 - * ASL Optimizing Compiler version 20060707 [Dec 30 2006]
    14.8 + * ASL Optimizing Compiler version 20060707 [Feb 16 2007]
    14.9   * Copyright (C) 2000 - 2006 Intel Corporation
   14.10   * Supports ACPI Specification Revision 3.0a
   14.11   * 
   14.12 - * Compilation of "dsdt.asl" - Sat May 12 16:13:55 2007
   14.13 + * Compilation of "dsdt.asl" - Wed Jul 11 13:34:30 2007
   14.14   * 
   14.15   * C source code output
   14.16   *
   14.17   */
   14.18  unsigned char AmlCode[] =
   14.19  {
   14.20 -    0x44,0x53,0x44,0x54,0x67,0x0D,0x00,0x00,  /* 00000000    "DSDTg..." */
   14.21 -    0x02,0xE0,0x58,0x65,0x6E,0x00,0x00,0x00,  /* 00000008    "..Xen..." */
   14.22 +    0x44,0x53,0x44,0x54,0x9F,0x0D,0x00,0x00,  /* 00000000    "DSDT...." */
   14.23 +    0x02,0x2E,0x58,0x65,0x6E,0x00,0x00,0x00,  /* 00000008    "..Xen..." */
   14.24      0x48,0x56,0x4D,0x00,0x00,0x00,0x00,0x00,  /* 00000010    "HVM....." */
   14.25      0x00,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C,  /* 00000018    "....INTL" */
   14.26      0x07,0x07,0x06,0x20,0x08,0x50,0x4D,0x42,  /* 00000020    "... .PMB" */
   14.27 @@ -27,7 +27,7 @@ unsigned char AmlCode[] =
   14.28      0x04,0x0A,0x07,0x0A,0x07,0x00,0x00,0x08,  /* 00000060    "........" */
   14.29      0x50,0x49,0x43,0x44,0x00,0x14,0x0C,0x5F,  /* 00000068    "PICD..._" */
   14.30      0x50,0x49,0x43,0x01,0x70,0x68,0x50,0x49,  /* 00000070    "PIC.phPI" */
   14.31 -    0x43,0x44,0x10,0x4C,0xCE,0x5F,0x53,0x42,  /* 00000078    "CD.L._SB" */
   14.32 +    0x43,0x44,0x10,0x44,0xD2,0x5F,0x53,0x42,  /* 00000078    "CD.D._SB" */
   14.33      0x5F,0x5B,0x82,0x49,0x04,0x4D,0x45,0x4D,  /* 00000080    "_[.I.MEM" */
   14.34      0x30,0x08,0x5F,0x48,0x49,0x44,0x0C,0x41,  /* 00000088    "0._HID.A" */
   14.35      0xD0,0x0C,0x02,0x08,0x5F,0x43,0x52,0x53,  /* 00000090    "...._CRS" */
   14.36 @@ -37,7 +37,7 @@ unsigned char AmlCode[] =
   14.37      0x00,0x00,0xFF,0xFF,0x09,0x00,0x00,0x00,  /* 000000B0    "........" */
   14.38      0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 000000B8    "........" */
   14.39      0x00,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,  /* 000000C0    "........" */
   14.40 -    0x00,0x00,0x79,0x00,0x5B,0x82,0x49,0xC9,  /* 000000C8    "..y.[.I." */
   14.41 +    0x00,0x00,0x79,0x00,0x5B,0x82,0x41,0xCD,  /* 000000C8    "..y.[.A." */
   14.42      0x50,0x43,0x49,0x30,0x08,0x5F,0x48,0x49,  /* 000000D0    "PCI0._HI" */
   14.43      0x44,0x0C,0x41,0xD0,0x0A,0x03,0x08,0x5F,  /* 000000D8    "D.A...._" */
   14.44      0x55,0x49,0x44,0x00,0x08,0x5F,0x41,0x44,  /* 000000E0    "UID.._AD" */
   14.45 @@ -59,7 +59,7 @@ unsigned char AmlCode[] =
   14.46      0x00,0xF0,0xFF,0xFF,0xFF,0xF4,0x00,0x00,  /* 00000160    "........" */
   14.47      0x00,0x00,0x00,0x00,0x00,0x05,0x79,0x00,  /* 00000168    "......y." */
   14.48      0xA4,0x50,0x52,0x54,0x30,0x08,0x42,0x55,  /* 00000170    ".PRT0.BU" */
   14.49 -    0x46,0x41,0x11,0x09,0x0A,0x06,0x23,0xA0,  /* 00000178    "FA....#." */
   14.50 +    0x46,0x41,0x11,0x09,0x0A,0x06,0x23,0x20,  /* 00000178    "FA....# " */
   14.51      0x0C,0x18,0x79,0x00,0x08,0x42,0x55,0x46,  /* 00000180    "..y..BUF" */
   14.52      0x42,0x11,0x09,0x0A,0x06,0x23,0x00,0x00,  /* 00000188    "B....#.." */
   14.53      0x18,0x79,0x00,0x8B,0x42,0x55,0x46,0x42,  /* 00000190    ".y..BUFB" */
   14.54 @@ -348,7 +348,7 @@ unsigned char AmlCode[] =
   14.55      0x0C,0x04,0x0C,0xFF,0xFF,0x0F,0x00,0x0A,  /* 00000A68    "........" */
   14.56      0x02,0x00,0x0A,0x2F,0x12,0x0C,0x04,0x0C,  /* 00000A70    ".../...." */
   14.57      0xFF,0xFF,0x0F,0x00,0x0A,0x03,0x00,0x0A,  /* 00000A78    "........" */
   14.58 -    0x10,0x5B,0x82,0x44,0x2E,0x49,0x53,0x41,  /* 00000A80    ".[.D.ISA" */
   14.59 +    0x10,0x5B,0x82,0x4C,0x31,0x49,0x53,0x41,  /* 00000A80    ".[.L1ISA" */
   14.60      0x5F,0x08,0x5F,0x41,0x44,0x52,0x0C,0x00,  /* 00000A88    "_._ADR.." */
   14.61      0x00,0x01,0x00,0x5B,0x80,0x50,0x49,0x52,  /* 00000A90    "...[.PIR" */
   14.62      0x51,0x02,0x0A,0x60,0x0A,0x04,0x10,0x2E,  /* 00000A98    "Q..`...." */
   14.63 @@ -440,6 +440,13 @@ unsigned char AmlCode[] =
   14.64      0x09,0x5F,0x53,0x54,0x41,0x00,0xA4,0x0A,  /* 00000D48    "._STA..." */
   14.65      0x0F,0x08,0x5F,0x43,0x52,0x53,0x11,0x10,  /* 00000D50    ".._CRS.." */
   14.66      0x0A,0x0D,0x47,0x01,0xF8,0x03,0xF8,0x03,  /* 00000D58    "..G....." */
   14.67 -    0x01,0x08,0x22,0x10,0x00,0x79,0x00,
   14.68 +    0x01,0x08,0x22,0x10,0x00,0x79,0x00,0x5B,  /* 00000D60    ".."..y.[" */
   14.69 +    0x82,0x36,0x4C,0x54,0x50,0x31,0x08,0x5F,  /* 00000D68    ".6LTP1._" */
   14.70 +    0x48,0x49,0x44,0x0C,0x41,0xD0,0x04,0x00,  /* 00000D70    "HID.A..." */
   14.71 +    0x08,0x5F,0x55,0x49,0x44,0x0A,0x02,0x14,  /* 00000D78    "._UID..." */
   14.72 +    0x09,0x5F,0x53,0x54,0x41,0x00,0xA4,0x0A,  /* 00000D80    "._STA..." */
   14.73 +    0x0F,0x08,0x5F,0x43,0x52,0x53,0x11,0x10,  /* 00000D88    ".._CRS.." */
   14.74 +    0x0A,0x0D,0x47,0x01,0x78,0x03,0x78,0x03,  /* 00000D90    "..G.x.x." */
   14.75 +    0x08,0x08,0x22,0x80,0x00,0x79,0x00,
   14.76  };
   14.77  int DsdtLen=sizeof(AmlCode);
    15.1 --- a/tools/firmware/hvmloader/config.h	Thu Jul 26 14:35:01 2007 -0600
    15.2 +++ b/tools/firmware/hvmloader/config.h	Fri Jul 27 08:15:16 2007 -0600
    15.3 @@ -9,7 +9,7 @@
    15.4  #define LAPIC_ID(vcpu_id)   ((vcpu_id) * 2)
    15.5  
    15.6  #define PCI_ISA_DEVFN       0x08    /* dev 1, fn 0 */
    15.7 -#define PCI_ISA_IRQ_MASK    0x0ca0U /* ISA IRQs 5,7,10,11 are PCI connected */
    15.8 +#define PCI_ISA_IRQ_MASK    0x0c20U /* ISA IRQs 5,10,11 are PCI connected */
    15.9  
   15.10  #define ROMBIOS_SEG            0xF000
   15.11  #define ROMBIOS_BEGIN          0x000F0000
    16.1 --- a/tools/firmware/hvmloader/hvmloader.c	Thu Jul 26 14:35:01 2007 -0600
    16.2 +++ b/tools/firmware/hvmloader/hvmloader.c	Fri Jul 27 08:15:16 2007 -0600
    16.3 @@ -180,15 +180,13 @@ static void pci_setup(void)
    16.4      unsigned int bar, pin, link, isa_irq;
    16.5  
    16.6      /* Program PCI-ISA bridge with appropriate link routes. */
    16.7 -    link = 0;
    16.8 -    for ( isa_irq = 0; isa_irq < 15; isa_irq++ )
    16.9 +    isa_irq = 0;
   16.10 +    for ( link = 0; link < 4; link++ )
   16.11      {
   16.12 -        if ( !(PCI_ISA_IRQ_MASK & (1U << isa_irq)) )
   16.13 -            continue;
   16.14 +        do { isa_irq = (isa_irq + 1) & 15;
   16.15 +        } while ( !(PCI_ISA_IRQ_MASK & (1U << isa_irq)) );
   16.16          pci_writeb(PCI_ISA_DEVFN, 0x60 + link, isa_irq);
   16.17          printf("PCI-ISA link %u routed to IRQ%u\n", link, isa_irq);
   16.18 -        if ( link++ == 4 )
   16.19 -            break;
   16.20      }
   16.21  
   16.22      /* Program ELCR to match PCI-wired IRQs. */
    17.1 --- a/tools/firmware/rombios/rombios.c	Thu Jul 26 14:35:01 2007 -0600
    17.2 +++ b/tools/firmware/rombios/rombios.c	Fri Jul 27 08:15:16 2007 -0600
    17.3 @@ -9146,78 +9146,78 @@ pci_routing_table_structure:
    17.4    db 0 ;; pci bus number
    17.5    db 0x08 ;; pci device number (bit 7-3)
    17.6    db 0x61 ;; link value INTA#: pointer into PCI2ISA config space
    17.7 -  dw 0x0ca0 ;; IRQ bitmap INTA# 
    17.8 +  dw 0x0c20 ;; IRQ bitmap INTA# 
    17.9    db 0x62 ;; link value INTB#
   17.10 -  dw 0x0ca0 ;; IRQ bitmap INTB# 
   17.11 +  dw 0x0c20 ;; IRQ bitmap INTB# 
   17.12    db 0x63 ;; link value INTC#
   17.13 -  dw 0x0ca0 ;; IRQ bitmap INTC# 
   17.14 +  dw 0x0c20 ;; IRQ bitmap INTC# 
   17.15    db 0x60 ;; link value INTD#
   17.16 -  dw 0x0ca0 ;; IRQ bitmap INTD#
   17.17 +  dw 0x0c20 ;; IRQ bitmap INTD#
   17.18    db 0 ;; physical slot (0 = embedded)
   17.19    db 0 ;; reserved
   17.20    ;; second slot entry: 1st PCI slot
   17.21    db 0 ;; pci bus number
   17.22    db 0x10 ;; pci device number (bit 7-3)
   17.23    db 0x62 ;; link value INTA#
   17.24 -  dw 0x0ca0 ;; IRQ bitmap INTA# 
   17.25 +  dw 0x0c20 ;; IRQ bitmap INTA# 
   17.26    db 0x63 ;; link value INTB#
   17.27 -  dw 0x0ca0 ;; IRQ bitmap INTB# 
   17.28 +  dw 0x0c20 ;; IRQ bitmap INTB# 
   17.29    db 0x60 ;; link value INTC#
   17.30 -  dw 0x0ca0 ;; IRQ bitmap INTC# 
   17.31 +  dw 0x0c20 ;; IRQ bitmap INTC# 
   17.32    db 0x61 ;; link value INTD#
   17.33 -  dw 0x0ca0 ;; IRQ bitmap INTD#
   17.34 +  dw 0x0c20 ;; IRQ bitmap INTD#
   17.35    db 1 ;; physical slot (0 = embedded)
   17.36    db 0 ;; reserved
   17.37    ;; third slot entry: 2nd PCI slot
   17.38    db 0 ;; pci bus number
   17.39    db 0x18 ;; pci device number (bit 7-3)
   17.40    db 0x63 ;; link value INTA#
   17.41 -  dw 0x0ca0 ;; IRQ bitmap INTA# 
   17.42 +  dw 0x0c20 ;; IRQ bitmap INTA# 
   17.43    db 0x60 ;; link value INTB#
   17.44 -  dw 0x0ca0 ;; IRQ bitmap INTB# 
   17.45 +  dw 0x0c20 ;; IRQ bitmap INTB# 
   17.46    db 0x61 ;; link value INTC#
   17.47 -  dw 0x0ca0 ;; IRQ bitmap INTC# 
   17.48 +  dw 0x0c20 ;; IRQ bitmap INTC# 
   17.49    db 0x62 ;; link value INTD#
   17.50 -  dw 0x0ca0 ;; IRQ bitmap INTD#
   17.51 +  dw 0x0c20 ;; IRQ bitmap INTD#
   17.52    db 2 ;; physical slot (0 = embedded)
   17.53    db 0 ;; reserved
   17.54    ;; 4th slot entry: 3rd PCI slot
   17.55    db 0 ;; pci bus number
   17.56    db 0x20 ;; pci device number (bit 7-3)
   17.57    db 0x60 ;; link value INTA#
   17.58 -  dw 0x0ca0 ;; IRQ bitmap INTA# 
   17.59 +  dw 0x0c20 ;; IRQ bitmap INTA# 
   17.60    db 0x61 ;; link value INTB#
   17.61 -  dw 0x0ca0 ;; IRQ bitmap INTB# 
   17.62 +  dw 0x0c20 ;; IRQ bitmap INTB# 
   17.63    db 0x62 ;; link value INTC#
   17.64 -  dw 0x0ca0 ;; IRQ bitmap INTC# 
   17.65 +  dw 0x0c20 ;; IRQ bitmap INTC# 
   17.66    db 0x63 ;; link value INTD#
   17.67 -  dw 0x0ca0 ;; IRQ bitmap INTD#
   17.68 +  dw 0x0c20 ;; IRQ bitmap INTD#
   17.69    db 3 ;; physical slot (0 = embedded)
   17.70    db 0 ;; reserved
   17.71    ;; 5th slot entry: 4rd PCI slot
   17.72    db 0 ;; pci bus number
   17.73    db 0x28 ;; pci device number (bit 7-3)
   17.74    db 0x61 ;; link value INTA#
   17.75 -  dw 0x0ca0 ;; IRQ bitmap INTA# 
   17.76 +  dw 0x0c20 ;; IRQ bitmap INTA# 
   17.77    db 0x62 ;; link value INTB#
   17.78 -  dw 0x0ca0 ;; IRQ bitmap INTB# 
   17.79 +  dw 0x0c20 ;; IRQ bitmap INTB# 
   17.80    db 0x63 ;; link value INTC#
   17.81 -  dw 0x0ca0 ;; IRQ bitmap INTC# 
   17.82 +  dw 0x0c20 ;; IRQ bitmap INTC# 
   17.83    db 0x60 ;; link value INTD#
   17.84 -  dw 0x0ca0 ;; IRQ bitmap INTD#
   17.85 +  dw 0x0c20 ;; IRQ bitmap INTD#
   17.86    db 4 ;; physical slot (0 = embedded)
   17.87    db 0 ;; reserved
   17.88    ;; 6th slot entry: 5rd PCI slot
   17.89    db 0 ;; pci bus number
   17.90    db 0x30 ;; pci device number (bit 7-3)
   17.91    db 0x62 ;; link value INTA#
   17.92 -  dw 0x0ca0 ;; IRQ bitmap INTA# 
   17.93 +  dw 0x0c20 ;; IRQ bitmap INTA# 
   17.94    db 0x63 ;; link value INTB#
   17.95 -  dw 0x0ca0 ;; IRQ bitmap INTB# 
   17.96 +  dw 0x0c20 ;; IRQ bitmap INTB# 
   17.97    db 0x60 ;; link value INTC#
   17.98 -  dw 0x0ca0 ;; IRQ bitmap INTC# 
   17.99 +  dw 0x0c20 ;; IRQ bitmap INTC# 
  17.100    db 0x61 ;; link value INTD#
  17.101 -  dw 0x0ca0 ;; IRQ bitmap INTD#
  17.102 +  dw 0x0c20 ;; IRQ bitmap INTD#
  17.103    db 5 ;; physical slot (0 = embedded)
  17.104    db 0 ;; reserved
  17.105  #endif // BX_PCIBIOS
    18.1 --- a/tools/ioemu/hw/cirrus_vga.c	Thu Jul 26 14:35:01 2007 -0600
    18.2 +++ b/tools/ioemu/hw/cirrus_vga.c	Fri Jul 27 08:15:16 2007 -0600
    18.3 @@ -3096,8 +3096,6 @@ static void cirrus_vga_save(QEMUFile *f,
    18.4      qemu_put_be64s(f, (uint64_t*)&s->cirrus_lfb_addr);
    18.5      qemu_put_be64s(f, (uint64_t*)&s->cirrus_lfb_end);
    18.6      qemu_put_buffer(f, s->vram_ptr, VGA_RAM_SIZE); 
    18.7 -    if (vga_acc)
    18.8 -        cirrus_stop_acc(s);
    18.9  }
   18.10  
   18.11  static int cirrus_vga_load(QEMUFile *f, void *opaque, int version_id)
    19.1 --- a/tools/ioemu/hw/ide.c	Thu Jul 26 14:35:01 2007 -0600
    19.2 +++ b/tools/ioemu/hw/ide.c	Fri Jul 27 08:15:16 2007 -0600
    19.3 @@ -596,7 +596,8 @@ static void ide_identify(IDEState *s)
    19.4      /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
    19.5      put_le16(p + 83, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
    19.6      put_le16(p + 84, (1 << 14));
    19.7 -    put_le16(p + 85, (1 << 14));
    19.8 +    /* 14=nop 5=write_cache */
    19.9 +    put_le16(p + 85, (1 << 14) | (1 << 5));
   19.10      /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
   19.11      put_le16(p + 86, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
   19.12      put_le16(p + 87, (1 << 14));
    20.1 --- a/tools/ioemu/hw/rtl8139.c	Thu Jul 26 14:35:01 2007 -0600
    20.2 +++ b/tools/ioemu/hw/rtl8139.c	Fri Jul 27 08:15:16 2007 -0600
    20.3 @@ -53,9 +53,8 @@
    20.4  /* debug RTL8139 card C+ mode only */
    20.5  //#define DEBUG_RTL8139CP 1
    20.6  
    20.7 -/* RTL8139 provides frame CRC with received packet, this feature seems to be
    20.8 -   ignored by most drivers, disabled by default */
    20.9 -//#define RTL8139_CALCULATE_RXCRC 1
   20.10 +/* Calculate CRCs propoerly on Rx packets */
   20.11 +#define RTL8139_CALCULATE_RXCRC 1
   20.12  
   20.13  /* Uncomment to enable on-board timer interrupts */
   20.14  //#define RTL8139_ONBOARD_TIMER 1
   20.15 @@ -754,7 +753,7 @@ static void rtl8139_write_buffer(RTL8139
   20.16          int wrapped = MOD2(s->RxBufAddr + size, s->RxBufferSize);
   20.17  
   20.18          /* write packet data */
   20.19 -        if (wrapped && s->RxBufferSize < 65536 && !rtl8139_RxWrap(s))
   20.20 +        if (wrapped && !(s->RxBufferSize < 65536 && rtl8139_RxWrap(s)))
   20.21          {
   20.22              DEBUG_PRINT((">>> RTL8139: rx packet wrapped in buffer at %d\n", size-wrapped));
   20.23  
   20.24 @@ -1030,7 +1029,7 @@ static void rtl8139_do_receive(void *opa
   20.25  
   20.26          /* write checksum */
   20.27  #if defined (RTL8139_CALCULATE_RXCRC)
   20.28 -        val = cpu_to_le32(crc32(~0, buf, size));
   20.29 +        val = cpu_to_le32(crc32(0, buf, size));
   20.30  #else
   20.31          val = 0;
   20.32  #endif
   20.33 @@ -1136,7 +1135,7 @@ static void rtl8139_do_receive(void *opa
   20.34  
   20.35          /* write checksum */
   20.36  #if defined (RTL8139_CALCULATE_RXCRC)
   20.37 -        val = cpu_to_le32(crc32(~0, buf, size));
   20.38 +        val = cpu_to_le32(crc32(0, buf, size));
   20.39  #else
   20.40          val = 0;
   20.41  #endif
    21.1 --- a/tools/ioemu/keymaps.c	Thu Jul 26 14:35:01 2007 -0600
    21.2 +++ b/tools/ioemu/keymaps.c	Fri Jul 27 08:15:16 2007 -0600
    21.3 @@ -49,6 +49,7 @@ typedef struct {
    21.4      int extra_count;
    21.5      struct key_range *keypad_range;
    21.6      struct key_range *numlock_range;
    21.7 +    struct key_range *shift_range;
    21.8  } kbd_layout_t;
    21.9  
   21.10  static void add_to_key_range(struct key_range **krp, int code) {
   21.11 @@ -127,6 +128,10 @@ static kbd_layout_t *parse_keyboard_layo
   21.12  			add_to_key_range(&k->numlock_range, keysym);
   21.13  			fprintf(stderr, "keypad keysym %04x keycode %d\n", keysym, keycode);
   21.14  		    }
   21.15 +		    if (rest && strstr(rest, "shift")) {
   21.16 +			add_to_key_range(&k->shift_range, keysym);
   21.17 +			fprintf(stderr, "shift keysym %04x keycode %d\n", keysym, keycode);
   21.18 +		    }
   21.19  
   21.20  		    /* if(keycode&0x80)
   21.21  		       keycode=(keycode<<8)^0x80e0; */
   21.22 @@ -205,3 +210,14 @@ static int keysymIsNumlock(void *kbd_lay
   21.23  	    return 1;
   21.24      return 0;
   21.25  }
   21.26 +
   21.27 +static int keysymIsShift(void *kbd_layout, int keysym)
   21.28 +{
   21.29 +    kbd_layout_t *k = kbd_layout;
   21.30 +    struct key_range *kr;
   21.31 +
   21.32 +    for (kr = k->shift_range; kr; kr = kr->next)
   21.33 +	if (keysym >= kr->start && keysym <= kr->end)
   21.34 +	    return 1;
   21.35 +    return 0;
   21.36 +}
    22.1 --- a/tools/ioemu/target-i386-dm/exec-dm.c	Thu Jul 26 14:35:01 2007 -0600
    22.2 +++ b/tools/ioemu/target-i386-dm/exec-dm.c	Fri Jul 27 08:15:16 2007 -0600
    22.3 @@ -446,18 +446,16 @@ extern unsigned long logdirty_bitmap_siz
    22.4  #if defined(__x86_64__) || defined(__i386__)
    22.5  static void memcpy_words(void *dst, void *src, size_t n)
    22.6  {
    22.7 -    asm (
    22.8 +    asm volatile (
    22.9          "   movl %%edx,%%ecx \n"
   22.10  #ifdef __x86_64__
   22.11          "   shrl $3,%%ecx    \n"
   22.12 -        "   andl $7,%%edx    \n"
   22.13          "   rep  movsq       \n"
   22.14          "   test $4,%%edx    \n"
   22.15          "   jz   1f          \n"
   22.16          "   movsl            \n"
   22.17  #else /* __i386__ */
   22.18          "   shrl $2,%%ecx    \n"
   22.19 -        "   andl $3,%%edx    \n"
   22.20          "   rep  movsl       \n"
   22.21  #endif
   22.22          "1: test $2,%%edx    \n"
   22.23 @@ -467,7 +465,7 @@ static void memcpy_words(void *dst, void
   22.24          "   jz   1f          \n"
   22.25          "   movsb            \n"
   22.26          "1:                  \n"
   22.27 -        : : "S" (src), "D" (dst), "d" (n) : "ecx" );
   22.28 +        : "+S" (src), "+D" (dst) : "d" (n) : "ecx", "memory" );
   22.29  }
   22.30  #else
   22.31  static void memcpy_words(void *dst, void *src, size_t n)
    23.1 --- a/tools/ioemu/target-i386-dm/helper2.c	Thu Jul 26 14:35:01 2007 -0600
    23.2 +++ b/tools/ioemu/target-i386-dm/helper2.c	Fri Jul 27 08:15:16 2007 -0600
    23.3 @@ -618,6 +618,7 @@ int main_loop(void)
    23.4      CPUState *env = cpu_single_env;
    23.5      int evtchn_fd = xc_evtchn_fd(xce_handle);
    23.6      char qemu_file[PATH_MAX];
    23.7 +    fd_set fds;
    23.8  
    23.9      buffered_io_timer = qemu_new_timer(rt_clock, handle_buffered_io,
   23.10  				       cpu_single_env);
   23.11 @@ -625,19 +626,35 @@ int main_loop(void)
   23.12  
   23.13      qemu_set_fd_handler(evtchn_fd, cpu_handle_ioreq, NULL, env);
   23.14  
   23.15 -    while (!(vm_running && suspend_requested))
   23.16 -        /* Wait up to 10 msec. */
   23.17 -        main_loop_wait(10);
   23.18 +    xenstore_record_dm_state("running");
   23.19 +    while (1) {
   23.20 +        while (!(vm_running && suspend_requested))
   23.21 +            /* Wait up to 10 msec. */
   23.22 +            main_loop_wait(10);
   23.23  
   23.24 -    fprintf(logfile, "device model received suspend signal!\n");
   23.25 +        fprintf(logfile, "device model saving state\n");
   23.26 +
   23.27 +        /* Pull all outstanding ioreqs through the system */
   23.28 +        handle_buffered_io(env);
   23.29 +        main_loop_wait(1); /* For the select() on events */
   23.30  
   23.31 -    /* Pull all outstanding ioreqs through the system */
   23.32 -    handle_buffered_io(env);
   23.33 -    main_loop_wait(1); /* For the select() on events */
   23.34 +        /* Save the device state */
   23.35 +        snprintf(qemu_file, sizeof(qemu_file), 
   23.36 +                 "/var/lib/xen/qemu-save.%d", domid);
   23.37 +        do_savevm(qemu_file);
   23.38 +
   23.39 +        xenstore_record_dm_state("paused");
   23.40  
   23.41 -    /* Save the device state */
   23.42 -    snprintf(qemu_file, sizeof(qemu_file), "/var/lib/xen/qemu-save.%d", domid);
   23.43 -    do_savevm(qemu_file);
   23.44 +        /* Wait to be allowed to continue */
   23.45 +        while (suspend_requested) {
   23.46 +            FD_ZERO(&fds);
   23.47 +            FD_SET(xenstore_fd(), &fds);
   23.48 +            if (select(xenstore_fd() + 1, &fds, NULL, NULL, NULL) > 0)
   23.49 +                xenstore_process_event(NULL);
   23.50 +        }
   23.51 +
   23.52 +        xenstore_record_dm_state("running");
   23.53 +    }
   23.54  
   23.55      return 0;
   23.56  }
    24.1 --- a/tools/ioemu/vl.c	Thu Jul 26 14:35:01 2007 -0600
    24.2 +++ b/tools/ioemu/vl.c	Fri Jul 27 08:15:16 2007 -0600
    24.3 @@ -6856,15 +6856,6 @@ int set_mm_mapping(int xc_handle, uint32
    24.4      return 0;
    24.5  }
    24.6  
    24.7 -void suspend(int sig)
    24.8 -{
    24.9 -    fprintf(logfile, "suspend sig handler called with requested=%d!\n",
   24.10 -            suspend_requested);
   24.11 -    if (sig != SIGUSR1)
   24.12 -        fprintf(logfile, "suspend signal dismatch, get sig=%d!\n", sig);
   24.13 -    suspend_requested = 1;
   24.14 -}
   24.15 -
   24.16  #if defined(MAPCACHE)
   24.17  
   24.18  #if defined(__i386__) 
   24.19 @@ -7057,6 +7048,7 @@ int main(int argc, char **argv)
   24.20      xen_pfn_t *page_array;
   24.21      extern void *buffered_pio_page;
   24.22  #endif
   24.23 +    sigset_t set;
   24.24  
   24.25      char qemu_dm_logfilename[128];
   24.26      
   24.27 @@ -7141,13 +7133,8 @@ int main(int argc, char **argv)
   24.28          serial_devices[i][0] = '\0';
   24.29      serial_device_index = 0;
   24.30  
   24.31 -#ifndef CONFIG_DM
   24.32      pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
   24.33      for(i = 1; i < MAX_PARALLEL_PORTS; i++)
   24.34 -#else
   24.35 -    /* Xen steals IRQ7 for PCI. Disable LPT1 by default. */
   24.36 -    for(i = 0; i < MAX_PARALLEL_PORTS; i++)
   24.37 -#endif
   24.38          parallel_devices[i][0] = '\0';
   24.39      parallel_device_index = 0;
   24.40      
   24.41 @@ -7987,24 +7974,11 @@ int main(int argc, char **argv)
   24.42  	close(fd);
   24.43      }
   24.44  
   24.45 -    /* register signal for the suspend request when save */
   24.46 -    {
   24.47 -        struct sigaction act;
   24.48 -        sigset_t set;
   24.49 -        act.sa_handler = suspend;
   24.50 -        act.sa_flags = SA_RESTART;
   24.51 -        sigemptyset(&act.sa_mask);
   24.52 -
   24.53 -        sigaction(SIGUSR1, &act, NULL);
   24.54 -
   24.55 -        /* control panel mask some signals when spawn qemu, need unmask here*/
   24.56 -        sigemptyset(&set);
   24.57 -        sigaddset(&set, SIGUSR1);
   24.58 -        sigaddset(&set, SIGTERM);
   24.59 -        if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
   24.60 -            fprintf(stderr, "unblock signal fail, possible issue for HVM save!\n");
   24.61 -
   24.62 -    }
   24.63 +    /* Unblock SIGTERM, which may have been blocked by the caller */
   24.64 +    sigemptyset(&set);
   24.65 +    sigaddset(&set, SIGTERM);
   24.66 +    if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
   24.67 +        fprintf(stderr, "Failed to unblock SIGTERM\n");
   24.68  
   24.69      main_loop();
   24.70      quit_timers();
    25.1 --- a/tools/ioemu/vl.h	Thu Jul 26 14:35:01 2007 -0600
    25.2 +++ b/tools/ioemu/vl.h	Fri Jul 27 08:15:16 2007 -0600
    25.3 @@ -1456,6 +1456,7 @@ void readline_start(const char *prompt, 
    25.4  void xenstore_parse_domain_config(int domid);
    25.5  int xenstore_fd(void);
    25.6  void xenstore_process_event(void *opaque);
    25.7 +void xenstore_record_dm_state(char *state);
    25.8  void xenstore_check_new_media_present(int timeout);
    25.9  void xenstore_write_vncport(int vnc_display);
   25.10  int xenstore_read_vncpasswd(int domid);
    26.1 --- a/tools/ioemu/vnc.c	Thu Jul 26 14:35:01 2007 -0600
    26.2 +++ b/tools/ioemu/vnc.c	Fri Jul 27 08:15:16 2007 -0600
    26.3 @@ -915,12 +915,69 @@ static void press_key(VncState *vs, int 
    26.4      kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) | 0x80);
    26.5  }
    26.6  
    26.7 +static void press_key_shift_down(VncState *vs, int down, int keycode)
    26.8 +{
    26.9 +    if (down)
   26.10 +        kbd_put_keycode(0x2a & 0x7f);
   26.11 +
   26.12 +    if (keycode & 0x80)
   26.13 +        kbd_put_keycode(0xe0);
   26.14 +    if (down)
   26.15 +        kbd_put_keycode(keycode & 0x7f);
   26.16 +    else
   26.17 +        kbd_put_keycode(keycode | 0x80);
   26.18 +
   26.19 +    if (!down)
   26.20 +        kbd_put_keycode(0x2a | 0x80);
   26.21 +}
   26.22 +
   26.23 +static void press_key_shift_up(VncState *vs, int down, int keycode)
   26.24 +{
   26.25 +    if (down) {
   26.26 +        if (vs->modifiers_state[0x2a])
   26.27 +            kbd_put_keycode(0x2a | 0x80);
   26.28 +        if (vs->modifiers_state[0x36]) 
   26.29 +            kbd_put_keycode(0x36 | 0x80);
   26.30 +    }
   26.31 +
   26.32 +    if (keycode & 0x80)
   26.33 +        kbd_put_keycode(0xe0);
   26.34 +    if (down)
   26.35 +        kbd_put_keycode(keycode & 0x7f);
   26.36 +    else
   26.37 +        kbd_put_keycode(keycode | 0x80);
   26.38 +
   26.39 +    if (!down) {
   26.40 +        if (vs->modifiers_state[0x2a])
   26.41 +            kbd_put_keycode(0x2a & 0x7f);
   26.42 +        if (vs->modifiers_state[0x36]) 
   26.43 +            kbd_put_keycode(0x36 & 0x7f);
   26.44 +    }
   26.45 +}
   26.46 +
   26.47  static void do_key_event(VncState *vs, int down, uint32_t sym)
   26.48  {
   26.49      int keycode;
   26.50 +    int shift_keys = 0;
   26.51 +    int shift = 0;
   26.52 +
   26.53 +    if (is_graphic_console()) {
   26.54 +        if (sym >= 'A' && sym <= 'Z') {
   26.55 +            sym = sym - 'A' + 'a';
   26.56 +            shift = 1;
   26.57 +        }
   26.58 +        else {
   26.59 +            shift = keysymIsShift(vs->kbd_layout, sym & 0xFFFF);
   26.60 +        }
   26.61 +    }
   26.62 +    shift_keys = vs->modifiers_state[0x2a] | vs->modifiers_state[0x36];
   26.63  
   26.64      keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
   26.65 -    
   26.66 +    if (keycode == 0) {
   26.67 +        fprintf(stderr, "Key lost : keysym=0x%x(%d)\n", sym, sym);
   26.68 +        return;
   26.69 +    }
   26.70 +
   26.71      /* QEMU console switch */
   26.72      switch(keycode) {
   26.73      case 0x2a:                          /* Left Shift */
   26.74 @@ -929,11 +986,15 @@ static void do_key_event(VncState *vs, i
   26.75      case 0x9d:                          /* Right CTRL */
   26.76      case 0x38:                          /* Left ALT */
   26.77      case 0xb8:                          /* Right ALT */
   26.78 -        if (down)
   26.79 +        if (down) {
   26.80              vs->modifiers_state[keycode] = 1;
   26.81 -        else
   26.82 +            kbd_put_keycode(keycode & 0x7f);
   26.83 +        }
   26.84 +        else {
   26.85              vs->modifiers_state[keycode] = 0;
   26.86 -        break;
   26.87 +            kbd_put_keycode(keycode | 0x80);
   26.88 +        }
   26.89 +        return;
   26.90      case 0x02 ... 0x0a: /* '1' to '9' keys */ 
   26.91          if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
   26.92              /* Reset the modifiers sent to the current console */
   26.93 @@ -943,9 +1004,14 @@ static void do_key_event(VncState *vs, i
   26.94          }
   26.95          break;
   26.96      case 0x45:			/* NumLock */
   26.97 -	if (!down)
   26.98 +	if (down) {
   26.99 +            kbd_put_keycode(keycode & 0x7f);
  26.100 +        }
  26.101 +        else {	
  26.102  	    vs->modifiers_state[keycode] ^= 1;
  26.103 -	break;
  26.104 +            kbd_put_keycode(keycode | 0x80);
  26.105 +        }
  26.106 +	return;
  26.107      }
  26.108  
  26.109      if (keycodeIsKeypad(vs->kbd_layout, keycode)) {
  26.110 @@ -967,6 +1033,18 @@ static void do_key_event(VncState *vs, i
  26.111      }
  26.112  
  26.113      if (is_graphic_console()) {
  26.114 +        /*  If the shift state needs to change then simulate an additional
  26.115 +            keypress before sending this one.
  26.116 +        */
  26.117 +        if (shift && !shift_keys) {
  26.118 +            press_key_shift_down(vs, down, keycode);
  26.119 +            return;
  26.120 +        }
  26.121 +        else if (!shift && shift_keys) {
  26.122 +            press_key_shift_up(vs, down, keycode);
  26.123 +            return;
  26.124 +        }
  26.125 +
  26.126          if (keycode & 0x80)
  26.127              kbd_put_keycode(0xe0);
  26.128          if (down)
  26.129 @@ -1021,8 +1099,6 @@ static void do_key_event(VncState *vs, i
  26.130  
  26.131  static void key_event(VncState *vs, int down, uint32_t sym)
  26.132  {
  26.133 -    if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
  26.134 -	sym = sym - 'A' + 'a';
  26.135      do_key_event(vs, down, sym);
  26.136  }
  26.137  
    27.1 --- a/tools/ioemu/xenstore.c	Thu Jul 26 14:35:01 2007 -0600
    27.2 +++ b/tools/ioemu/xenstore.c	Fri Jul 27 08:15:16 2007 -0600
    27.3 @@ -181,11 +181,18 @@ void xenstore_parse_domain_config(int do
    27.4      }
    27.5  
    27.6      /* Set a watch for log-dirty requests from the migration tools */
    27.7 -    if (pasprintf(&buf, "%s/logdirty/next-active", path) != -1) {
    27.8 +    if (pasprintf(&buf, "/local/domain/0/device-model/%u/logdirty/next-active",
    27.9 +                  domid) != -1) {
   27.10          xs_watch(xsh, buf, "logdirty");
   27.11          fprintf(logfile, "Watching %s\n", buf);
   27.12      }
   27.13  
   27.14 +    /* Set a watch for suspend requests from the migration tools */
   27.15 +    if (pasprintf(&buf, 
   27.16 +                  "/local/domain/0/device-model/%u/command", domid) != -1) {
   27.17 +        xs_watch(xsh, buf, "dm-command");
   27.18 +        fprintf(logfile, "Watching %s\n", buf);
   27.19 +    }
   27.20  
   27.21   out:
   27.22      free(type);
   27.23 @@ -218,33 +225,26 @@ void xenstore_process_logdirty_event(voi
   27.24      unsigned int len;
   27.25      int i;
   27.26  
   27.27 -    fprintf(logfile, "Triggered log-dirty buffer switch\n");
   27.28 -
   27.29      if (!seg) {
   27.30 -        char *path, *p, *key_ascii, key_terminated[17] = {0,};
   27.31 +        char *path = NULL, *key_ascii, key_terminated[17] = {0,};
   27.32          key_t key;
   27.33          int shmid;
   27.34  
   27.35          /* Find and map the shared memory segment for log-dirty bitmaps */
   27.36 -        if (!(path = xs_get_domain_path(xsh, domid))) {            
   27.37 -            fprintf(logfile, "Log-dirty: can't get domain path in store\n");
   27.38 -            exit(1);
   27.39 -        }
   27.40 -        if (!(path = realloc(path, strlen(path) 
   27.41 -                             + strlen("/logdirty/next-active") + 1))) {
   27.42 +        if (pasprintf(&path, 
   27.43 +                      "/local/domain/0/device-model/%u/logdirty/key", 
   27.44 +                      domid) == -1) {
   27.45              fprintf(logfile, "Log-dirty: out of memory\n");
   27.46              exit(1);
   27.47          }
   27.48 -        strcat(path, "/logdirty/");
   27.49 -        p = path + strlen(path);
   27.50 -        strcpy(p, "key");
   27.51          
   27.52          key_ascii = xs_read(xsh, XBT_NULL, path, &len);
   27.53 -        if (!key_ascii) {
   27.54 +        free(path);
   27.55 +
   27.56 +        if (!key_ascii) 
   27.57              /* No key yet: wait for the next watch */
   27.58 -            free(path);
   27.59              return;
   27.60 -        }
   27.61 +
   27.62          strncpy(key_terminated, key_ascii, 16);
   27.63          free(key_ascii);
   27.64          key = (key_t) strtoull(key_terminated, NULL, 16);
   27.65 @@ -276,18 +276,21 @@ void xenstore_process_logdirty_event(voi
   27.66          }
   27.67  
   27.68          /* Remember the paths for the next-active and active entries */
   27.69 -        strcpy(p, "active");
   27.70 -        if (!(active_path = strdup(path))) {
   27.71 +        if (pasprintf(&active_path, 
   27.72 +                      "/local/domain/0/device-model/%u/logdirty/active",
   27.73 +                      domid) == -1) {
   27.74              fprintf(logfile, "Log-dirty: out of memory\n");
   27.75              exit(1);
   27.76          }
   27.77 -        strcpy(p, "next-active");
   27.78 -        if (!(next_active_path = strdup(path))) {
   27.79 +        if (pasprintf(&next_active_path, 
   27.80 +                      "/local/domain/0/device-model/%u/logdirty/next-active",
   27.81 +                      domid) == -1) {
   27.82              fprintf(logfile, "Log-dirty: out of memory\n");
   27.83              exit(1);
   27.84          }
   27.85 -        free(path);
   27.86      }
   27.87 +
   27.88 +    fprintf(logfile, "Triggered log-dirty buffer switch\n");
   27.89      
   27.90      /* Read the required active buffer from the store */
   27.91      act = xs_read(xsh, XBT_NULL, next_active_path, &len);
   27.92 @@ -310,6 +313,52 @@ void xenstore_process_logdirty_event(voi
   27.93  }
   27.94  
   27.95  
   27.96 +/* Accept state change commands from the control tools */
   27.97 +static void xenstore_process_dm_command_event(void)
   27.98 +{
   27.99 +    char *path = NULL, *command = NULL;
  27.100 +    unsigned int len;
  27.101 +    extern int suspend_requested;
  27.102 +
  27.103 +    if (pasprintf(&path, 
  27.104 +                  "/local/domain/0/device-model/%u/command", domid) == -1) {
  27.105 +        fprintf(logfile, "out of memory reading dm command\n");
  27.106 +        goto out;
  27.107 +    }
  27.108 +    command = xs_read(xsh, XBT_NULL, path, &len);
  27.109 +    if (!command)
  27.110 +        goto out;
  27.111 +    
  27.112 +    if (!strncmp(command, "save", len)) {
  27.113 +        fprintf(logfile, "dm-command: pause and save state\n");
  27.114 +        suspend_requested = 1;
  27.115 +    } else if (!strncmp(command, "continue", len)) {
  27.116 +        fprintf(logfile, "dm-command: continue after state save\n");
  27.117 +        suspend_requested = 0;
  27.118 +    } else {
  27.119 +        fprintf(logfile, "dm-command: unknown command\"%*s\"\n", len, command);
  27.120 +    }
  27.121 +
  27.122 + out:
  27.123 +    free(path);
  27.124 +    free(command);
  27.125 +}
  27.126 +
  27.127 +void xenstore_record_dm_state(char *state)
  27.128 +{
  27.129 +    char *path = NULL;
  27.130 +
  27.131 +    if (pasprintf(&path, 
  27.132 +                  "/local/domain/0/device-model/%u/state", domid) == -1) {
  27.133 +        fprintf(logfile, "out of memory recording dm state\n");
  27.134 +        goto out;
  27.135 +    }
  27.136 +    if (!xs_write(xsh, XBT_NULL, path, state, strlen(state)))
  27.137 +        fprintf(logfile, "error recording dm state\n");
  27.138 +
  27.139 + out:
  27.140 +    free(path);
  27.141 +}
  27.142  
  27.143  void xenstore_process_event(void *opaque)
  27.144  {
  27.145 @@ -325,6 +374,11 @@ void xenstore_process_event(void *opaque
  27.146          goto out;
  27.147      }
  27.148  
  27.149 +    if (!strcmp(vec[XS_WATCH_TOKEN], "dm-command")) {
  27.150 +        xenstore_process_dm_command_event();
  27.151 +        goto out;
  27.152 +    }
  27.153 +
  27.154      if (strncmp(vec[XS_WATCH_TOKEN], "hd", 2) ||
  27.155          strlen(vec[XS_WATCH_TOKEN]) != 3)
  27.156          goto out;
    28.1 --- a/tools/libxc/xc_domain.c	Thu Jul 26 14:35:01 2007 -0600
    28.2 +++ b/tools/libxc/xc_domain.c	Fri Jul 27 08:15:16 2007 -0600
    28.3 @@ -588,6 +588,27 @@ int xc_domain_ioport_permission(int xc_h
    28.4      return do_domctl(xc_handle, &domctl);
    28.5  }
    28.6  
    28.7 +int xc_availheap(int xc_handle,
    28.8 +                 int min_width,
    28.9 +                 int max_width,
   28.10 +                 int node,
   28.11 +                 uint64_t *bytes)
   28.12 +{
   28.13 +    DECLARE_SYSCTL;
   28.14 +    int rc;
   28.15 +
   28.16 +    sysctl.cmd = XEN_SYSCTL_availheap;
   28.17 +    sysctl.u.availheap.min_bitwidth = min_width;
   28.18 +    sysctl.u.availheap.max_bitwidth = max_width;
   28.19 +    sysctl.u.availheap.node = node;
   28.20 +
   28.21 +    rc = xc_sysctl(xc_handle, &sysctl);
   28.22 +
   28.23 +    *bytes = sysctl.u.availheap.avail_bytes;
   28.24 +
   28.25 +    return rc;
   28.26 +}
   28.27 +
   28.28  int xc_vcpu_setcontext(int xc_handle,
   28.29                         uint32_t domid,
   28.30                         uint32_t vcpu,
    29.1 --- a/tools/libxc/xc_linux.c	Thu Jul 26 14:35:01 2007 -0600
    29.2 +++ b/tools/libxc/xc_linux.c	Fri Jul 27 08:15:16 2007 -0600
    29.3 @@ -456,7 +456,7 @@ void *xc_gnttab_map_grant_refs(int xcg_h
    29.4  
    29.5      map->count = count;
    29.6      
    29.7 -    if ( ioctl(xcg_handle, IOCTL_GNTDEV_MAP_GRANT_REF, &map) )
    29.8 +    if ( ioctl(xcg_handle, IOCTL_GNTDEV_MAP_GRANT_REF, map) )
    29.9          goto out;
   29.10  
   29.11      addr = mmap(NULL, PAGE_SIZE * count, prot, MAP_SHARED, xcg_handle,
    30.1 --- a/tools/libxc/xenctrl.h	Thu Jul 26 14:35:01 2007 -0600
    30.2 +++ b/tools/libxc/xenctrl.h	Fri Jul 27 08:15:16 2007 -0600
    30.3 @@ -628,6 +628,20 @@ int xc_get_pfn_type_batch(int xc_handle,
    30.4  /* Get current total pages allocated to a domain. */
    30.5  long xc_get_tot_pages(int xc_handle, uint32_t domid);
    30.6  
    30.7 +/**
    30.8 + * This function retrieves the the number of bytes available
    30.9 + * in the heap in a specific range of address-widths and nodes.
   30.10 + * 
   30.11 + * @parm xc_handle a handle to an open hypervisor interface
   30.12 + * @parm domid the domain to query
   30.13 + * @parm min_width the smallest address width to query (0 if don't care)
   30.14 + * @parm max_width the largest address width to query (0 if don't care)
   30.15 + * @parm node the node to query (-1 for all)
   30.16 + * @parm *bytes caller variable to put total bytes counted
   30.17 + * @return 0 on success, <0 on failure.
   30.18 + */
   30.19 +int xc_availheap(int xc_handle, int min_width, int max_width, int node,
   30.20 +                 uint64_t *bytes);
   30.21  
   30.22  /*
   30.23   * Trace Buffer Operations
    31.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    31.2 +++ b/tools/libxen/include/xen/api/xen_acmpolicy.h	Fri Jul 27 08:15:16 2007 -0600
    31.3 @@ -0,0 +1,117 @@
    31.4 +/*
    31.5 + * Copyright (c) 2007, IBM Corp.
    31.6 + * Copyright (c) 2007, XenSource Inc.
    31.7 + *
    31.8 + * This library is free software; you can redistribute it and/or
    31.9 + * modify it under the terms of the GNU Lesser General Public
   31.10 + * License as published by the Free Software Foundation; either
   31.11 + * version 2.1 of the License, or (at your option) any later version.
   31.12 + *
   31.13 + * This library is distributed in the hope that it will be useful,
   31.14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
   31.15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   31.16 + * Lesser General Public License for more details.
   31.17 + *
   31.18 + * You should have received a copy of the GNU Lesser General Public
   31.19 + * License along with this library; if not, write to the Free Software
   31.20 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
   31.21 + */
   31.22 +
   31.23 +#ifndef XEN_ACMPOLICY_H
   31.24 +#define XEN_ACMPOLICY_H
   31.25 +
   31.26 +#include "xen_common.h"
   31.27 +#include "xen_string_string_map.h"
   31.28 +#include "xen_xspolicy_decl.h"
   31.29 +#include "xen_vm_decl.h"
   31.30 +
   31.31 +/*
   31.32 + * Data structures.
   31.33 + */
   31.34 +
   31.35 +typedef struct xen_acmpolicy_record
   31.36 +{
   31.37 +    xen_xspolicy handle;
   31.38 +    char *uuid;
   31.39 +    char *repr;
   31.40 +    xs_instantiationflags flags;
   31.41 +    xs_type type;
   31.42 +} xen_acmpolicy_record;
   31.43 +
   31.44 +/**
   31.45 + * Allocate a xen_acmpolicy_record.
   31.46 + */
   31.47 +extern xen_acmpolicy_record *
   31.48 +xen_acmpolicy_record_alloc(void);
   31.49 +
   31.50 +/**
   31.51 + * Free the given xen_xspolicy_record, and all referenced values.  The
   31.52 + * given record must have been allocated by this library.
   31.53 + */
   31.54 +extern void
   31.55 +xen_acmpolicy_record_free(xen_acmpolicy_record *record);
   31.56 +
   31.57 +
   31.58 +/**
   31.59 + * Data structures for the policy's header
   31.60 + */
   31.61 +typedef struct xen_acm_header
   31.62 +{
   31.63 +    char *policyname;
   31.64 +    char *policyurl;
   31.65 +    char *date;
   31.66 +    char *reference;
   31.67 +    char *namespaceurl;
   31.68 +    char *version;
   31.69 +} xen_acm_header;
   31.70 +
   31.71 +extern xen_acm_header *
   31.72 +xen_acm_header_alloc(void);
   31.73 +
   31.74 +extern void
   31.75 +xen_acm_header_free(xen_acm_header *hdr);
   31.76 +
   31.77 +/**
   31.78 + * Get the referenced policy's record.
   31.79 + */
   31.80 +bool
   31.81 +xen_acmpolicy_get_record(xen_session *session, xen_acmpolicy_record **result,
   31.82 +                         xen_xspolicy xspolicy);
   31.83 +
   31.84 +/**
   31.85 + * Get the header of a  policy.
   31.86 + */
   31.87 +extern bool
   31.88 +xen_acmpolicy_get_header(xen_session *session, xen_acm_header **hdr,
   31.89 +                         xen_xspolicy xspolicy);
   31.90 +
   31.91 +
   31.92 +/**
   31.93 + * Get the XML representation of the policy.
   31.94 + */
   31.95 +extern bool
   31.96 +xen_acmpolicy_get_xml(xen_session *session, char **xml,
   31.97 +                      xen_xspolicy xspolicy);
   31.98 +
   31.99 +/**
  31.100 + * Get the mapping file of the policy.
  31.101 + */
  31.102 +extern bool
  31.103 +xen_acmpolicy_get_map(xen_session *session, char **map,
  31.104 +                      xen_xspolicy xspolicy);
  31.105 +
  31.106 +/**
  31.107 + * Get the binary representation (base64-encoded) of the policy.
  31.108 + */
  31.109 +extern bool
  31.110 +xen_acmpolicy_get_binary(xen_session *session, char **binary,
  31.111 +                         xen_xspolicy xspolicy);
  31.112 +
  31.113 +/**
  31.114 + * Get the UUID filed of the given policy.
  31.115 + */
  31.116 +bool
  31.117 +xen_acmpolicy_get_uuid(xen_session *session, char **result,
  31.118 +                       xen_xspolicy xspolicy);
  31.119 +
  31.120 +#endif
    32.1 --- a/tools/libxen/include/xen/api/xen_vdi.h	Thu Jul 26 14:35:01 2007 -0600
    32.2 +++ b/tools/libxen/include/xen/api/xen_vdi.h	Fri Jul 27 08:15:16 2007 -0600
    32.3 @@ -344,4 +344,17 @@ extern bool
    32.4  xen_vdi_get_all(xen_session *session, struct xen_vdi_set **result);
    32.5  
    32.6  
    32.7 +/**
    32.8 + * Set the security label of a VDI.
    32.9 + */
   32.10 +extern bool
   32.11 +xen_vdi_set_security_label(xen_session *session, int64_t *result, xen_vdi vdi,
   32.12 +                           char *label, char *oldlabel);
   32.13 +
   32.14 +/**
   32.15 + * Get the security label of a VDI.
   32.16 + */
   32.17 +extern bool
   32.18 +xen_vdi_get_security_label(xen_session *session, char **result, xen_vdi vdi);
   32.19 +
   32.20  #endif
    33.1 --- a/tools/libxen/include/xen/api/xen_vif.h	Thu Jul 26 14:35:01 2007 -0600
    33.2 +++ b/tools/libxen/include/xen/api/xen_vif.h	Fri Jul 27 08:15:16 2007 -0600
    33.3 @@ -362,4 +362,18 @@ extern bool
    33.4  xen_vif_get_all(xen_session *session, struct xen_vif_set **result);
    33.5  
    33.6  
    33.7 +/**
    33.8 + * Set the security label of a VIF.
    33.9 + */
   33.10 +extern bool
   33.11 +xen_vif_set_security_label(xen_session *session, int64_t *result, xen_vif vif,
   33.12 +                           char *label, char *oldlabel);
   33.13 +
   33.14 +
   33.15 +/**
   33.16 + * Get the security label of a VIF.
   33.17 + */
   33.18 +extern bool
   33.19 +xen_vif_get_security_label(xen_session *session, char **result, xen_vif vif);
   33.20 +
   33.21  #endif
    34.1 --- a/tools/libxen/include/xen/api/xen_vm.h	Thu Jul 26 14:35:01 2007 -0600
    34.2 +++ b/tools/libxen/include/xen/api/xen_vm.h	Fri Jul 27 08:15:16 2007 -0600
    34.3 @@ -112,6 +112,7 @@ typedef struct xen_vm_record
    34.4      bool is_control_domain;
    34.5      struct xen_vm_metrics_record_opt *metrics;
    34.6      struct xen_vm_guest_metrics_record_opt *guest_metrics;
    34.7 +    char *security_label;
    34.8  } xen_vm_record;
    34.9  
   34.10  /**
   34.11 @@ -891,4 +892,17 @@ extern bool
   34.12  xen_vm_get_all(xen_session *session, struct xen_vm_set **result);
   34.13  
   34.14  
   34.15 +/**
   34.16 + * Set the security label of a domain.
   34.17 + */
   34.18 +extern bool
   34.19 +xen_vm_set_security_label(xen_session *session, int64_t *result, xen_vm vm,
   34.20 +                          char *label, char *oldlabel);
   34.21 +
   34.22 +/**
   34.23 + * Get the security label of a domain.
   34.24 + */
   34.25 +extern bool
   34.26 +xen_vm_get_security_label(xen_session *session, char **result, xen_vm vm);
   34.27 +
   34.28  #endif
    35.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    35.2 +++ b/tools/libxen/include/xen/api/xen_xspolicy.h	Fri Jul 27 08:15:16 2007 -0600
    35.3 @@ -0,0 +1,271 @@
    35.4 +/*
    35.5 + * Copyright (c) 2007, IBM Corp.
    35.6 + * Copyright (c) 2007, XenSource Inc.
    35.7 + *
    35.8 + * This library is free software; you can redistribute it and/or
    35.9 + * modify it under the terms of the GNU Lesser General Public
   35.10 + * License as published by the Free Software Foundation; either
   35.11 + * version 2.1 of the License, or (at your option) any later version.
   35.12 + *
   35.13 + * This library is distributed in the hope that it will be useful,
   35.14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
   35.15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   35.16 + * Lesser General Public License for more details.
   35.17 + *
   35.18 + * You should have received a copy of the GNU Lesser General Public
   35.19 + * License along with this library; if not, write to the Free Software
   35.20 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
   35.21 + */
   35.22 +
   35.23 +#ifndef XEN_XSPOLICY_H
   35.24 +#define XEN_XSPOLICY_H
   35.25 +
   35.26 +#include "xen_common.h"
   35.27 +#include "xen_xspolicy_decl.h"
   35.28 +#include "xen_string_string_map.h"
   35.29 +
   35.30 +
   35.31 +/*
   35.32 + * The XSPolicy and associated data structures.
   35.33 + *
   35.34 + */
   35.35 +typedef int64_t xs_type;
   35.36 +typedef int64_t xs_instantiationflags;
   35.37 +
   35.38 +enum xs_type {
   35.39 +    XS_POLICY_ACM = (1 << 0),
   35.40 +};
   35.41 +
   35.42 +enum xs_instantiationflags {
   35.43 +    XS_INST_NONE = 0,
   35.44 +    XS_INST_BOOT = (1 << 0),
   35.45 +    XS_INST_LOAD = (1 << 1),
   35.46 +};
   35.47 +
   35.48 +
   35.49 +/* Error codes returned by xend following XSPolicy operations */
   35.50 +#define XSERR_BASE                       0x1000
   35.51 +
   35.52 +#define XSERR_SUCCESS                    0
   35.53 +#define XSERR_GENERAL_FAILURE            1 + XSERR_BASE
   35.54 +#define XSERR_BAD_XML                    2 + XSERR_BASE
   35.55 +#define XSERR_XML_PROCESSING             3 + XSERR_BASE
   35.56 +#define XSERR_POLICY_INCONSISTENT        4 + XSERR_BASE
   35.57 +#define XSERR_FILE_ERROR                 5 + XSERR_BASE
   35.58 +#define XSERR_BAD_RESOURCE_FORMAT        6 + XSERR_BASE
   35.59 +#define XSERR_BAD_LABEL_FORMAT           7 + XSERR_BASE
   35.60 +#define XSERR_RESOURCE_NOT_LABELED       8 + XSERR_BASE
   35.61 +#define XSERR_RESOURCE_ALREADY_LABELED   9 + XSERR_BASE
   35.62 +#define XSERR_WRONG_POLICY_TYPE         10 + XSERR_BASE
   35.63 +#define XSERR_BOOTPOLICY_INSTALLED      11 + XSERR_BASE
   35.64 +#define XSERR_NO_DEFAULT_BOOT_TITLE     12 + XSERR_BASE
   35.65 +#define XSERR_POLICY_LOAD_FAILED        13 + XSERR_BASE
   35.66 +#define XSERR_POLICY_LOADED             14 + XSERR_BASE
   35.67 +#define XSERR_POLICY_TYPE_UNSUPPORTED   15 + XSERR_BASE
   35.68 +#define XSERR_BAD_CONFLICTSET           20 + XSERR_BASE
   35.69 +#define XSERR_RESOURCE_IN_USE           21 + XSERR_BASE
   35.70 +#define XSERR_BAD_POLICY_NAME           22 + XSERR_BASE
   35.71 +#define XSERR_RESOURCE_ACCESS           23 + XSERR_BASE
   35.72 +#define XSERR_HV_OP_FAILED              24 + XSERR_BASE
   35.73 +#define XSERR_BOOTPOLICY_INSTALL_ERROR  25 + XSERR_BASE
   35.74 +
   35.75 +
   35.76 +/**
   35.77 + * Free the given xen_xspolicy.  The given handle must have been allocated
   35.78 + * by this library.
   35.79 + */
   35.80 +extern void
   35.81 +xen_xspolicy_free(xen_xspolicy xspolicy);
   35.82 +
   35.83 +
   35.84 +typedef struct xen_xspolicy_set
   35.85 +{
   35.86 +    size_t size;
   35.87 +    xen_xspolicy *contents[];
   35.88 +} xen_xspolicy_set;
   35.89 +
   35.90 +/**
   35.91 + * Allocate a xen_xspolicy_set of the given size.
   35.92 + */
   35.93 +extern xen_xspolicy_set *
   35.94 +xen_xspolicy_set_alloc(size_t size);
   35.95 +
   35.96 +/**
   35.97 + * Free the given xen_xspolicy_set.  The given set must have been allocated
   35.98 + * by this library.
   35.99 + */
  35.100 +extern void
  35.101 +xen_xspolicy_set_free(xen_xspolicy_set *set);
  35.102 +
  35.103 +
  35.104 +typedef struct xen_xspolicy_record
  35.105 +{
  35.106 +    xen_xspolicy handle;
  35.107 +    char *uuid;
  35.108 +    char *repr;
  35.109 +    xs_instantiationflags flags;
  35.110 +    xs_type type;
  35.111 +} xen_xspolicy_record;
  35.112 +
  35.113 +/**
  35.114 + * Allocate a xen_xspolicy_record.
  35.115 + */
  35.116 +extern xen_xspolicy_record *
  35.117 +xen_xspolicy_record_alloc(void);
  35.118 +
  35.119 +/**
  35.120 + * Free the given xen_xspolicy_record, and all referenced values.  The
  35.121 + * given record must have been allocated by this library.
  35.122 + */
  35.123 +extern void
  35.124 +xen_xspolicy_record_free(xen_xspolicy_record *record);
  35.125 +
  35.126 +
  35.127 +typedef struct xen_xspolicy_record_opt
  35.128 +{
  35.129 +    bool is_record;
  35.130 +    union
  35.131 +    {
  35.132 +        xen_xspolicy handle;
  35.133 +        xen_xspolicy_record *record;
  35.134 +    } u;
  35.135 +} xen_xspolicy_record_opt;
  35.136 +
  35.137 +/**
  35.138 + * Allocate a xen_xspolicy_record_opt.
  35.139 + */
  35.140 +extern xen_xspolicy_record_opt *
  35.141 +xen_xspolicy_record_opt_alloc(void);
  35.142 +
  35.143 +/**
  35.144 + * Free the given xen_xspolicy_record_opt, and all referenced values.  The
  35.145 + * given record_opt must have been allocated by this library.
  35.146 + */
  35.147 +extern void
  35.148 +xen_xspolicy_record_opt_free(xen_xspolicy_record_opt *record_opt);
  35.149 +
  35.150 +
  35.151 +typedef struct xen_xspolicy_record_set
  35.152 +{
  35.153 +    size_t size;
  35.154 +    xen_xspolicy_record *contents[];
  35.155 +} xen_xspolicy_record_set;
  35.156 +
  35.157 +/**
  35.158 + * Allocate a xen_xspolicy_record_set of the given size.
  35.159 + */
  35.160 +extern xen_xspolicy_record_set *
  35.161 +xen_xspolicy_record_set_alloc(size_t size);
  35.162 +
  35.163 +/**
  35.164 + * Free the given xen_xspolicy_record_set, and all referenced values.  The
  35.165 + * given set must have been allocated by this library.
  35.166 + */
  35.167 +extern void
  35.168 +xen_xspolicy_record_set_free(xen_xspolicy_record_set *set);
  35.169 +
  35.170 +/**
  35.171 + * Data structures and function declarations for an XS Policy's state
  35.172 + * information.
  35.173 + */
  35.174 +typedef struct xen_xs_policystate
  35.175 +{
  35.176 +    xen_xspolicy_record_opt *xs_ref;
  35.177 +    int64_t xserr;
  35.178 +    char *repr;
  35.179 +    xs_type type;
  35.180 +    xs_instantiationflags flags;
  35.181 +    char *version;
  35.182 +    char *errors;
  35.183 +} xen_xs_policystate;
  35.184 +
  35.185 +void
  35.186 +xen_xs_policystate_free(xen_xs_policystate *state);
  35.187 +
  35.188 +
  35.189 +/**
  35.190 + * Get the referenced policy's record.
  35.191 + */
  35.192 +bool
  35.193 +xen_xspolicy_get_record(xen_session *session, xen_xspolicy_record **result,
  35.194 +                        xen_xspolicy xspolicy);
  35.195 +
  35.196 +/**
  35.197 + * Get the UUID field of the given policy.
  35.198 + */
  35.199 +bool
  35.200 +xen_xspolicy_get_uuid(xen_session *session, char **result,
  35.201 +                      xen_xspolicy xspolicy);
  35.202 +
  35.203 +/**
  35.204 + * Get a policy given it's UUID
  35.205 + */
  35.206 +bool
  35.207 +xen_xspolicy_get_by_uuid(xen_session *session, xen_xspolicy *result,
  35.208 +                         char *uuid);
  35.209 +
  35.210 +
  35.211 +/**
  35.212 + * Get the types of policies supported by the system.
  35.213 + */
  35.214 +bool
  35.215 +xen_xspolicy_get_xstype(xen_session *session, xs_type *result);
  35.216 +
  35.217 +
  35.218 +/**
  35.219 + * Get information about the currently managed policy.
  35.220 + * (The API allows only one policy to be on the system.)
  35.221 + */
  35.222 +bool
  35.223 +xen_xspolicy_get_xspolicy(xen_session *session, xen_xs_policystate **result);
  35.224 +
  35.225 +/**
  35.226 + * Activate the referenced policy by loading it into the hypervisor.
  35.227 + */
  35.228 +bool
  35.229 +xen_xspolicy_activate_xspolicy(xen_session *session, int64_t *result,
  35.230 +                               xen_xspolicy xspolicy,
  35.231 +                               xs_instantiationflags flags);
  35.232 +
  35.233 +
  35.234 +/**
  35.235 + * Set the system's policy to the given information comprising
  35.236 + * type of policy, the xml representation of the policy, some flags
  35.237 + * on whether to load the policy immediately and whether to overwrite
  35.238 + * an existing policy on the system.
  35.239 + */
  35.240 +bool
  35.241 +xen_xspolicy_set_xspolicy(xen_session *session, xen_xs_policystate **result,
  35.242 +                          xs_type type, char *repr, int64_t flags,
  35.243 +                          bool overwrite);
  35.244 +
  35.245 +
  35.246 +/**
  35.247 + * Remove any policy from having the system booted with.
  35.248 + */
  35.249 +extern bool
  35.250 +xen_xspolicy_rm_xsbootpolicy(xen_session *session);
  35.251 +
  35.252 +/**
  35.253 + * Retrieve all labeled resources.
  35.254 + */
  35.255 +extern bool
  35.256 +xen_xspolicy_get_labeled_resources(xen_session *session,
  35.257 +                                   xen_string_string_map **resources);
  35.258 +
  35.259 +/**
  35.260 + * Label a resource such as for example a hard drive partition or file
  35.261 + */
  35.262 +extern bool
  35.263 +xen_xspolicy_set_resource_label(xen_session *session,
  35.264 +                                char *resource, char *label,
  35.265 +                                char *oldlabel);
  35.266 +
  35.267 +/**
  35.268 + * Get the label of a resource.
  35.269 + */
  35.270 +extern bool
  35.271 +xen_xspolicy_get_resource_label(xen_session *session, char **label,
  35.272 +                                char *resource);
  35.273 +
  35.274 +#endif
    36.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    36.2 +++ b/tools/libxen/include/xen/api/xen_xspolicy_decl.h	Fri Jul 27 08:15:16 2007 -0600
    36.3 @@ -0,0 +1,31 @@
    36.4 +/*
    36.5 + * Copyright (c) 2007, IBM Corp.
    36.6 + * Copyright (c) 2007, XenSource Inc.
    36.7 + *
    36.8 + * This library is free software; you can redistribute it and/or
    36.9 + * modify it under the terms of the GNU Lesser General Public
   36.10 + * License as published by the Free Software Foundation; either
   36.11 + * version 2.1 of the License, or (at your option) any later version.
   36.12 + *
   36.13 + * This library is distributed in the hope that it will be useful,
   36.14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
   36.15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   36.16 + * Lesser General Public License for more details.
   36.17 + *
   36.18 + * You should have received a copy of the GNU Lesser General Public
   36.19 + * License along with this library; if not, write to the Free Software
   36.20 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
   36.21 + */
   36.22 +
   36.23 +#ifndef XEN_XSPOLICY_DECL_H
   36.24 +#define XEN_XSPOLICY_DECL_H
   36.25 +
   36.26 +typedef void *xen_xspolicy;
   36.27 +
   36.28 +struct xen_xspolicy_set;
   36.29 +struct xen_xspolicy_record;
   36.30 +struct xen_xspolicy_record_set;
   36.31 +struct xen_xspolicy_record_opt;
   36.32 +struct xen_xspolicy_record_opt_set;
   36.33 +
   36.34 +#endif
    37.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    37.2 +++ b/tools/libxen/src/xen_acmpolicy.c	Fri Jul 27 08:15:16 2007 -0600
    37.3 @@ -0,0 +1,234 @@
    37.4 +/*
    37.5 + * Copyright (c) 2007, IBM Corp.
    37.6 + * Copyright (c) 2007, XenSource Inc.
    37.7 + *
    37.8 + * This library is free software; you can redistribute it and/or
    37.9 + * modify it under the terms of the GNU Lesser General Public
   37.10 + * License as published by the Free Software Foundation; either
   37.11 + * version 2.1 of the License, or (at your option) any later version.
   37.12 + *
   37.13 + * This library is distributed in the hope that it will be useful,
   37.14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
   37.15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   37.16 + * Lesser General Public License for more details.
   37.17 + *
   37.18 + * You should have received a copy of the GNU Lesser General Public
   37.19 + * License along with this library; if not, write to the Free Software
   37.20 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
   37.21 + */
   37.22 +
   37.23 +
   37.24 +#include <stddef.h>
   37.25 +#include <stdlib.h>
   37.26 +
   37.27 +#include "xen_internal.h"
   37.28 +#include "xen/api/xen_common.h"
   37.29 +#include "xen/api/xen_xspolicy.h"
   37.30 +#include "xen/api/xen_acmpolicy.h"
   37.31 +
   37.32 +
   37.33 +static const struct_member xen_acmpolicy_record_struct_members[] =
   37.34 +    {
   37.35 +        { .key = "uuid",
   37.36 +          .type = &abstract_type_string,
   37.37 +          .offset = offsetof(xen_acmpolicy_record, uuid) },
   37.38 +        { .key = "flags",
   37.39 +          .type = &abstract_type_int,
   37.40 +          .offset = offsetof(xen_acmpolicy_record, flags) },
   37.41 +        { .key = "repr",
   37.42 +          .type = &abstract_type_string,
   37.43 +          .offset = offsetof(xen_acmpolicy_record, repr) },
   37.44 +        { .key = "type",
   37.45 +          .type = &abstract_type_int,
   37.46 +          .offset = offsetof(xen_acmpolicy_record, type) },
   37.47 +    };
   37.48 +
   37.49 +const abstract_type xen_acmpolicy_record_abstract_type_ =
   37.50 +    {
   37.51 +       .typename = STRUCT,
   37.52 +       .struct_size = sizeof(xen_acmpolicy_record),
   37.53 +       .member_count =
   37.54 +          sizeof(xen_acmpolicy_record_struct_members) / sizeof(struct_member),
   37.55 +       .members = xen_acmpolicy_record_struct_members
   37.56 +    };
   37.57 +
   37.58 +
   37.59 +static const struct_member xen_acm_header_struct_members[] =
   37.60 +    {
   37.61 +        { .key = "policyname",
   37.62 +          .type = &abstract_type_string,
   37.63 +          .offset = offsetof(xen_acm_header, policyname) },
   37.64 +        { .key = "policyurl",
   37.65 +          .type = &abstract_type_string,
   37.66 +          .offset = offsetof(xen_acm_header, policyurl) },
   37.67 +        { .key = "date",
   37.68 +          .type = &abstract_type_string,
   37.69 +          .offset = offsetof(xen_acm_header, date) },
   37.70 +        { .key = "reference",
   37.71 +          .type = &abstract_type_string,
   37.72 +          .offset = offsetof(xen_acm_header, reference) },
   37.73 +        { .key = "namespaceurl",
   37.74 +          .type = &abstract_type_string,
   37.75 +          .offset = offsetof(xen_acm_header, namespaceurl) },
   37.76 +        { .key = "version",
   37.77 +          .type = &abstract_type_string,
   37.78 +          .offset = offsetof(xen_acm_header, version) },
   37.79 +    };
   37.80 +
   37.81 +const abstract_type xen_acm_header_abstract_type_ =
   37.82 +    {
   37.83 +        .typename = STRUCT,
   37.84 +        .struct_size = sizeof(xen_acm_header),
   37.85 +        .member_count =
   37.86 +            sizeof(xen_acm_header_struct_members) /
   37.87 +            sizeof(struct_member),
   37.88 +        .members = xen_acm_header_struct_members,
   37.89 +    };
   37.90 +
   37.91 +void
   37.92 +xen_acm_header_free(xen_acm_header *shdr)
   37.93 +{
   37.94 +    if (shdr == NULL)
   37.95 +    {
   37.96 +        return;
   37.97 +    }
   37.98 +    free(shdr->policyname);
   37.99 +    free(shdr->policyurl);
  37.100 +    free(shdr->date);
  37.101 +    free(shdr->reference);
  37.102 +    free(shdr->namespaceurl);
  37.103 +    free(shdr->version);
  37.104 +    free(shdr);
  37.105 +}
  37.106 +
  37.107 +
  37.108 +void
  37.109 +xen_acmpolicy_record_free(xen_acmpolicy_record *record)
  37.110 +{
  37.111 +    if (record == NULL)
  37.112 +    {
  37.113 +        return;
  37.114 +    }
  37.115 +    free(record->handle);
  37.116 +    free(record->uuid);
  37.117 +    free(record->repr);
  37.118 +    free(record);
  37.119 +}
  37.120 +
  37.121 +
  37.122 +
  37.123 +bool
  37.124 +xen_acmpolicy_get_record(xen_session *session, xen_acmpolicy_record **result,
  37.125 +                         xen_xspolicy xspolicy)
  37.126 +{
  37.127 +    abstract_value param_values[] =
  37.128 +        {
  37.129 +            { .type = &abstract_type_string,
  37.130 +              .u.string_val = xspolicy }
  37.131 +        };
  37.132 +
  37.133 +    abstract_type result_type = xen_acmpolicy_record_abstract_type_;
  37.134 +
  37.135 +    *result = NULL;
  37.136 +    XEN_CALL_("ACMPolicy.get_record");
  37.137 +
  37.138 +    if (session->ok)
  37.139 +    {
  37.140 +       (*result)->handle = xen_strdup_((*result)->uuid);
  37.141 +    }
  37.142 +
  37.143 +    return session->ok;
  37.144 +}
  37.145 +
  37.146 +
  37.147 +bool
  37.148 +xen_acmpolicy_get_header(xen_session *session,
  37.149 +                         xen_acm_header **result,
  37.150 +                         xen_xspolicy xspolicy)
  37.151 +{
  37.152 +    abstract_value param_values[] =
  37.153 +        {
  37.154 +            { .type = &abstract_type_string,
  37.155 +              .u.string_val = xspolicy },
  37.156 +        };
  37.157 +
  37.158 +    abstract_type result_type = xen_acm_header_abstract_type_;
  37.159 +
  37.160 +    *result = NULL;
  37.161 +    XEN_CALL_("ACMPolicy.get_header");
  37.162 +    return session->ok;
  37.163 +}
  37.164 +
  37.165 +
  37.166 +bool
  37.167 +xen_acmpolicy_get_xml(xen_session *session,
  37.168 +                      char **result,
  37.169 +                      xen_xspolicy xspolicy)
  37.170 +{
  37.171 +    abstract_value param_values[] =
  37.172 +        {
  37.173 +            { .type = &abstract_type_string,
  37.174 +              .u.string_val = xspolicy },
  37.175 +        };
  37.176 +
  37.177 +    abstract_type result_type = abstract_type_string;
  37.178 +
  37.179 +    *result = NULL;
  37.180 +    XEN_CALL_("ACMPolicy.get_xml");
  37.181 +    return session->ok;
  37.182 +}
  37.183 +
  37.184 +
  37.185 +bool
  37.186 +xen_acmpolicy_get_map(xen_session *session,
  37.187 +                      char **result,
  37.188 +                      xen_xspolicy xspolicy)
  37.189 +{
  37.190 +    abstract_value param_values[] =
  37.191 +        {
  37.192 +            { .type = &abstract_type_string,
  37.193 +              .u.string_val = xspolicy },
  37.194 +        };
  37.195 +
  37.196 +    abstract_type result_type = abstract_type_string;
  37.197 +
  37.198 +    *result = NULL;
  37.199 +    XEN_CALL_("ACMPolicy.get_map");
  37.200 +    return session->ok;
  37.201 +}
  37.202 +
  37.203 +
  37.204 +bool
  37.205 +xen_acmpolicy_get_binary(xen_session *session, char **result,
  37.206 +                         xen_xspolicy xspolicy)
  37.207 +{
  37.208 +    abstract_value param_values[] =
  37.209 +        {
  37.210 +            { .type = &abstract_type_string,
  37.211 +              .u.string_val = xspolicy },
  37.212 +        };
  37.213 +
  37.214 +    abstract_type result_type = abstract_type_string;
  37.215 +
  37.216 +    *result = NULL;
  37.217 +    XEN_CALL_("ACMPolicy.get_binary");
  37.218 +    return session->ok;
  37.219 +}
  37.220 +
  37.221 +
  37.222 +bool
  37.223 +xen_acmpolicy_get_uuid(xen_session *session, char **result,
  37.224 +                       xen_xspolicy xspolicy)
  37.225 +{
  37.226 +    abstract_value param_values[] =
  37.227 +        {
  37.228 +            { .type = &abstract_type_string,
  37.229 +              .u.string_val = xspolicy }
  37.230 +        };
  37.231 +
  37.232 +    abstract_type result_type = abstract_type_string;
  37.233 +
  37.234 +    *result = NULL;
  37.235 +    XEN_CALL_("ACMPolicy.get_uuid");
  37.236 +    return session->ok;
  37.237 +}
    38.1 --- a/tools/libxen/src/xen_vdi.c	Thu Jul 26 14:35:01 2007 -0600
    38.2 +++ b/tools/libxen/src/xen_vdi.c	Fri Jul 27 08:15:16 2007 -0600
    38.3 @@ -534,3 +534,42 @@ xen_vdi_get_uuid(xen_session *session, c
    38.4      XEN_CALL_("VDI.get_uuid");
    38.5      return session->ok;
    38.6  }
    38.7 +
    38.8 +
    38.9 +bool
   38.10 +xen_vdi_set_security_label(xen_session *session, int64_t *result, xen_vdi vdi,
   38.11 +                           char *label, char *oldlabel)
   38.12 +{
   38.13 +    abstract_value param_values[] =
   38.14 +        {
   38.15 +            { .type = &abstract_type_string,
   38.16 +              .u.string_val = vdi },
   38.17 +            { .type = &abstract_type_string,
   38.18 +              .u.string_val = label },
   38.19 +            { .type = &abstract_type_string,
   38.20 +              .u.string_val = oldlabel },
   38.21 +        };
   38.22 +
   38.23 +    abstract_type result_type = abstract_type_int;
   38.24 +
   38.25 +    *result = 0;
   38.26 +    XEN_CALL_("VDI.set_security_label");
   38.27 +    return session->ok;
   38.28 +}
   38.29 +
   38.30 +
   38.31 +bool
   38.32 +xen_vdi_get_security_label(xen_session *session, char **result, xen_vdi vdi)
   38.33 +{
   38.34 +    abstract_value param_values[] =
   38.35 +        {
   38.36 +            { .type = &abstract_type_string,
   38.37 +              .u.string_val = vdi },
   38.38 +        };
   38.39 +
   38.40 +    abstract_type result_type = abstract_type_string;
   38.41 +
   38.42 +    *result = NULL;
   38.43 +    XEN_CALL_("VDI.get_security_label");
   38.44 +    return session->ok;
   38.45 +}
    39.1 --- a/tools/libxen/src/xen_vif.c	Thu Jul 26 14:35:01 2007 -0600
    39.2 +++ b/tools/libxen/src/xen_vif.c	Fri Jul 27 08:15:16 2007 -0600
    39.3 @@ -575,3 +575,42 @@ xen_vif_get_uuid(xen_session *session, c
    39.4      XEN_CALL_("VIF.get_uuid");
    39.5      return session->ok;
    39.6  }
    39.7 +
    39.8 +
    39.9 +bool
   39.10 +xen_vif_set_security_label(xen_session *session, int64_t *result, xen_vif vif,
   39.11 +                           char *label, char *oldlabel)
   39.12 +{
   39.13 +    abstract_value param_values[] =
   39.14 +        {
   39.15 +            { .type = &abstract_type_string,
   39.16 +              .u.string_val = vif },
   39.17 +            { .type = &abstract_type_string,
   39.18 +              .u.string_val = label },
   39.19 +            { .type = &abstract_type_string,
   39.20 +              .u.string_val = oldlabel },
   39.21 +        };
   39.22 +
   39.23 +    abstract_type result_type = abstract_type_int;
   39.24 +
   39.25 +    *result = 0;
   39.26 +    XEN_CALL_("VIF.set_security_label");
   39.27 +    return session->ok;
   39.28 +}
   39.29 +
   39.30 +
   39.31 +bool
   39.32 +xen_vif_get_security_label(xen_session *session, char **result, xen_vif vif)
   39.33 +{
   39.34 +    abstract_value param_values[] =
   39.35 +        {
   39.36 +            { .type = &abstract_type_string,
   39.37 +              .u.string_val = vif },
   39.38 +        };
   39.39 +
   39.40 +    abstract_type result_type = abstract_type_string;
   39.41 +
   39.42 +    *result = NULL;
   39.43 +    XEN_CALL_("VIF.get_security_label");
   39.44 +    return session->ok;
   39.45 +}
    40.1 --- a/tools/libxen/src/xen_vm.c	Thu Jul 26 14:35:01 2007 -0600
    40.2 +++ b/tools/libxen/src/xen_vm.c	Fri Jul 27 08:15:16 2007 -0600
    40.3 @@ -162,7 +162,10 @@ static const struct_member xen_vm_record
    40.4            .offset = offsetof(xen_vm_record, metrics) },
    40.5          { .key = "guest_metrics",
    40.6            .type = &abstract_type_ref,
    40.7 -          .offset = offsetof(xen_vm_record, guest_metrics) }
    40.8 +          .offset = offsetof(xen_vm_record, guest_metrics) },
    40.9 +        { .key = "security_label",
   40.10 +          .type = &abstract_type_string,
   40.11 +          .offset = offsetof(xen_vm_record, security_label) }
   40.12      };
   40.13  
   40.14  const abstract_type xen_vm_record_abstract_type_ =
   40.15 @@ -206,6 +209,7 @@ xen_vm_record_free(xen_vm_record *record
   40.16      xen_string_string_map_free(record->other_config);
   40.17      xen_vm_metrics_record_opt_free(record->metrics);
   40.18      xen_vm_guest_metrics_record_opt_free(record->guest_metrics);
   40.19 +    free(record->security_label);
   40.20      free(record);
   40.21  }
   40.22  
   40.23 @@ -1738,3 +1742,42 @@ xen_vm_get_uuid(xen_session *session, ch
   40.24      XEN_CALL_("VM.get_uuid");
   40.25      return session->ok;
   40.26  }
   40.27 +
   40.28 +
   40.29 +bool
   40.30 +xen_vm_set_security_label(xen_session *session, int64_t *result, xen_vm vm,
   40.31 +                          char *label, char *oldlabel)
   40.32 +{
   40.33 +    abstract_value param_values[] =
   40.34 +        {
   40.35 +            { .type = &abstract_type_string,
   40.36 +              .u.string_val = vm },
   40.37 +            { .type = &abstract_type_string,
   40.38 +              .u.string_val = label },
   40.39 +            { .type = &abstract_type_string,
   40.40 +              .u.string_val = oldlabel },
   40.41 +        };
   40.42 +
   40.43 +    abstract_type result_type = abstract_type_int;
   40.44 +
   40.45 +    *result = 0;
   40.46 +    XEN_CALL_("VM.set_security_label");
   40.47 +    return session->ok;
   40.48 +}
   40.49 +
   40.50 +
   40.51 +bool
   40.52 +xen_vm_get_security_label(xen_session *session, char **result, xen_vm vm)
   40.53 +{
   40.54 +    abstract_value param_values[] =
   40.55 +        {
   40.56 +            { .type = &abstract_type_string,
   40.57 +              .u.string_val = vm },
   40.58 +        };
   40.59 +
   40.60 +    abstract_type result_type = abstract_type_string;
   40.61 +
   40.62 +    *result = NULL;
   40.63 +    XEN_CALL_("VM.get_security_label");
   40.64 +    return session->ok;
   40.65 +}
    41.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    41.2 +++ b/tools/libxen/src/xen_xspolicy.c	Fri Jul 27 08:15:16 2007 -0600
    41.3 @@ -0,0 +1,327 @@
    41.4 +/*
    41.5 + * Copyright (c) 2007, IBM Corp.
    41.6 + * Copyright (c) 2007, XenSource Inc.
    41.7 + *
    41.8 + * This library is free software; you can redistribute it and/or
    41.9 + * modify it under the terms of the GNU Lesser General Public
   41.10 + * License as published by the Free Software Foundation; either
   41.11 + * version 2.1 of the License, or (at your option) any later version.
   41.12 + *
   41.13 + * This library is distributed in the hope that it will be useful,
   41.14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
   41.15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   41.16 + * Lesser General Public License for more details.
   41.17 + *
   41.18 + * You should have received a copy of the GNU Lesser General Public
   41.19 + * License along with this library; if not, write to the Free Software
   41.20 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
   41.21 + */
   41.22 +
   41.23 +
   41.24 +#include <stddef.h>
   41.25 +#include <stdlib.h>
   41.26 +
   41.27 +#include "xen/api/xen_common.h"
   41.28 +#include "xen/api/xen_internal.h"
   41.29 +#include "xen/api/xen_xspolicy.h"
   41.30 +
   41.31 +
   41.32 +XEN_FREE(xen_xspolicy)
   41.33 +XEN_SET_ALLOC_FREE(xen_xspolicy)
   41.34 +XEN_RECORD_OPT_FREE(xen_xspolicy)
   41.35 +
   41.36 +static const struct_member xen_xspolicy_record_struct_members[] =
   41.37 +    {
   41.38 +        { .key = "uuid",
   41.39 +          .type = &abstract_type_string,
   41.40 +          .offset = offsetof(xen_xspolicy_record, uuid) },
   41.41 +        { .key = "flags",
   41.42 +          .type = &abstract_type_int,
   41.43 +          .offset = offsetof(xen_xspolicy_record, flags) },
   41.44 +        { .key = "repr",
   41.45 +          .type = &abstract_type_string,
   41.46 +          .offset = offsetof(xen_xspolicy_record, repr) },
   41.47 +        { .key = "type",
   41.48 +          .type = &abstract_type_int,
   41.49 +          .offset = offsetof(xen_xspolicy_record, type) },
   41.50 +    };
   41.51 +
   41.52 +const abstract_type xen_xspolicy_record_abstract_type_ =
   41.53 +    {
   41.54 +       .typename = STRUCT,
   41.55 +       .struct_size = sizeof(xen_xspolicy_record),
   41.56 +       .member_count =
   41.57 +           sizeof(xen_xspolicy_record_struct_members) / sizeof(struct_member),
   41.58 +       .members = xen_xspolicy_record_struct_members
   41.59 +    };
   41.60 +
   41.61 +
   41.62 +static const struct_member xen_xs_policystate_struct_members[] =
   41.63 +    {
   41.64 +        { .key = "xs_ref",
   41.65 +          .type = &abstract_type_ref,
   41.66 +          .offset = offsetof(xen_xs_policystate, xs_ref) },
   41.67 +        { .key = "xserr",
   41.68 +          .type = &abstract_type_int,
   41.69 +          .offset = offsetof(xen_xs_policystate, xserr) },
   41.70 +        { .key = "repr",
   41.71 +          .type = &abstract_type_string,
   41.72 +          .offset = offsetof(xen_xs_policystate, repr) },
   41.73 +        { .key = "type",
   41.74 +          .type = &abstract_type_int,
   41.75 +          .offset = offsetof(xen_xs_policystate, type) },
   41.76 +        { .key = "flags",
   41.77 +          .type = &abstract_type_int,
   41.78 +          .offset = offsetof(xen_xs_policystate, flags) },
   41.79 +        { .key = "version",
   41.80 +          .type = &abstract_type_string,
   41.81 +          .offset = offsetof(xen_xs_policystate, version) },
   41.82 +        { .key = "errors",
   41.83 +          .type = &abstract_type_string,
   41.84 +          .offset = offsetof(xen_xs_policystate, errors) },
   41.85 +    };
   41.86 +
   41.87 +const abstract_type xen_xs_policystate_abstract_type_ =
   41.88 +    {
   41.89 +        .typename = STRUCT,
   41.90 +        .struct_size = sizeof(xen_xs_policystate),
   41.91 +        .member_count =
   41.92 +            sizeof(xen_xs_policystate_struct_members) /
   41.93 +            sizeof(struct_member),
   41.94 +        .members = xen_xs_policystate_struct_members,
   41.95 +    };
   41.96 +
   41.97 +
   41.98 +
   41.99 +
  41.100 +void
  41.101 +xen_xs_policystate_free(xen_xs_policystate *state)
  41.102 +{
  41.103 +    if (state == NULL)
  41.104 +    {
  41.105 +        return;
  41.106 +    }
  41.107 +    xen_xspolicy_record_opt_free(state->xs_ref);
  41.108 +    free(state->repr);
  41.109 +    free(state->errors);
  41.110 +    free(state->version);
  41.111 +    free(state);
  41.112 +}
  41.113 +
  41.114 +
  41.115 +void
  41.116 +xen_xspolicy_record_free(xen_xspolicy_record *record)
  41.117 +{
  41.118 +    if (record == NULL)
  41.119 +    {
  41.120 +        return;
  41.121 +    }
  41.122 +    free(record->handle);
  41.123 +    free(record->uuid);
  41.124 +    free(record->repr);
  41.125 +    free(record);
  41.126 +}
  41.127 +
  41.128 +
  41.129 +bool
  41.130 +xen_xspolicy_get_record(xen_session *session, xen_xspolicy_record **result,
  41.131 +                        xen_xspolicy xspolicy)
  41.132 +{
  41.133 +    abstract_value param_values[] =
  41.134 +        {
  41.135 +            { .type = &abstract_type_string,
  41.136 +              .u.string_val = xspolicy }
  41.137 +        };
  41.138 +
  41.139 +    abstract_type result_type = xen_xspolicy_record_abstract_type_;
  41.140 +
  41.141 +    *result = NULL;
  41.142 +    XEN_CALL_("XSPolicy.get_record");
  41.143 +
  41.144 +    if (session->ok)
  41.145 +    {
  41.146 +       (*result)->handle = xen_strdup_((*result)->uuid);
  41.147 +    }
  41.148 +
  41.149 +    return session->ok;
  41.150 +}
  41.151 +
  41.152 +
  41.153 +bool
  41.154 +xen_xspolicy_get_uuid(xen_session *session, char **result,
  41.155 +                      xen_xspolicy xspolicy)
  41.156 +{
  41.157 +    abstract_value param_values[] =
  41.158 +        {
  41.159 +            { .type = &abstract_type_string,
  41.160 +              .u.string_val = xspolicy }
  41.161 +        };
  41.162 +
  41.163 +    abstract_type result_type = abstract_type_string;
  41.164 +
  41.165 +    *result = NULL;
  41.166 +    XEN_CALL_("XSPolicy.get_uuid");
  41.167 +    return session->ok;
  41.168 +}
  41.169 +
  41.170 +
  41.171 +bool
  41.172 +xen_xspolicy_get_by_uuid(xen_session *session, xen_xspolicy *result,
  41.173 +                         char *uuid)
  41.174 +{
  41.175 +    abstract_value param_values[] =
  41.176 +        {
  41.177 +            { .type = &abstract_type_string,
  41.178 +              .u.string_val = uuid }
  41.179 +        };
  41.180 +
  41.181 +    abstract_type result_type = abstract_type_string;
  41.182 +
  41.183 +    *result = NULL;
  41.184 +    XEN_CALL_("XSPolicy.get_by_uuid");
  41.185 +    return session->ok;
  41.186 +}
  41.187 +
  41.188 +
  41.189 +bool
  41.190 +xen_xspolicy_get_xstype(xen_session *session, xs_type *result)
  41.191 +{
  41.192 +    abstract_value param_values[] =
  41.193 +        {
  41.194 +        };
  41.195 +
  41.196 +    abstract_type result_type = abstract_type_int;
  41.197 +
  41.198 +    *result = 0;
  41.199 +    XEN_CALL_("XSPolicy.get_xstype");
  41.200 +    return session->ok;
  41.201 +}
  41.202 +
  41.203 +
  41.204 +bool
  41.205 +xen_xspolicy_set_xspolicy(xen_session *session, xen_xs_policystate **result,
  41.206 +                          xs_type type, char *repr,
  41.207 +                          xs_instantiationflags flags,
  41.208 +                          bool overwrite)
  41.209 +{
  41.210 +    abstract_value param_values[] =
  41.211 +        {
  41.212 +            { .type = &abstract_type_int,
  41.213 +              .u.int_val = type },
  41.214 +            { .type = &abstract_type_string,
  41.215 +              .u.string_val = repr },
  41.216 +            { .type = &abstract_type_int,
  41.217 +              .u.int_val = flags },
  41.218 +            { .type = &abstract_type_bool,
  41.219 +              .u.bool_val = overwrite }
  41.220 +        };
  41.221 +
  41.222 +    abstract_type result_type = xen_xs_policystate_abstract_type_;
  41.223 +
  41.224 +    *result = NULL;
  41.225 +    XEN_CALL_("XSPolicy.set_xspolicy");
  41.226 +    return session->ok;
  41.227 +}
  41.228 +
  41.229 +
  41.230 +bool
  41.231 +xen_xspolicy_get_xspolicy(xen_session *session, xen_xs_policystate **result)
  41.232 +{
  41.233 +    abstract_value param_values[] =
  41.234 +        {
  41.235 +        };
  41.236 +
  41.237 +    abstract_type result_type = xen_xs_policystate_abstract_type_;
  41.238 +
  41.239 +    *result = NULL;
  41.240 +    XEN_CALL_("XSPolicy.get_xspolicy");
  41.241 +    return session->ok;
  41.242 +}
  41.243 +
  41.244 +
  41.245 +bool
  41.246 +xen_xspolicy_get_labeled_resources(xen_session *session,
  41.247 +                                   xen_string_string_map **result)
  41.248 +{
  41.249 +    abstract_value param_values[] =
  41.250 +        {
  41.251 +        };
  41.252 +
  41.253 +    abstract_type result_type = abstract_type_string_string_map;
  41.254 +
  41.255 +    *result = NULL;
  41.256 +    XEN_CALL_("XSPolicy.get_labeled_resources");
  41.257 +    return session->ok;
  41.258 +}
  41.259 +
  41.260 +
  41.261 +bool
  41.262 +xen_xspolicy_set_resource_label(xen_session *session,
  41.263 +                                char *resource, char *label,
  41.264 +                                char *oldlabel)
  41.265 +{
  41.266 +    abstract_value param_values[] =
  41.267 +        {
  41.268 +            { .type = &abstract_type_string,
  41.269 +              .u.string_val = resource },
  41.270 +            { .type = &abstract_type_string,
  41.271 +              .u.string_val = label },
  41.272 +            { .type = &abstract_type_string,
  41.273 +              .u.string_val = oldlabel },
  41.274 +        };
  41.275 +
  41.276 +    xen_call_(session, "XSPolicy.set_resource_label", param_values, 3,
  41.277 +                       NULL, NULL);
  41.278 +    return session->ok;
  41.279 +}
  41.280 +
  41.281 +
  41.282 +bool
  41.283 +xen_xspolicy_get_resource_label(xen_session *session, char **result,
  41.284 +                                char *resource)
  41.285 +{
  41.286 +    abstract_value param_values[] =
  41.287 +        {
  41.288 +            { .type = &abstract_type_string,
  41.289 +              .u.string_val = resource },
  41.290 +        };
  41.291 +
  41.292 +    abstract_type result_type = abstract_type_string;
  41.293 +    XEN_CALL_("XSPolicy.get_resource_label");
  41.294 +    return session->ok;
  41.295 +}
  41.296 +
  41.297 +
  41.298 +bool
  41.299 +xen_xspolicy_rm_xsbootpolicy(xen_session *session)
  41.300 +{
  41.301 +    abstract_value param_values[] =
  41.302 +        {
  41.303 +        };
  41.304 +
  41.305 +    xen_call_(session, "XSPolicy.rm_xsbootpolicy", param_values, 0,
  41.306 +                       NULL, NULL);
  41.307 +    return session->ok;
  41.308 +}
  41.309 +
  41.310 +
  41.311 +bool
  41.312 +xen_xspolicy_activate_xspolicy(xen_session *session,
  41.313 +                               xs_instantiationflags *result,
  41.314 +                               xen_xspolicy xspolicy,
  41.315 +                               xs_instantiationflags flags)
  41.316 +{
  41.317 +    abstract_value param_values[] =
  41.318 +        {
  41.319 +            { .type = &abstract_type_string,
  41.320 +              .u.string_val = xspolicy },
  41.321 +            { .type = &abstract_type_int,
  41.322 +              .u.int_val = flags },
  41.323 +        };
  41.324 +
  41.325 +    abstract_type result_type = abstract_type_int;
  41.326 +
  41.327 +    *result = 0;
  41.328 +    XEN_CALL_("XSPolicy.activate_xspolicy");
  41.329 +    return session->ok;
  41.330 +}
    42.1 --- a/tools/python/xen/lowlevel/acm/acm.c	Thu Jul 26 14:35:01 2007 -0600
    42.2 +++ b/tools/python/xen/lowlevel/acm/acm.c	Fri Jul 27 08:15:16 2007 -0600
    42.3 @@ -148,9 +148,10 @@ static PyObject *getdecision(PyObject * 
    42.4      char *arg1_name, *arg1, *arg2_name, *arg2, *decision = NULL;
    42.5      struct acm_getdecision getdecision;
    42.6      int xc_handle, rc;
    42.7 +    uint32_t hooktype;
    42.8  
    42.9 -    if (!PyArg_ParseTuple(args, "ssss", &arg1_name,
   42.10 -                          &arg1, &arg2_name, &arg2)) {
   42.11 +    if (!PyArg_ParseTuple(args, "ssssi", &arg1_name,
   42.12 +                          &arg1, &arg2_name, &arg2, &hooktype)) {
   42.13          return NULL;
   42.14      }
   42.15  
   42.16 @@ -163,7 +164,7 @@ static PyObject *getdecision(PyObject * 
   42.17      (strcmp(arg2_name, "domid") && strcmp(arg2_name, "ssidref")))
   42.18          return NULL;
   42.19  
   42.20 -    getdecision.hook = ACMHOOK_sharing;
   42.21 +    getdecision.hook = hooktype;
   42.22      if (!strcmp(arg1_name, "domid")) {
   42.23          getdecision.get_decision_by1 = ACM_GETBY_domainid;
   42.24          getdecision.id1.domainid = atoi(arg1);
    43.1 --- a/tools/python/xen/util/acmpolicy.py	Thu Jul 26 14:35:01 2007 -0600
    43.2 +++ b/tools/python/xen/util/acmpolicy.py	Fri Jul 27 08:15:16 2007 -0600
    43.3 @@ -57,12 +57,20 @@ class ACMPolicy(XSPolicy):
    43.4      def __init__(self, name=None, dom=None, ref=None, xml=None):
    43.5          if name:
    43.6              self.name = name
    43.7 -            self.dom = minidom.parse(self.path_from_policy_name(name))
    43.8 +            try:
    43.9 +                self.dom = minidom.parse(self.path_from_policy_name(name))
   43.10 +            except Exception, e:
   43.11 +                raise SecurityError(-xsconstants.XSERR_XML_PROCESSING,
   43.12 +                                    str(e))
   43.13          elif dom:
   43.14              self.dom = dom
   43.15              self.name = self.get_name()
   43.16          elif xml:
   43.17 -            self.dom = minidom.parseString(xml)
   43.18 +            try:
   43.19 +                self.dom = minidom.parseString(xml)
   43.20 +            except Exception, e:
   43.21 +                raise SecurityError(-xsconstants.XSERR_XML_PROCESSING,
   43.22 +                                    str(e))
   43.23              self.name = self.get_name()
   43.24          rc = self.validate()
   43.25          if rc != xsconstants.XSERR_SUCCESS:
   43.26 @@ -114,7 +122,8 @@ class ACMPolicy(XSPolicy):
   43.27              rc = -xsconstants.XSERR_GENERAL_FAILURE
   43.28          if rc != xsconstants.XSERR_SUCCESS:
   43.29              log.warn("XML did not validate against schema")
   43.30 -        rc = self.__validate_name_and_labels()
   43.31 +        if rc == xsconstants.XSERR_SUCCESS:
   43.32 +            rc = self.__validate_name_and_labels()
   43.33          return rc
   43.34  
   43.35      def __validate_name_and_labels(self):
   43.36 @@ -481,7 +490,8 @@ class ACMPolicy(XSPolicy):
   43.37          strings = []
   43.38          i = 0
   43.39          while i < len(node.childNodes):
   43.40 -            if node.childNodes[i].nodeName == "Type":
   43.41 +            if node.childNodes[i].nodeName == "Type" and \
   43.42 +               len(node.childNodes[i].childNodes) > 0:
   43.43                  strings.append(node.childNodes[i].childNodes[0].nodeValue)
   43.44              i += 1
   43.45          return strings
   43.46 @@ -564,7 +574,8 @@ class ACMPolicy(XSPolicy):
   43.47              while i < len(node.childNodes):
   43.48                  if node.childNodes[i].nodeName == "VirtualMachineLabel":
   43.49                      name = self.policy_dom_get(node.childNodes[i], "Name")
   43.50 -                    strings.append(name.childNodes[0].nodeValue)
   43.51 +                    if len(name.childNodes) > 0:
   43.52 +                        strings.append(name.childNodes[0].nodeValue)
   43.53                  i += 1
   43.54          return strings
   43.55  
   43.56 @@ -592,43 +603,46 @@ class ACMPolicy(XSPolicy):
   43.57              i = 0
   43.58              while i < len(node.childNodes):
   43.59                  if node.childNodes[i].nodeName == "VirtualMachineLabel":
   43.60 -                    _res = {}
   43.61 -                    _res['type'] = xsconstants.ACM_LABEL_VM
   43.62                      name = self.policy_dom_get(node.childNodes[i], "Name")
   43.63 -                    _res['name'] = name.childNodes[0].nodeValue
   43.64 -                    stes = self.policy_dom_get(node.childNodes[i],
   43.65 -                                               "SimpleTypeEnforcementTypes")
   43.66 -                    if stes:
   43.67 -                        _res['stes'] = self.policy_get_types(stes)
   43.68 -                    else:
   43.69 -                        _res['stes'] = []
   43.70 -                    chws = self.policy_dom_get(node.childNodes[i],
   43.71 -                                               "ChineseWallTypes")
   43.72 -                    if chws:
   43.73 -                        _res['chws'] = self.policy_get_types(chws)
   43.74 -                    else:
   43.75 -                        _res['chws'] = []
   43.76 -                    res.append(_res)
   43.77 +                    if len(name.childNodes) > 0:
   43.78 +                        _res = {}
   43.79 +                        _res['type'] = xsconstants.ACM_LABEL_VM
   43.80 +                        _res['name'] = name.childNodes[0].nodeValue
   43.81 +                        stes = self.policy_dom_get(node.childNodes[i],
   43.82 +                                                 "SimpleTypeEnforcementTypes")
   43.83 +                        if stes:
   43.84 +                           _res['stes'] = self.policy_get_types(stes)
   43.85 +                        else:
   43.86 +                            _res['stes'] = []
   43.87 +                        chws = self.policy_dom_get(node.childNodes[i],
   43.88 +                                                   "ChineseWallTypes")
   43.89 +                        if chws:
   43.90 +                            _res['chws'] = self.policy_get_types(chws)
   43.91 +                        else:
   43.92 +                            _res['chws'] = []
   43.93 +                        res.append(_res)
   43.94                  i += 1
   43.95          return res
   43.96  
   43.97      def policy_get_stes_of_vmlabel(self, vmlabel):
   43.98          """ Get a list of all STEs of a given VMlabel """
   43.99          return self.__policy_get_stes_of_labeltype(vmlabel,
  43.100 -                                                   "VirtualMachineLabel")
  43.101 +                                        "/SubjectLabels", "VirtualMachineLabel")
  43.102  
  43.103      def policy_get_stes_of_resource(self, reslabel):
  43.104          """ Get a list of all resources of a given VMlabel """
  43.105 -        return self.__policy_get_stes_of_labeltype(reslabel, "ResourceLabel")
  43.106 +        return self.__policy_get_stes_of_labeltype(reslabel,
  43.107 +                                        "/ObjectLabels", "ResourceLabel")
  43.108  
  43.109 -    def __policy_get_stes_of_labeltype(self, label, labeltype):
  43.110 -        node = self.dom_get_node("SecurityLabelTemplate/SubjectLabels")
  43.111 +    def __policy_get_stes_of_labeltype(self, label, path, labeltype):
  43.112 +        node = self.dom_get_node("SecurityLabelTemplate" + path)
  43.113          if node:
  43.114              i = 0
  43.115              while i < len(node.childNodes):
  43.116                  if node.childNodes[i].nodeName == labeltype:
  43.117                      name = self.policy_dom_get(node.childNodes[i], "Name")
  43.118 -                    if name.childNodes[0].nodeValue == label:
  43.119 +                    if len(name.childNodes) > 0 and \
  43.120 +                       name.childNodes[0].nodeValue == label:
  43.121                          stes = self.policy_dom_get(node.childNodes[i],
  43.122                                              "SimpleTypeEnforcementTypes")
  43.123                          if not stes:
  43.124 @@ -649,7 +663,8 @@ class ACMPolicy(XSPolicy):
  43.125              return False
  43.126          for res in resources:
  43.127              res_stes = self.policy_get_stes_of_resource(res)
  43.128 -            if len( set(res_stes).union( set(vm_stes) ) ) == 0:
  43.129 +            if len(res_stes) == 0 or \
  43.130 +               len( set(res_stes).intersection( set(vm_stes) ) ) == 0:
  43.131                  return False
  43.132          return True
  43.133  
  43.134 @@ -662,7 +677,7 @@ class ACMPolicy(XSPolicy):
  43.135                  if node.childNodes[i].nodeName == labeltype:
  43.136                      name = self.policy_dom_get(node.childNodes[i], "Name")
  43.137                      from_name = name.getAttribute("from")
  43.138 -                    if from_name:
  43.139 +                    if from_name and len(name.childNodes) > 0:
  43.140                          res.update({from_name : name.childNodes[0].nodeValue})
  43.141                  i += 1
  43.142          return res
  43.143 @@ -700,7 +715,7 @@ class ACMPolicy(XSPolicy):
  43.144                      name = self.policy_dom_get(node.childNodes[i], "Name")
  43.145                      stes = self.policy_dom_get(node.childNodes[i],
  43.146                                            "SimpleTypeEnforcementTypes")
  43.147 -                    if stes:
  43.148 +                    if stes and len(name.childNodes) > 0:
  43.149                          strings.append(name.childNodes[0].nodeValue)
  43.150                  i += 1
  43.151          return strings
  43.152 @@ -715,18 +730,19 @@ class ACMPolicy(XSPolicy):
  43.153              i = 0
  43.154              while i < len(node.childNodes):
  43.155                  if node.childNodes[i].nodeName == "ResourceLabel":
  43.156 -                    _res = {}
  43.157 -                    _res['type'] = xsconstants.ACM_LABEL_RES
  43.158                      name = self.policy_dom_get(node.childNodes[i], "Name")
  43.159 -                    _res['name'] = name.childNodes[0].nodeValue
  43.160 -                    stes = self.policy_dom_get(node.childNodes[i],
  43.161 -                                               "SimpleTypeEnforcementTypes")
  43.162 -                    if stes:
  43.163 -                        _res['stes'] = self.policy_get_types(stes)
  43.164 -                    else:
  43.165 -                        _res['stes'] = []
  43.166 -                    _res['chws'] = []
  43.167 -                    res.append(_res)
  43.168 +                    if len(name.childNodes) > 0:
  43.169 +                        _res = {}
  43.170 +                        _res['type'] = xsconstants.ACM_LABEL_RES
  43.171 +                        _res['name'] = name.childNodes[0].nodeValue
  43.172 +                        stes = self.policy_dom_get(node.childNodes[i],
  43.173 +                                                   "SimpleTypeEnforcementTypes")
  43.174 +                        if stes:
  43.175 +                            _res['stes'] = self.policy_get_types(stes)
  43.176 +                        else:
  43.177 +                            _res['stes'] = []
  43.178 +                        _res['chws'] = []
  43.179 +                        res.append(_res)
  43.180                  i += 1
  43.181          return res
  43.182  
    44.1 --- a/tools/python/xen/util/security.py	Thu Jul 26 14:35:01 2007 -0600
    44.2 +++ b/tools/python/xen/util/security.py	Fri Jul 27 08:15:16 2007 -0600
    44.3 @@ -62,6 +62,10 @@ empty_line_re = re.compile("^\s*$")
    44.4  binary_name_re = re.compile(".*[chwall|ste|chwall_ste].*\.bin", re.IGNORECASE)
    44.5  policy_name_re = re.compile(".*[chwall|ste|chwall_ste].*", re.IGNORECASE)
    44.6  
    44.7 +#decision hooks known to the hypervisor
    44.8 +ACMHOOK_sharing = 1
    44.9 +ACMHOOK_authorization = 2
   44.10 +
   44.11  #other global variables
   44.12  NULL_SSIDREF = 0
   44.13  
   44.14 @@ -155,75 +159,6 @@ def calc_dom_ssidref_from_info(info):
   44.15      raise VmError("security.calc_dom_ssidref_from_info: info of type '%s'"
   44.16                    "not supported." % type(info))
   44.17  
   44.18 -# Assumes a 'security' info  [security access_control ...] [ssidref ...]
   44.19 -def get_security_info(info, field):
   44.20 -    """retrieves security field from self.info['security'])
   44.21 -    allowed search fields: ssidref, label, policy
   44.22 -    """
   44.23 -    if isinstance(info, dict):
   44.24 -        security = info['security']
   44.25 -    elif isinstance(info, list):
   44.26 -        security = sxp.child_value(info, 'security')
   44.27 -    if not security:
   44.28 -        if field == 'ssidref':
   44.29 -            #return default ssid
   44.30 -            return 0
   44.31 -        else:
   44.32 -            err("Security information not found in info struct.")
   44.33 -
   44.34 -    if field == 'ssidref':
   44.35 -        search = 'ssidref'
   44.36 -    elif field in ['policy', 'label']:
   44.37 -            search = 'access_control'
   44.38 -    else:
   44.39 -        err("Illegal field in get_security_info.")
   44.40 -
   44.41 -    for idx in range(0, len(security)):
   44.42 -        if search != security[idx][0]:
   44.43 -            continue
   44.44 -        if search == 'ssidref':
   44.45 -            return int(security[idx][1])
   44.46 -        else:
   44.47 -            for aidx in range(0, len(security[idx])):
   44.48 -                if security[idx][aidx][0] == field:
   44.49 -                    return str(security[idx][aidx][1])
   44.50 -
   44.51 -    if search == 'ssidref':
   44.52 -        return 0
   44.53 -    else:
   44.54 -        return None
   44.55 -
   44.56 -
   44.57 -def get_security_printlabel(info):
   44.58 -    """retrieves printable security label from self.info['security']),
   44.59 -    preferably the label name and otherwise (if label is not specified
   44.60 -    in config and cannot be found in mapping file) a hex string of the
   44.61 -    ssidref or none if both not available
   44.62 -    """
   44.63 -    try:
   44.64 -        if not on():
   44.65 -            return "INACTIVE"
   44.66 -        if active_policy in ["DEFAULT"]:
   44.67 -            return "DEFAULT"
   44.68 -
   44.69 -        printlabel = get_security_info(info, 'label')
   44.70 -        if printlabel:
   44.71 -            return printlabel
   44.72 -        ssidref = get_security_info(info, 'ssidref')
   44.73 -        if not ssidref:
   44.74 -            return None
   44.75 -        #try to translate ssidref to a label
   44.76 -        result = ssidref2label(ssidref)
   44.77 -        if not result:
   44.78 -            printlabel = "0x%08x" % ssidref
   44.79 -        else:
   44.80 -            printlabel = result
   44.81 -        return printlabel
   44.82 -    except ACMError:
   44.83 -        #don't throw an exception in xm list
   44.84 -        return "ERROR"
   44.85 -
   44.86 -
   44.87  
   44.88  def getmapfile(policyname):
   44.89      """
   44.90 @@ -522,7 +457,8 @@ def get_decision(arg1, arg2):
   44.91          err("Invalid id or ssidref type, string or int required")
   44.92  
   44.93      try:
   44.94 -        decision = acm.getdecision(arg1[0], arg1[1], arg2[0], arg2[1])
   44.95 +        decision = acm.getdecision(arg1[0], arg1[1], arg2[0], arg2[1],
   44.96 +                                   ACMHOOK_sharing)
   44.97      except:
   44.98          err("Cannot determine decision.")
   44.99  
  44.100 @@ -532,6 +468,21 @@ def get_decision(arg1, arg2):
  44.101          err("Cannot determine decision (Invalid parameter).")
  44.102  
  44.103  
  44.104 +def has_authorization(ssidref):
  44.105 +    """ Check if the domain with the given ssidref has authorization to
  44.106 +        run on this system. To have authoriztion dom0's STE types must
  44.107 +        be a superset of that of the domain's given through its ssidref.
  44.108 +    """
  44.109 +    rc = True
  44.110 +    dom0_ssidref = int(acm.getssid(0)['ssidref'])
  44.111 +    decision = acm.getdecision('ssidref', str(dom0_ssidref),
  44.112 +                               'ssidref', str(ssidref),
  44.113 +                               ACMHOOK_authorization)
  44.114 +    if decision == "DENIED":
  44.115 +        rc = False
  44.116 +    return rc
  44.117 +
  44.118 +
  44.119  def hv_chg_policy(bin_pol, del_array, chg_array):
  44.120      """
  44.121          Change the binary policy in the hypervisor
  44.122 @@ -868,9 +819,10 @@ def is_resource_in_use(resource):
  44.123              lst.append(dominfo)
  44.124      return lst
  44.125  
  44.126 -def devices_equal(res1, res2):
  44.127 +def devices_equal(res1, res2, mustexist=True):
  44.128      """ Determine whether two devices are equal """
  44.129 -    return (unify_resname(res1) == unify_resname(res2))
  44.130 +    return (unify_resname(res1, mustexist) ==
  44.131 +            unify_resname(res2, mustexist))
  44.132  
  44.133  def is_resource_in_use_by_dom(dominfo, resource):
  44.134      """ Determine whether a resources is in use by a given domain
  44.135 @@ -886,7 +838,7 @@ def is_resource_in_use_by_dom(dominfo, r
  44.136          dev = devs[uuid]
  44.137          if len(dev) >= 2 and dev[1].has_key('uname'):
  44.138              # dev[0] is type, i.e. 'vbd'
  44.139 -            if devices_equal(dev[1]['uname'], resource):
  44.140 +            if devices_equal(dev[1]['uname'], resource, mustexist=False):
  44.141                  log.info("RESOURCE IN USE: Domain %d uses %s." %
  44.142                           (dominfo.domid, resource))
  44.143                  return True
  44.144 @@ -899,7 +851,7 @@ def get_domain_resources(dominfo):
  44.145          Entries are strored in the following formats:
  44.146            tap:qcow:/path/xyz.qcow
  44.147      """
  44.148 -    resources = { 'vbd' : [], 'tap' : []}
  44.149 +    resources = { 'vbd' : [], 'tap' : [], 'vif' : []}
  44.150      devs = dominfo.info['devices']
  44.151      uuids = devs.keys()
  44.152      for uuid in uuids:
  44.153 @@ -907,6 +859,15 @@ def get_domain_resources(dominfo):
  44.154          typ = dev[0]
  44.155          if typ in [ 'vbd', 'tap' ]:
  44.156              resources[typ].append(dev[1]['uname'])
  44.157 +        if typ in [ 'vif' ]:
  44.158 +            sec_lab = dev[1].get('security_label')
  44.159 +            if sec_lab:
  44.160 +                resources[typ].append(sec_lab)
  44.161 +            else:
  44.162 +                resources[typ].append("%s:%s:%s" %
  44.163 +                                      (xsconstants.ACM_POLICY_ID,
  44.164 +                                       active_policy,
  44.165 +                                       "unlabeled"))
  44.166  
  44.167      return resources
  44.168  
  44.169 @@ -942,23 +903,36 @@ def __resources_compatible_with_vmlabel(
  44.170          dictionary of the resource name to resource label mappings
  44.171          under which the evaluation should be done.
  44.172      """
  44.173 +    def collect_labels(reslabels, s_label, polname):
  44.174 +        if len(s_label) != 3 or polname != s_label[1]:
  44.175 +            return False
  44.176 +        label = s_label[2]
  44.177 +        if not label in reslabels:
  44.178 +            reslabels.append(label)
  44.179 +        return True
  44.180 +
  44.181      resources = get_domain_resources(dominfo)
  44.182      reslabels = []  # all resource labels
  44.183 -    polname = xspol.get_name()
  44.184 -    for key in resources.keys():
  44.185 -        for res in resources[key]:
  44.186 -            try:
  44.187 -                tmp = access_control[res]
  44.188 -                if len(tmp) != 3:
  44.189 -                    return False
  44.190  
  44.191 -                if polname != tmp[1]:
  44.192 +    polname = xspol.get_name()
  44.193 +    for key, value in resources.items():
  44.194 +        if key in [ 'vbd', 'tap' ]:
  44.195 +            for res in resources[key]:
  44.196 +                try:
  44.197 +                    label = access_control[res]
  44.198 +                    if not collect_labels(reslabels, label, polname):
  44.199 +                        return False
  44.200 +                except:
  44.201                      return False
  44.202 -                label = tmp[2]
  44.203 -                if not label in reslabels:
  44.204 -                    reslabels.append(label)
  44.205 -            except:
  44.206 -                return False
  44.207 +        elif key in [ 'vif' ]:
  44.208 +            for xapi_label in value:
  44.209 +                label = xapi_label.split(":")
  44.210 +                if not collect_labels(reslabels, label, polname):
  44.211 +                    return False
  44.212 +        else:
  44.213 +            log.error("Unhandled device type: %s" % key)
  44.214 +            return False
  44.215 +
  44.216      # Check that all resource labes have a common STE type with the
  44.217      # vmlabel
  44.218      rc = xspol.policy_check_vmlabel_against_reslabels(vmlabel, reslabels)
    45.1 --- a/tools/python/xen/xend/XendAPI.py	Thu Jul 26 14:35:01 2007 -0600
    45.2 +++ b/tools/python/xen/xend/XendAPI.py	Fri Jul 27 08:15:16 2007 -0600
    45.3 @@ -1410,22 +1410,22 @@ class XendAPI(object):
    45.4      def VM_set_memory_dynamic_max(self, session, vm_ref, mem):
    45.5          dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
    45.6          dom.set_memory_dynamic_max(int(mem))
    45.7 -        return xen_api_success_void()
    45.8 +        return self._VM_save(dom)
    45.9  
   45.10      def VM_set_memory_dynamic_min(self, session, vm_ref, mem):
   45.11          dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
   45.12          dom.set_memory_dynamic_min(int(mem))
   45.13 -        return xen_api_success_void()
   45.14 +        return self._VM_save(dom)
   45.15  
   45.16      def VM_set_memory_static_max(self, session, vm_ref, mem):
   45.17          dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
   45.18          dom.set_memory_static_max(int(mem))
   45.19 -        return xen_api_success_void()
   45.20 +        return self._VM_save(dom)
   45.21      
   45.22      def VM_set_memory_static_min(self, session, vm_ref, mem):
   45.23          dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
   45.24          dom.set_memory_static_min(int(mem))
   45.25 -        return xen_api_success_void()
   45.26 +        return self._VM_save(dom)
   45.27  
   45.28      def VM_set_memory_dynamic_max_live(self, session, vm_ref, mem):
   45.29          dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
   45.30 @@ -1620,7 +1620,8 @@ class XendAPI(object):
   45.31          (rc, errors, oldlabel, new_ssidref) = \
   45.32                                   dom.set_security_label(sec_label, old_label)
   45.33          if rc != xsconstants.XSERR_SUCCESS:
   45.34 -            return xen_api_error(['SECURITY_ERROR', rc])
   45.35 +            return xen_api_error(['SECURITY_ERROR', rc,
   45.36 +                                 xsconstants.xserr2string(-rc)])
   45.37          if rc == 0:
   45.38              rc = new_ssidref
   45.39          return xen_api_success(rc)
   45.40 @@ -2083,6 +2084,25 @@ class XendAPI(object):
   45.41      def VIF_get_security_label(self, session, vif_ref):
   45.42          return self._VIF_get(vif_ref, 'security_label')
   45.43  
   45.44 +    def _VIF_set(self, ref, prop, val, old_val):
   45.45 +        return XendDomain.instance().set_dev_property_by_uuid(
   45.46 +                       'vif', ref, prop, val, old_val)
   45.47 +
   45.48 +    def VIF_set_security_label(self, session, vif_ref, sec_lab, old_lab):
   45.49 +        xendom = XendDomain.instance()
   45.50 +        dom = xendom.get_vm_with_dev_uuid('vif', vif_ref)
   45.51 +        if not dom:
   45.52 +            return xen_api_error(['HANDLE_INVALID', 'VIF', vif_ref])
   45.53 +
   45.54 +        if dom._stateGet() == XEN_API_VM_POWER_STATE_RUNNING:
   45.55 +            raise SecurityError(-xsconstants.XSERR_RESOURCE_IN_USE)
   45.56 +
   45.57 +        rc = self._VIF_set(vif_ref, 'security_label', sec_lab, old_lab)
   45.58 +        if rc == False:
   45.59 +            raise SecurityError(-xsconstants.XSERR_BAD_LABEL)
   45.60 +        return xen_api_success(xsconstants.XSERR_SUCCESS)
   45.61 +
   45.62 +
   45.63      # Xen API: Class VIF_metrics
   45.64      # ----------------------------------------------------------------
   45.65  
   45.66 @@ -2239,7 +2259,8 @@ class XendAPI(object):
   45.67          vdi = XendNode.instance().get_vdi_by_uuid(vdi_ref)
   45.68          rc = vdi.set_security_label(sec_lab, old_lab)
   45.69          if rc < 0:
   45.70 -            return xen_api_error(['SECURITY_ERROR', rc])
   45.71 +            return xen_api_error(['SECURITY_ERROR', rc,
   45.72 +                                 xsconstants.xserr2string(-rc)])
   45.73          return xen_api_success(rc)
   45.74  
   45.75      def VDI_get_security_label(self, session, vdi_ref):
   45.76 @@ -2357,11 +2378,13 @@ class XendAPI(object):
   45.77          return xen_api_success(cons)
   45.78  
   45.79      def console_get_location(self, session, console_ref):
   45.80 +        xendom = XendDomain.instance()
   45.81          return xen_api_success(xendom.get_dev_property_by_uuid('console',
   45.82                                                                 console_ref,
   45.83                                                                 'location'))
   45.84  
   45.85      def console_get_protocol(self, session, console_ref):
   45.86 +        xendom = XendDomain.instance()
   45.87          return xen_api_success(xendom.get_dev_property_by_uuid('console',
   45.88                                                                 console_ref,
   45.89                                                                 'protocol'))
   45.90 @@ -2371,6 +2394,12 @@ class XendAPI(object):
   45.91          vm = xendom.get_vm_with_dev_uuid('console', console_ref)
   45.92          return xen_api_success(vm.get_uuid())
   45.93      
   45.94 +    def console_get_other_config(self, session, console_ref):
   45.95 +        xendom = XendDomain.instance()        
   45.96 +        return xen_api_success(xendom.get_dev_property_by_uuid('console',
   45.97 +                                                               console_ref,
   45.98 +                                                               'other_config'))
   45.99 +    
  45.100      # object methods
  45.101      def console_get_record(self, session, console_ref):
  45.102          xendom = XendDomain.instance()
  45.103 @@ -2409,6 +2438,13 @@ class XendAPI(object):
  45.104          except XendError, exn:
  45.105              return xen_api_error(['INTERNAL_ERROR', str(exn)])
  45.106  
  45.107 +    def console_set_other_config(self, session, console_ref, other_config):
  45.108 +        xd = XendDomain.instance()
  45.109 +        vm = xd.get_vm_with_dev_uuid('console', console_ref)
  45.110 +        vm.set_console_other_config(console_ref, other_config)
  45.111 +        xd.managed_config_save(vm)
  45.112 +        return xen_api_success_void()
  45.113 +
  45.114      # Xen API: Class SR
  45.115      # ----------------------------------------------------------------
  45.116      SR_attr_ro = ['VDIs',
    46.1 --- a/tools/python/xen/xend/XendCheckpoint.py	Thu Jul 26 14:35:01 2007 -0600
    46.2 +++ b/tools/python/xen/xend/XendCheckpoint.py	Fri Jul 27 08:15:16 2007 -0600
    46.3 @@ -98,10 +98,6 @@ def save(fd, dominfo, network, live, dst
    46.4                  log.info("Domain %d suspended.", dominfo.getDomid())
    46.5                  dominfo.migrateDevices(network, dst, DEV_MIGRATE_STEP3,
    46.6                                         domain_name)
    46.7 -                #send signal to device model for save
    46.8 -                if hvm:
    46.9 -                    log.info("release_devices for hvm domain")
   46.10 -                    dominfo._releaseDevices(True)
   46.11                  tochild.write("done\n")
   46.12                  tochild.flush()
   46.13                  log.debug('Written done')
   46.14 @@ -139,7 +135,7 @@ def save(fd, dominfo, network, live, dst
   46.15      except Exception, exn:
   46.16          log.exception("Save failed on domain %s (%s).", domain_name,
   46.17                        dominfo.getDomid())
   46.18 -
   46.19 +        
   46.20          dominfo.resumeDomain()
   46.21          log.debug("XendCheckpoint.save: resumeDomain")
   46.22  
    47.1 --- a/tools/python/xen/xend/XendConfig.py	Thu Jul 26 14:35:01 2007 -0600
    47.2 +++ b/tools/python/xen/xend/XendConfig.py	Fri Jul 27 08:15:16 2007 -0600
    47.3 @@ -129,6 +129,11 @@ XENAPI_PLATFORM_CFG = [ 'acpi', 'apic', 
    47.4                          'vncconsole', 'vncdisplay', 'vnclisten',
    47.5                          'vncpasswd', 'vncunused', 'xauthority']
    47.6  
    47.7 +# Xen API console 'other_config' keys.
    47.8 +XENAPI_CONSOLE_OTHER_CFG = ['vncunused', 'vncdisplay', 'vnclisten',
    47.9 +                            'vncpasswd', 'type', 'display', 'xauthority',
   47.10 +                            'keymap']
   47.11 +
   47.12  # List of XendConfig configuration keys that have no direct equivalent
   47.13  # in the old world.
   47.14  
   47.15 @@ -636,6 +641,8 @@ class XendConfig(dict):
   47.16                  except ValueError, e:
   47.17                      raise XendConfigError('cpus = %s: %s' % (cfg['cpus'], e))
   47.18  
   47.19 +        if not 'security' in cfg and sxp.child_value(sxp_cfg, 'security'):
   47.20 +            cfg['security'] = sxp.child_value(sxp_cfg, 'security')
   47.21          if 'security' in cfg and not cfg.get('security_label'):
   47.22              secinfo = cfg['security']
   47.23              if isinstance(secinfo, list):
   47.24 @@ -1083,6 +1090,12 @@ class XendConfig(dict):
   47.25  
   47.26              self.device_duplicate_check(dev_type, dev_info, target)
   47.27  
   47.28 +            if dev_type == 'vif':
   47.29 +                if dev_info.get('policy') and dev_info.get('label'):
   47.30 +                    dev_info['security_label'] = "%s:%s:%s" % \
   47.31 +                        (xsconstants.ACM_POLICY_ID,
   47.32 +                         dev_info['policy'],dev_info['label'])
   47.33 +
   47.34              # create uuid if it doesn't exist
   47.35              dev_uuid = dev_info.get('uuid', None)
   47.36              if not dev_uuid:
   47.37 @@ -1113,9 +1126,7 @@ class XendConfig(dict):
   47.38                  # with vfb
   47.39  
   47.40                  other_config = {}
   47.41 -                for key in ['vncunused', 'vncdisplay', 'vnclisten',
   47.42 -                            'vncpasswd', 'type', 'display', 'xauthority',
   47.43 -                            'keymap']:
   47.44 +                for key in XENAPI_CONSOLE_OTHER_CFG:
   47.45                      if key in dev_info:
   47.46                          other_config[key] = dev_info[key]
   47.47                  target['devices'][dev_uuid][1]['other_config'] =  other_config
   47.48 @@ -1157,6 +1168,10 @@ class XendConfig(dict):
   47.49                      network = XendAPIStore.get(
   47.50                          cfg_xenapi.get('network'), 'network')
   47.51                      dev_info['bridge'] = network.get_name_label()
   47.52 +
   47.53 +                if cfg_xenapi.get('security_label'):
   47.54 +                    dev_info['security_label'] = \
   47.55 +                         cfg_xenapi.get('security_label')
   47.56                  
   47.57                  dev_uuid = cfg_xenapi.get('uuid', None)
   47.58                  if not dev_uuid:
   47.59 @@ -1299,6 +1314,13 @@ class XendConfig(dict):
   47.60          for dev_uuid, (dev_type, dev_info) in self['devices'].items():
   47.61              if dev_uuid == console_uuid:
   47.62                  dev_info[key] = value
   47.63 +                # collapse other_config into dev_info for things
   47.64 +                # such as vncpasswd, vncunused, etc.
   47.65 +                if key == 'other_config':
   47.66 +                    for k in XENAPI_CONSOLE_OTHER_CFG:
   47.67 +                        if k in dev_info and k not in value:
   47.68 +                            del dev_info[k]
   47.69 +                    dev_info.update(value)
   47.70                  break
   47.71  
   47.72      def console_get_all(self, protocol):
    48.1 --- a/tools/python/xen/xend/XendDevices.py	Thu Jul 26 14:35:01 2007 -0600
    48.2 +++ b/tools/python/xen/xend/XendDevices.py	Fri Jul 27 08:15:16 2007 -0600
    48.3 @@ -78,6 +78,7 @@ class XendDevices:
    48.4          @param domain: domain this controller is handling devices for.
    48.5          @type domain: XendDomainInfo
    48.6          """
    48.7 -        tpmif.destroy_vtpmstate(domain.getName())
    48.8 +        from xen.xend.XendLogging import log
    48.9 +        tpmif.destroy_vtpmstate(domain.info.get('vtpm_refs'))
   48.10  
   48.11      destroy_device_state = classmethod(destroy_device_state)
    49.1 --- a/tools/python/xen/xend/XendDomain.py	Thu Jul 26 14:35:01 2007 -0600
    49.2 +++ b/tools/python/xen/xend/XendDomain.py	Fri Jul 27 08:15:16 2007 -0600
    49.3 @@ -51,6 +51,7 @@ from xen.xend.xenstore.xstransact import
    49.4  from xen.xend.xenstore.xswatch import xswatch
    49.5  from xen.util import mkdir
    49.6  from xen.xend import uuid
    49.7 +from xen.xend import sxp
    49.8  
    49.9  xc = xen.lowlevel.xc.xc()
   49.10  xoptions = XendOptions.instance() 
   49.11 @@ -688,6 +689,29 @@ class XendDomain:
   49.12          
   49.13          return value
   49.14  
   49.15 +    def set_dev_property_by_uuid(self, klass, dev_uuid, field, value,
   49.16 +                                 old_val = None):
   49.17 +        rc = True
   49.18 +        self.domains_lock.acquire()
   49.19 +
   49.20 +        try:
   49.21 +            try:
   49.22 +                dom = self.get_vm_with_dev_uuid(klass, dev_uuid)
   49.23 +                if dom:
   49.24 +                    o_val = dom.get_dev_property(klass, dev_uuid, field)
   49.25 +                    log.info("o_val=%s, old_val=%s" % (o_val, old_val))
   49.26 +                    if old_val and old_val != o_val:
   49.27 +                        return False
   49.28 +
   49.29 +                    dom.set_dev_property(klass, dev_uuid, field, value)
   49.30 +                    self.managed_config_save(dom)
   49.31 +            except ValueError, e:
   49.32 +                pass
   49.33 +        finally:
   49.34 +            self.domains_lock.release()
   49.35 +
   49.36 +        return rc
   49.37 +
   49.38      def is_valid_vm(self, vm_ref):
   49.39          return (self.get_vm_by_uuid(vm_ref) != None)
   49.40  
   49.41 @@ -945,6 +969,31 @@ class XendDomain:
   49.42          try:
   49.43              try:
   49.44                  domconfig = XendConfig.XendConfig(sxp_obj = config)
   49.45 +                
   49.46 +                domains = self.list('all')
   49.47 +                domains = map(lambda dom: dom.sxpr(), domains)
   49.48 +                for dom in domains:
   49.49 +                    if sxp.child_value(config, 'uuid', None):
   49.50 +                        if domconfig['uuid'] == sxp.child_value(dom, 'uuid'):
   49.51 +                            if domconfig['name_label'] != sxp.child_value(dom, 'name'):
   49.52 +                                raise XendError("Domain UUID '%s' is already used." % \
   49.53 +                                                domconfig['uuid'])
   49.54 +                            else:
   49.55 +                                # Update the config for that existing domain
   49.56 +                                # because it is same name and same UUID.
   49.57 +                                break
   49.58 +                        else:
   49.59 +                            if domconfig['name_label'] == sxp.child_value(dom, 'name'):
   49.60 +                                raise XendError("Domain name '%s' is already used." % \
   49.61 +                                                domconfig['name_label'])
   49.62 +                    else:
   49.63 +                        if domconfig['name_label'] == sxp.child_value(dom, 'name'):
   49.64 +                            # Overwrite the auto-generated UUID by the UUID
   49.65 +                            # of the existing domain. And update the config
   49.66 +                            # for that existing domain.
   49.67 +                            domconfig['uuid'] = sxp.child_value(dom, 'uuid')
   49.68 +                            break
   49.69 +                
   49.70                  dominfo = XendDomainInfo.createDormant(domconfig)
   49.71                  log.debug("Creating new managed domain: %s" %
   49.72                            dominfo.getName())
   49.73 @@ -1164,6 +1213,10 @@ class XendDomain:
   49.74  
   49.75          if dominfo.getDomid() == DOM0_ID:
   49.76              raise XendError("Cannot dump core for privileged domain %s" % domid)
   49.77 +        if dominfo._stateGet() not in (DOM_STATE_PAUSED, DOM_STATE_RUNNING):
   49.78 +            raise VMBadState("Domain '%s' is not started" % domid,
   49.79 +                             POWER_STATE_NAMES[DOM_STATE_PAUSED],
   49.80 +                             POWER_STATE_NAMES[dominfo._stateGet()])
   49.81  
   49.82          try:
   49.83              log.info("Domain core dump requested for domain %s (%d) "
   49.84 @@ -1537,6 +1590,10 @@ class XendDomain:
   49.85          dominfo = self.domain_lookup_nr(domid)
   49.86          if not dominfo:
   49.87              raise XendInvalidDomain(str(domid))
   49.88 +        if dominfo._stateGet() not in (DOM_STATE_RUNNING, DOM_STATE_PAUSED):
   49.89 +            raise VMBadState("Domain '%s' is not started" % domid,
   49.90 +                             POWER_STATE_NAMES[DOM_STATE_RUNNING],
   49.91 +                             POWER_STATE_NAMES[dominfo._stateGet()])
   49.92          if trigger_name.lower() in TRIGGER_TYPE: 
   49.93              trigger = TRIGGER_TYPE[trigger_name.lower()]
   49.94          else:
    50.1 --- a/tools/python/xen/xend/XendDomainInfo.py	Thu Jul 26 14:35:01 2007 -0600
    50.2 +++ b/tools/python/xen/xend/XendDomainInfo.py	Fri Jul 27 08:15:16 2007 -0600
    50.3 @@ -632,16 +632,27 @@ class XendDomainInfo:
    50.4                      ['vcpu_count', self.info['VCPUs_max']]]
    50.5  
    50.6              for i in range(0, self.info['VCPUs_max']):
    50.7 -                info = xc.vcpu_getinfo(self.domid, i)
    50.8 -
    50.9 -                sxpr.append(['vcpu',
   50.10 -                             ['number',   i],
   50.11 -                             ['online',   info['online']],
   50.12 -                             ['blocked',  info['blocked']],
   50.13 -                             ['running',  info['running']],
   50.14 -                             ['cpu_time', info['cpu_time'] / 1e9],
   50.15 -                             ['cpu',      info['cpu']],
   50.16 -                             ['cpumap',   info['cpumap']]])
   50.17 +                if self.domid is not None:
   50.18 +                    info = xc.vcpu_getinfo(self.domid, i)
   50.19 +
   50.20 +                    sxpr.append(['vcpu',
   50.21 +                                 ['number',   i],
   50.22 +                                 ['online',   info['online']],
   50.23 +                                 ['blocked',  info['blocked']],
   50.24 +                                 ['running',  info['running']],
   50.25 +                                 ['cpu_time', info['cpu_time'] / 1e9],
   50.26 +                                 ['cpu',      info['cpu']],
   50.27 +                                 ['cpumap',   info['cpumap']]])
   50.28 +                else:
   50.29 +                    sxpr.append(['vcpu',
   50.30 +                                 ['number',   i],
   50.31 +                                 ['online',   0],
   50.32 +                                 ['blocked',  0],
   50.33 +                                 ['running',  0],
   50.34 +                                 ['cpu_time', 0.0],
   50.35 +                                 ['cpu',      -1],
   50.36 +                                 ['cpumap',   self.info['cpus'] and \
   50.37 +                                              self.info['cpus'] or range(64)]])
   50.38  
   50.39              return sxpr
   50.40  
   50.41 @@ -1111,6 +1122,8 @@ class XendDomainInfo:
   50.42                      self._clearRestart()
   50.43  
   50.44                      if reason == 'suspend':
   50.45 +                        if self._stateGet() != DOM_STATE_SUSPENDED:
   50.46 +                            self.image.saveDeviceModel()
   50.47                          self._stateSet(DOM_STATE_SUSPENDED)
   50.48                          # Don't destroy the domain.  XendCheckpoint will do
   50.49                          # this once it has finished.  However, stop watching
   50.50 @@ -1447,9 +1460,13 @@ class XendDomainInfo:
   50.51          # allocation of 1MB. We free up 2MB here to be on the safe side.
   50.52          balloon.free(2*1024) # 2MB should be plenty
   50.53  
   50.54 -        ssidref = security.calc_dom_ssidref_from_info(self.info)
   50.55 -        if ssidref == 0 and security.on():
   50.56 -            raise VmError('VM is not properly labeled.')
   50.57 +        ssidref = 0
   50.58 +        if security.on():
   50.59 +            ssidref = security.calc_dom_ssidref_from_info(self.info)
   50.60 +            if ssidref == 0:
   50.61 +                raise VmError('VM is not properly labeled.')
   50.62 +            if security.has_authorization(ssidref) == False:
   50.63 +                raise VmError("VM is not authorized to run.")
   50.64  
   50.65          try:
   50.66              self.domid = xc.domain_create(
   50.67 @@ -1594,6 +1611,7 @@ class XendDomainInfo:
   50.68                  log.exception("Removing domain path failed.")
   50.69  
   50.70              self._stateSet(DOM_STATE_HALTED)
   50.71 +            self.domid = None  # Do not push into _stateSet()!
   50.72          finally:
   50.73              self.refresh_shutdown_lock.release()
   50.74  
   50.75 @@ -1752,6 +1770,9 @@ class XendDomainInfo:
   50.76              ResumeDomain(self.domid)
   50.77          except:
   50.78              log.exception("XendDomainInfo.resume: xc.domain_resume failed on domain %s." % (str(self.domid)))
   50.79 +        if self.is_hvm():
   50.80 +            self.image.resumeDeviceModel()
   50.81 +
   50.82  
   50.83      #
   50.84      # Channels for xenstore and console
   50.85 @@ -2419,6 +2440,8 @@ class XendDomainInfo:
   50.86                  config['io_read_kbs'] = 0.0
   50.87                  config['io_write_kbs'] = 0.0                
   50.88  
   50.89 +            config['security_label'] = config.get('security_label', '')
   50.90 +
   50.91          if dev_class == 'vbd':
   50.92  
   50.93              if self._stateGet() not in (XEN_API_VM_POWER_STATE_HALTED,):
   50.94 @@ -2610,6 +2633,9 @@ class XendDomainInfo:
   50.95  
   50.96          return dev_uuid
   50.97  
   50.98 +    def set_console_other_config(self, console_uuid, other_config):
   50.99 +        self.info.console_update(console_uuid, 'other_config', other_config)
  50.100 +
  50.101      def destroy_device_by_uuid(self, dev_type, dev_uuid):
  50.102          if dev_uuid not in self.info['devices']:
  50.103              raise XendError('Device does not exist')
    51.1 --- a/tools/python/xen/xend/XendPIF.py	Thu Jul 26 14:35:01 2007 -0600
    51.2 +++ b/tools/python/xen/xend/XendPIF.py	Fri Jul 27 08:15:16 2007 -0600
    51.3 @@ -24,6 +24,7 @@ from xen.xend import XendAPIStore
    51.4  from xen.xend.XendBase import XendBase
    51.5  from xen.xend.XendPIFMetrics import XendPIFMetrics
    51.6  from xen.xend.XendError import *
    51.7 +from xen.xend import Vifctl
    51.8  
    51.9  log = logging.getLogger("xend.XendPIF")
   51.10  log.setLevel(logging.TRACE)
   51.11 @@ -31,14 +32,17 @@ log.setLevel(logging.TRACE)
   51.12  MAC_RE = re.compile(':'.join(['[0-9a-f]{2}'] * 6))
   51.13  IP_IFACE_RE = re.compile(r'^\d+: (\w+):.*mtu (\d+) .* link/\w+ ([0-9a-f:]+)')
   51.14  
   51.15 +
   51.16 +Vifctl.network('start')
   51.17 +
   51.18  def linux_phy_to_virt(pif_name):
   51.19      return 'eth' + re.sub(r'^[a-z]+', '', pif_name)
   51.20  
   51.21  def linux_get_phy_ifaces():
   51.22      """Returns a list of physical interfaces.
   51.23  
   51.24 -    Identifies PIFs as those that have a interface name starting with 'p'
   51.25 -    and have the fake 'fe:ff:ff:ff:ff:ff' MAC address.
   51.26 +    Identifies PIFs as those that have a interface name starting with
   51.27 +    'peth'.
   51.28  
   51.29      See /etc/xen/scripts/network-bridge for how the devices are renamed.
   51.30  
   51.31 @@ -58,7 +62,7 @@ def linux_get_phy_ifaces():
   51.32                  
   51.33          # resolve pifs' mac addresses
   51.34          for name, mtu, mac in ifaces.values():
   51.35 -            if name[0] == 'p' and mac == 'fe:ff:ff:ff:ff:ff':
   51.36 +            if name.startswith('peth'):
   51.37                  bridged_ifname = linux_phy_to_virt(name)
   51.38                  bridged_if = ifaces.get(bridged_ifname)
   51.39                  if bridged_if:
    52.1 --- a/tools/python/xen/xend/XendVDI.py	Thu Jul 26 14:35:01 2007 -0600
    52.2 +++ b/tools/python/xen/xend/XendVDI.py	Fri Jul 27 08:15:16 2007 -0600
    52.3 @@ -24,6 +24,7 @@ import os
    52.4  from xen.util.xmlrpclib2 import stringify
    52.5  from xmlrpclib import dumps, loads
    52.6  from xen.util import security, xsconstants
    52.7 +from xen.xend.XendError import SecurityError
    52.8  
    52.9  KB = 1024
   52.10  MB = 1024 * 1024
    53.1 --- a/tools/python/xen/xend/XendXSPolicyAdmin.py	Thu Jul 26 14:35:01 2007 -0600
    53.2 +++ b/tools/python/xen/xend/XendXSPolicyAdmin.py	Fri Jul 27 08:15:16 2007 -0600
    53.3 @@ -56,7 +56,10 @@ class XSPolicyAdmin:
    53.4              typ = data[1]
    53.5              try:
    53.6                  if typ == xsconstants.ACM_POLICY_ID:
    53.7 -                    self.xsobjs[ref] = ACMPolicy(name=name, ref=ref)
    53.8 +                    try:
    53.9 +                        self.xsobjs[ref] = ACMPolicy(name=name, ref=ref)
   53.10 +                    except Exception, e:
   53.11 +                        del self.policies[ref]
   53.12                  else:
   53.13                      del self.policies[ref]
   53.14              except Exception, e:
   53.15 @@ -271,6 +274,10 @@ class XSPolicyAdmin:
   53.16                  return pol
   53.17          return None
   53.18  
   53.19 +    def get_hv_loaded_policy_name(self):
   53.20 +        security.refresh_security_policy()
   53.21 +        return security.active_policy
   53.22 +
   53.23      def get_policy_by_name(self, name):
   53.24          for pol in self.xsobjs.values():
   53.25              if pol.get_name() == name:
   53.26 @@ -305,6 +312,18 @@ class XSPolicyAdmin:
   53.27              vmlabel = pol.policy_get_domain_label_by_ssidref_formatted(ssidref)
   53.28          return vmlabel
   53.29  
   53.30 +    def get_stes_of_vmlabel(self, vmlabel_xapi):
   53.31 +        """ Get the list of STEs given a VM label in XenAPI format """
   53.32 +        stes = []
   53.33 +        loadedpol = self.get_loaded_policy()
   53.34 +        if loadedpol:
   53.35 +            tmp = vmlabel_xapi.split(":")
   53.36 +            if len(tmp) != 3:
   53.37 +                return []
   53.38 +            stes = loadedpol.policy_get_stes_of_vmlabel(tmp[2])
   53.39 +        return stes
   53.40 +
   53.41 +
   53.42  poladmin = None
   53.43  
   53.44  def XSPolicyAdminInstance(maxpolicies=1):
    54.1 --- a/tools/python/xen/xend/balloon.py	Thu Jul 26 14:35:01 2007 -0600
    54.2 +++ b/tools/python/xen/xend/balloon.py	Fri Jul 27 08:15:16 2007 -0600
    54.3 @@ -94,7 +94,9 @@ def free(need_mem):
    54.4      # track the last used value so that we don't trigger too many watches.
    54.5  
    54.6      xoptions = XendOptions.instance()
    54.7 +    dom0 = XendDomain.instance().privilegedDomain()
    54.8      xc = xen.lowlevel.xc.xc()
    54.9 +    dom0_start_alloc_mb = get_dom0_current_alloc() / 1024
   54.10  
   54.11      try:
   54.12          dom0_min_mem = xoptions.get_dom0_min_mem() * 1024
   54.13 @@ -133,7 +135,6 @@ def free(need_mem):
   54.14                          new_alloc_mb = new_alloc / 1024  # Round down
   54.15                          log.debug("Balloon: setting dom0 target to %d MiB.",
   54.16                                    new_alloc_mb)
   54.17 -                        dom0 = XendDomain.instance().privilegedDomain()
   54.18                          dom0.setMemoryTarget(new_alloc_mb)
   54.19                          last_new_alloc = new_alloc
   54.20                  # Continue to retry, waiting for ballooning or scrubbing.
   54.21 @@ -158,7 +159,10 @@ def free(need_mem):
   54.22                  (need_mem, dom0_min_mem, dom0_min_mem,
   54.23                   free_mem + scrub_mem + dom0_alloc - dom0_min_mem))
   54.24          else:
   54.25 -            raise VmError('The privileged domain did not balloon!')
   54.26 +            dom0.setMemoryTarget(dom0_start_alloc_mb)
   54.27 +            raise VmError(
   54.28 +                ('Not enough memory is available, and dom0 cannot'
   54.29 +                 ' be shrunk any further'))
   54.30  
   54.31      finally:
   54.32          del xc
    55.1 --- a/tools/python/xen/xend/image.py	Thu Jul 26 14:35:01 2007 -0600
    55.2 +++ b/tools/python/xen/xend/image.py	Fri Jul 27 08:15:16 2007 -0600
    55.3 @@ -20,6 +20,7 @@
    55.4  import os, string
    55.5  import re
    55.6  import math
    55.7 +import time
    55.8  import signal
    55.9  
   55.10  import xen.lowlevel.xc
   55.11 @@ -27,6 +28,7 @@ from xen.xend.XendConstants import REVER
   55.12  from xen.xend.XendError import VmError, XendError, HVMRequired
   55.13  from xen.xend.XendLogging import log
   55.14  from xen.xend.XendOptions import instance as xenopts
   55.15 +from xen.xend.xenstore.xstransact import xstransact
   55.16  from xen.xend.xenstore.xswatch import xswatch
   55.17  from xen.xend import arch
   55.18  
   55.19 @@ -175,6 +177,14 @@ class ImageHandler:
   55.20          """Create device model for the domain (define in subclass if needed)."""
   55.21          pass
   55.22      
   55.23 +    def saveDeviceModel(self):
   55.24 +        """Save device model for the domain (define in subclass if needed)."""
   55.25 +        pass
   55.26 +
   55.27 +    def resumeDeviceModel(self):
   55.28 +        """Unpause device model for the domain (define in subclass if needed)."""
   55.29 +        pass
   55.30 +
   55.31      def destroy(self):
   55.32          """Extra cleanup on domain destroy (define in subclass if needed)."""
   55.33          pass
   55.34 @@ -443,17 +453,34 @@ class HVMImageHandler(ImageHandler):
   55.35          self.vm.storeDom("image/device-model-pid", self.pid)
   55.36          log.info("device model pid: %d", self.pid)
   55.37  
   55.38 +    def saveDeviceModel(self):
   55.39 +        # Signal the device model to pause itself and save its state
   55.40 +        xstransact.Store("/local/domain/0/device-model/%i"
   55.41 +                         % self.vm.getDomid(), ('command', 'save'))
   55.42 +        # Wait for confirmation.  Could do this with a watch but we'd
   55.43 +        # still end up spinning here waiting for the watch to fire. 
   55.44 +        state = ''
   55.45 +        count = 0
   55.46 +        while state != 'paused':
   55.47 +            state = xstransact.Read("/local/domain/0/device-model/%i/state"
   55.48 +                                    % self.vm.getDomid())
   55.49 +            time.sleep(0.1)
   55.50 +            count += 1
   55.51 +            if count > 100:
   55.52 +                raise VmError('Timed out waiting for device model to save')
   55.53 +
   55.54 +    def resumeDeviceModel(self):
   55.55 +        # Signal the device model to resume activity after pausing to save.
   55.56 +        xstransact.Store("/local/domain/0/device-model/%i"
   55.57 +                         % self.vm.getDomid(), ('command', 'continue'))
   55.58 +
   55.59      def recreate(self):
   55.60          self.pid = self.vm.gatherDom(('image/device-model-pid', int))
   55.61  
   55.62      def destroy(self, suspend = False):
   55.63 -        if self.pid:
   55.64 +        if self.pid and not suspend:
   55.65              try:
   55.66 -                sig = signal.SIGKILL
   55.67 -                if suspend:
   55.68 -                    log.info("use sigusr1 to signal qemu %d", self.pid)
   55.69 -                    sig = signal.SIGUSR1
   55.70 -                os.kill(self.pid, sig)
   55.71 +                os.kill(self.pid, signal.SIGKILL)
   55.72              except OSError, exn:
   55.73                  log.exception(exn)
   55.74              try:
   55.75 @@ -464,6 +491,8 @@ class HVMImageHandler(ImageHandler):
   55.76                  # but we can't wait for it because it's not our child.
   55.77                  pass
   55.78              self.pid = None
   55.79 +            state = xstransact.Remove("/local/domain/0/device-model/%i"
   55.80 +                                      % self.vm.getDomid())
   55.81  
   55.82  
   55.83  class IA64_HVM_ImageHandler(HVMImageHandler):
   55.84 @@ -507,6 +536,7 @@ class X86_HVM_ImageHandler(HVMImageHandl
   55.85          return max(4 * (256 * self.vm.getVCpuCount() + 2 * (maxmem_kb / 1024)),
   55.86                     shadow_mem_kb)
   55.87  
   55.88 +
   55.89  class X86_Linux_ImageHandler(LinuxImageHandler):
   55.90  
   55.91      def buildDomain(self):
    56.1 --- a/tools/python/xen/xend/server/SrvServer.py	Thu Jul 26 14:35:01 2007 -0600
    56.2 +++ b/tools/python/xen/xend/server/SrvServer.py	Fri Jul 27 08:15:16 2007 -0600
    56.3 @@ -49,7 +49,6 @@ from threading import Thread
    56.4  from xen.web.httpserver import HttpServer, UnixHttpServer
    56.5  
    56.6  from xen.xend import XendNode, XendOptions, XendAPI
    56.7 -from xen.xend import Vifctl
    56.8  from xen.xend.XendLogging import log
    56.9  from xen.xend.XendClient import XEN_API_SOCKET
   56.10  from xen.xend.XendDomain import instance as xenddomain
   56.11 @@ -101,8 +100,6 @@ class XendServers:
   56.12          if status:
   56.13              fcntl.fcntl(status, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
   56.14          
   56.15 -        Vifctl.network('start')
   56.16 -
   56.17          # Prepare to catch SIGTERM (received when 'xend stop' is executed)
   56.18          # and call each server's cleanup if possible
   56.19          signal.signal(signal.SIGTERM, self.cleanup)
    57.1 --- a/tools/python/xen/xend/server/netif.py	Thu Jul 26 14:35:01 2007 -0600
    57.2 +++ b/tools/python/xen/xend/server/netif.py	Fri Jul 27 08:15:16 2007 -0600
    57.3 @@ -26,6 +26,11 @@ import re
    57.4  
    57.5  from xen.xend import XendOptions
    57.6  from xen.xend.server.DevController import DevController
    57.7 +from xen.xend.XendError import VmError
    57.8 +from xen.util import security
    57.9 +from xen.xend.XendXSPolicyAdmin import XSPolicyAdminInstance
   57.10 +
   57.11 +from xen.xend.XendLogging import log
   57.12  
   57.13  xoptions = XendOptions.instance()
   57.14  
   57.15 @@ -108,6 +113,7 @@ class NetifController(DevController):
   57.16          ipaddr  = config.get('ip')
   57.17          model   = config.get('model')
   57.18          accel   = config.get('accel')
   57.19 +        sec_lab = config.get('security_label')
   57.20  
   57.21          if not typ:
   57.22              typ = xoptions.netback_type
   57.23 @@ -134,6 +140,8 @@ class NetifController(DevController):
   57.24              back['model'] = model
   57.25          if accel:
   57.26              back['accel'] = accel
   57.27 +        if sec_lab:
   57.28 +            back['security_label'] = sec_lab
   57.29  
   57.30          config_path = "device/%s/%d/" % (self.deviceClass, devid)
   57.31          for x in back:
   57.32 @@ -149,9 +157,34 @@ class NetifController(DevController):
   57.33              front = { 'handle' : "%i" % devid,
   57.34                        'mac'    : mac }
   57.35  
   57.36 +        if security.on():
   57.37 +            self.do_access_control(config)
   57.38 +
   57.39          return (devid, back, front)
   57.40  
   57.41  
   57.42 +    def do_access_control(self, config):
   57.43 +        """ do access control checking. Throws a VMError if access is denied """
   57.44 +        domain_label = self.vm.get_security_label()
   57.45 +        stes = XSPolicyAdminInstance().get_stes_of_vmlabel(domain_label)
   57.46 +        res_label = config.get('security_label')
   57.47 +        if len(stes) > 1 or res_label:
   57.48 +            if not res_label:
   57.49 +                raise VmError("'VIF' must be labeled")
   57.50 +            (label, ssidref, policy) = \
   57.51 +                              security.security_label_to_details(res_label)
   57.52 +            if domain_label:
   57.53 +                rc = security.res_security_check_xapi(label, ssidref,
   57.54 +                                                      policy,
   57.55 +                                                      domain_label)
   57.56 +                if rc == 0:
   57.57 +                    raise VmError("VM's access to network device denied. "
   57.58 +                                  "Check labeling")
   57.59 +            else:
   57.60 +                raise VmError("VM must have a security label to access "
   57.61 +                              "network device")
   57.62 +
   57.63 +
   57.64      def getDeviceConfiguration(self, devid):
   57.65          """@see DevController.configuration"""
   57.66  
   57.67 @@ -160,10 +193,12 @@ class NetifController(DevController):
   57.68          config_path = "device/%s/%d/" % (self.deviceClass, devid)
   57.69          devinfo = ()
   57.70          for x in ( 'script', 'ip', 'bridge', 'mac',
   57.71 -                   'type', 'vifname', 'rate', 'uuid', 'model', 'accel'):
   57.72 +                   'type', 'vifname', 'rate', 'uuid', 'model', 'accel',
   57.73 +                   'security_label'):
   57.74              y = self.vm._readVm(config_path + x)
   57.75              devinfo += (y,)
   57.76 -        (script, ip, bridge, mac, typ, vifname, rate, uuid, model, accel) = devinfo
   57.77 +        (script, ip, bridge, mac, typ, vifname, rate, uuid,
   57.78 +         model, accel, security_label) = devinfo
   57.79  
   57.80          if script:
   57.81              result['script'] = script
   57.82 @@ -185,5 +220,7 @@ class NetifController(DevController):
   57.83              result['model'] = model
   57.84          if accel:
   57.85              result['accel'] = accel
   57.86 -            
   57.87 +        if security_label:
   57.88 +            result['security_label'] = security_label
   57.89 +
   57.90          return result
    58.1 --- a/tools/python/xen/xend/server/tpmif.py	Thu Jul 26 14:35:01 2007 -0600
    58.2 +++ b/tools/python/xen/xend/server/tpmif.py	Fri Jul 27 08:15:16 2007 -0600
    58.3 @@ -31,9 +31,10 @@ import re
    58.4  
    58.5  xoptions = XendOptions.instance()
    58.6  
    58.7 -def destroy_vtpmstate(name):
    58.8 +def destroy_vtpmstate(uuids):
    58.9      if os.path.exists(VTPM_DELETE_SCRIPT):
   58.10 -        os.system(VTPM_DELETE_SCRIPT + " " + name)
   58.11 +        for uuid in uuids:
   58.12 +            os.system(VTPM_DELETE_SCRIPT + " " + uuid)
   58.13  
   58.14  class TPMifController(DevController):
   58.15      """TPM interface controller. Handles all TPM devices for a domain.
    59.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    59.2 +++ b/tools/python/xen/xm/activatepolicy.py	Fri Jul 27 08:15:16 2007 -0600
    59.3 @@ -0,0 +1,86 @@
    59.4 +#============================================================================
    59.5 +# This library is free software; you can redistribute it and/or
    59.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
    59.7 +# License as published by the Free Software Foundation.
    59.8 +#
    59.9 +# This library is distributed in the hope that it will be useful,
   59.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
   59.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   59.12 +# Lesser General Public License for more details.
   59.13 +#
   59.14 +# You should have received a copy of the GNU Lesser General Public
   59.15 +# License along with this library; if not, write to the Free Software
   59.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   59.17 +#============================================================================
   59.18 +# Copyright (C) 2007 International Business Machines Corp.
   59.19 +# Author: Stefan Berger <stefanb@us.ibm.com>
   59.20 +#============================================================================
   59.21 +
   59.22 +"""Activate the managed policy of the system.
   59.23 +"""
   59.24 +
   59.25 +import sys
   59.26 +from xen.util import xsconstants
   59.27 +from xml.dom import minidom
   59.28 +from xen.xm.opts import OptionError
   59.29 +from xen.xm import getpolicy
   59.30 +from xen.xm import main as xm_main
   59.31 +from xen.xm.main import server
   59.32 +
   59.33 +def help():
   59.34 +    return """
   59.35 +    Usage: xm activatepolicy [options]
   59.36 +
   59.37 +    Activate the xend-managed policy.
   59.38 +
   59.39 +    The following options are defined:
   59.40 +      --load     Load the policy into the hypervisor.
   59.41 +      --boot     Have the system boot with the policy. Changes the default
   59.42 +                 title in grub.conf.
   59.43 +      --noboot   Remove the policy from the default entry in grub.conf.
   59.44 +    """
   59.45 +
   59.46 +def activate_policy(flags):
   59.47 +    policystate = server.xenapi.XSPolicy.get_xspolicy()
   59.48 +    xs_ref = policystate['xs_ref']
   59.49 +    if int(policystate['type']) == 0 or xs_ref == "":
   59.50 +        print "No policy is installed."
   59.51 +        return
   59.52 +    rc = int(server.xenapi.XSPolicy.activate_xspolicy(xs_ref, flags))
   59.53 +    if rc == flags:
   59.54 +        print "Successfully activated the policy."
   59.55 +    else:
   59.56 +        print "An error occurred trying to activate the policy: %s" % \
   59.57 +              xsconstants.xserr2string(rc)
   59.58 +
   59.59 +def remove_bootpolicy():
   59.60 +    server.xenapi.XSPolicy.rm_xsbootpolicy()
   59.61 +
   59.62 +def main(argv):
   59.63 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   59.64 +        raise OptionError('xm needs to be configured to use the xen-api.')
   59.65 +    flags = 0
   59.66 +    c = 1
   59.67 +
   59.68 +    while c < len(argv):
   59.69 +        if '--boot' == argv[c]:
   59.70 +            flags |= xsconstants.XS_INST_BOOT
   59.71 +        elif '--load' == argv[c]:
   59.72 +            flags |= xsconstants.XS_INST_LOAD
   59.73 +        elif '--noboot' == argv[c]:
   59.74 +            remove_bootpolicy()
   59.75 +        else:
   59.76 +            raise OptionError("Unknown command line option '%s'" % argv[c])
   59.77 +        c += 1
   59.78 +
   59.79 +    if flags != 0:
   59.80 +        activate_policy(flags)
   59.81 +
   59.82 +    getpolicy.getpolicy(False)
   59.83 +
   59.84 +if __name__ == '__main__':
   59.85 +    try:
   59.86 +        main(sys.argv)
   59.87 +    except Exception, e:
   59.88 +        sys.stderr.write('Error: %s\n' % str(e))
   59.89 +        sys.exit(-1)
    60.1 --- a/tools/python/xen/xm/addlabel.py	Thu Jul 26 14:35:01 2007 -0600
    60.2 +++ b/tools/python/xen/xm/addlabel.py	Fri Jul 27 08:15:16 2007 -0600
    60.3 @@ -25,17 +25,30 @@ import sys
    60.4  from xen.util import dictio
    60.5  from xen.util import security
    60.6  from xen.xm.opts import OptionError
    60.7 +from xen.util import xsconstants
    60.8 +from xen.xm import main as xm_main
    60.9 +from xen.xm.main import server
   60.10  
   60.11  def help():
   60.12      return """
   60.13      Format: xm addlabel <label> dom <configfile> [<policy>]
   60.14 -            xm addlabel <label> res <resource> [<policy>]
   60.15 +            xm addlabel <label> mgt <domain name> [<policy type>:<policy>]
   60.16 +            xm addlabel <label> res <resource> [[<policy type>:]<policy>]
   60.17 +            xm addlabel <label> vif-<idx> <domain name> [<policy type>:<policy>]
   60.18      
   60.19      This program adds an acm_label entry into the 'configfile'
   60.20 -    for a domain or to the global resource label file for a
   60.21 -    resource. It derives the policy from the running hypervisor
   60.22 +    for a domain or allows to label a xend-managed domain.
   60.23 +    The global resource label file for is extended with labels for
   60.24 +    resources. It derives the policy from the running hypervisor
   60.25      if it is not given (optional parameter). If a label already
   60.26 -    exists for the given domain or resource, then addlabel fails."""
   60.27 +    exists for the given domain or resource, then addlabel fails.
   60.28 +
   60.29 +    For xend-managed domains, the 'mgt' parameter should be used and
   60.30 +    the 'xm' tool must have been configured to use the xen-api for
   60.31 +    communication with xen. If a policy is provided as last parameter,
   60.32 +    its type must also be given. Currently only one type of policy is
   60.33 +    supported and identified as 'ACM'. An example for a valid string
   60.34 +    is 'ACM:xm-test'. """
   60.35  
   60.36  
   60.37  def validate_config_file(configfile):
   60.38 @@ -66,32 +79,47 @@ def validate_config_file(configfile):
   60.39          return 1
   60.40  
   60.41  
   60.42 -def add_resource_label(label, resource, policyref):
   60.43 +def add_resource_label(label, resource, policyref, policy_type):
   60.44      """Adds a resource label to the global resource label file.
   60.45      """
   60.46 -    # sanity check: make sure this label can be instantiated later on
   60.47 -    ssidref = security.label2ssidref(label, policyref, 'res')
   60.48 +
   60.49 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   60.50 +
   60.51 +        # sanity check: make sure this label can be instantiated later on
   60.52 +        ssidref = security.label2ssidref(label, policyref, 'res')
   60.53 +
   60.54 +        #build canonical resource name
   60.55 +        resource = security.unify_resname(resource,mustexist=False)
   60.56  
   60.57 -    #build canonical resource name
   60.58 -    resource = security.unify_resname(resource)
   60.59 +        # see if this resource is already in the file
   60.60 +        access_control = {}
   60.61 +        fil = security.res_label_filename
   60.62 +        try:
   60.63 +            access_control = dictio.dict_read("resources", fil)
   60.64 +        except:
   60.65 +            print "Resource file not found, creating new file at:"
   60.66 +            print "%s" % (fil)
   60.67  
   60.68 -    # see if this resource is already in the file
   60.69 -    access_control = {}
   60.70 -    file = security.res_label_filename
   60.71 -    try:
   60.72 -        access_control = dictio.dict_read("resources", file)
   60.73 -    except:
   60.74 -        print "Resource file not found, creating new file at:"
   60.75 -        print "%s" % (file)
   60.76 +        if access_control.has_key(resource):
   60.77 +            security.err("This resource is already labeled.")
   60.78  
   60.79 -    if access_control.has_key(resource):
   60.80 -        security.err("This resource is already labeled.")
   60.81 -
   60.82 -    # write the data to file
   60.83 -    new_entry = { resource : tuple([policyref, label]) }
   60.84 -    access_control.update(new_entry)
   60.85 -    dictio.dict_write(access_control, "resources", file)
   60.86 -
   60.87 +        # write the data to file
   60.88 +        new_entry = { resource : tuple([policy_type, policyref, label]) }
   60.89 +        access_control.update(new_entry)
   60.90 +        dictio.dict_write(access_control, "resources", fil)
   60.91 +    else:
   60.92 +        res = [ policy_type, policyref, label ]
   60.93 +        res_xapi = security.format_resource_label(res)
   60.94 +        old = server.xenapi.XSPolicy.get_resource_label(resource)
   60.95 +        if old == "":
   60.96 +            try:
   60.97 +                server.xenapi.XSPolicy.set_resource_label(resource,
   60.98 +                                                          res_xapi,
   60.99 +                                                          "")
  60.100 +            except Exception, e:
  60.101 +                security.err("Could not label this resource: %s" % e)
  60.102 +        else:
  60.103 +            security.err("'%s' is already labeled with '%s'" % (resource,old))
  60.104  
  60.105  def add_domain_label(label, configfile, policyref):
  60.106      # sanity checks: make sure this label can be instantiated later on
  60.107 @@ -109,9 +137,61 @@ def add_domain_label(label, configfile, 
  60.108      config_fd.write(new_label)
  60.109      config_fd.close()
  60.110  
  60.111 +def add_domain_label_xapi(label, domainname, policyref, policy_type):
  60.112 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
  60.113 +        raise OptionError('Xm must be configured to use the xen-api.')
  60.114 +    uuids = server.xenapi.VM.get_by_name_label(domainname)
  60.115 +    if len(uuids) == 0:
  60.116 +        raise OptionError('A VM with that name does not exist.')
  60.117 +    if len(uuids) != 1:
  60.118 +        raise OptionError('There are multiple domains with the same name.')
  60.119 +    uuid = uuids[0]
  60.120 +    sec_lab = "%s:%s:%s" % (policy_type, policyref, label)
  60.121 +    try:
  60.122 +        old_lab = server.xenapi.VM.get_security_label(uuid)
  60.123 +        rc = server.xenapi.VM.set_security_label(uuid, sec_lab, old_lab)
  60.124 +    except:
  60.125 +        rc = -1
  60.126 +    if int(rc) < 0:
  60.127 +        raise OptionError('Could not label domain.')
  60.128 +    else:
  60.129 +        ssidref = int(rc)
  60.130 +        if ssidref != 0:
  60.131 +            print "Set the label of domain '%s' to '%s'. New ssidref = %08x" % \
  60.132 +                  (domainname,label,ssidref)
  60.133 +        else:
  60.134 +            print "Set the label of dormant domain '%s' to '%s'." % \
  60.135 +                  (domainname,label)
  60.136 +
  60.137 +def add_vif_label(label, vmname, idx, policyref, policy_type):
  60.138 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
  60.139 +        raise OptionError('Need to be configure for using xen-api.')
  60.140 +    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
  60.141 +    if len(vm_refs) == 0:
  60.142 +        raise OptionError('A VM with the name %s does not exist.' %
  60.143 +                          vmname)
  60.144 +    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
  60.145 +    if len(vif_refs) <= idx:
  60.146 +        raise OptionError("Bad VIF index.")
  60.147 +    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
  60.148 +    if not vif_ref:
  60.149 +        print "Internal error: VIF does not exist."
  60.150 +    sec_lab = "%s:%s:%s" % (policy_type, policyref, label)
  60.151 +    try:
  60.152 +        old_lab = server.xenapi.VIF.get_security_label(vif_ref)
  60.153 +        rc = server.xenapi.VIF.set_security_label(vif_ref,
  60.154 +                                                  sec_lab, old_lab)
  60.155 +        if int(rc) != 0:
  60.156 +            print "Could not label the VIF."
  60.157 +        else:
  60.158 +            print "Successfully labeled the VIF."
  60.159 +    except Exception, e:
  60.160 +        print "Could not label the VIF: %s" % str(e)
  60.161 +
  60.162  
  60.163  def main(argv):
  60.164      policyref = None
  60.165 +    policy_type = ""
  60.166      if len(argv) not in (4, 5):
  60.167          raise OptionError('Needs either 2 or 3 arguments')
  60.168      
  60.169 @@ -121,6 +201,7 @@ def main(argv):
  60.170          policyref = argv[4]
  60.171      elif security.on():
  60.172          policyref = security.active_policy
  60.173 +        policy_type = xsconstants.ACM_POLICY_ID
  60.174      else:
  60.175          raise OptionError("No active policy. Must specify policy on the "
  60.176                            "command line.")
  60.177 @@ -136,11 +217,41 @@ def main(argv):
  60.178              raise OptionError('Invalid config file')
  60.179          else:
  60.180              add_domain_label(label, configfile, policyref)
  60.181 +    elif argv[2].lower() == "mgt":
  60.182 +        domain = argv[3]
  60.183 +        if policy_type == "":
  60.184 +            tmp = policyref.split(":")
  60.185 +            if len(tmp) != 2:
  60.186 +                raise OptionError("Policy name in wrong format.")
  60.187 +            policy_type, policyref = tmp
  60.188 +        add_domain_label_xapi(label, domain, policyref, policy_type)
  60.189      elif argv[2].lower() == "res":
  60.190          resource = argv[3]
  60.191 -        add_resource_label(label, resource, policyref)
  60.192 +        if policy_type == "":
  60.193 +            tmp = policyref.split(":")
  60.194 +            if len(tmp) == 1:
  60.195 +                policy_type = xsconstants.ACM_POLICY_ID
  60.196 +            elif len(tmp) == 2:
  60.197 +                policy_type, policyref = tmp
  60.198 +            else:
  60.199 +                raise OptionError("Policy name in wrong format.")
  60.200 +        add_resource_label(label, resource, policyref, policy_type)
  60.201 +    elif argv[2].lower().startswith("vif-"):
  60.202 +        try:
  60.203 +            idx = int(argv[2][4:])
  60.204 +            if idx < 0:
  60.205 +                raise
  60.206 +        except:
  60.207 +            raise OptionError("Bad VIF device index.")
  60.208 +        vmname = argv[3]
  60.209 +        if policy_type == "":
  60.210 +            tmp = policyref.split(":")
  60.211 +            if len(tmp) != 2:
  60.212 +                raise OptionError("Policy name in wrong format.")
  60.213 +            policy_type, policyref = tmp
  60.214 +        add_vif_label(label, vmname, idx, policyref, policy_type)
  60.215      else:
  60.216 -        raise OptionError('Need to specify either "dom" or "res" as '
  60.217 +        raise OptionError('Need to specify either "dom", "mgt" or "res" as '
  60.218                            'object to add label to.')
  60.219              
  60.220  if __name__ == '__main__':
  60.221 @@ -149,6 +260,3 @@ if __name__ == '__main__':
  60.222      except Exception, e:
  60.223          sys.stderr.write('Error: %s\n' % str(e))
  60.224          sys.exit(-1)
  60.225 -    
  60.226 -
  60.227 -
    61.1 --- a/tools/python/xen/xm/cfgbootpolicy.py	Thu Jul 26 14:35:01 2007 -0600
    61.2 +++ b/tools/python/xen/xm/cfgbootpolicy.py	Fri Jul 27 08:15:16 2007 -0600
    61.3 @@ -31,7 +31,11 @@ from xen.util.security import policy_dir
    61.4  from xen.util.security import boot_filename, altboot_filename
    61.5  from xen.util.security import any_title_re, xen_kernel_re, any_module_re
    61.6  from xen.util.security import empty_line_re, binary_name_re, policy_name_re
    61.7 +from xen.util import xsconstants
    61.8  from xen.xm.opts import OptionError
    61.9 +from xen.xm import main as xm_main
   61.10 +from xen.xm.main import server
   61.11 +from xen.util.acmpolicy import ACMPolicy
   61.12  
   61.13  def help():
   61.14      return """
   61.15 @@ -144,6 +148,40 @@ def insert_policy(boot_file, alt_boot_fi
   61.16          pass
   61.17      return extended_titles[0]
   61.18  
   61.19 +def cfgbootpolicy_xapi(policy, user_title=None):
   61.20 +    xstype = int(server.xenapi.XSPolicy.get_xstype())
   61.21 +    if xstype & xsconstants.XS_POLICY_ACM == 0:
   61.22 +        raise OptionError("ACM policy not supported on system.")
   61.23 +    if user_title:
   61.24 +        raise OptionError("Only the default title is supported with Xen-API.")
   61.25 +
   61.26 +    policystate = server.xenapi.XSPolicy.get_xspolicy()
   61.27 +    if int(policystate['type']) == 0:
   61.28 +        print "No policy is installed."
   61.29 +        return
   61.30 +
   61.31 +    if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
   61.32 +        print "Unknown policy type '%s'." % policystate['type']
   61.33 +        return
   61.34 +    else:
   61.35 +        xml = policystate['repr']
   61.36 +        xs_ref = policystate['xs_ref']
   61.37 +        if not xml:
   61.38 +            OptionError("No policy installed on system?")
   61.39 +        acmpol = ACMPolicy(xml=xml)
   61.40 +        if acmpol.get_name() != policy:
   61.41 +            raise OptionError("Policy installed on system '%s' does not "
   61.42 +                              "match the requested policy '%s'" %
   61.43 +                              (acmpol.get_name(), policy))
   61.44 +        flags = int(policystate['flags']) | xsconstants.XS_INST_BOOT
   61.45 +        rc = int(server.xenapi.XSPolicy.activate_xspolicy(xs_ref, flags))
   61.46 +        if rc == flags:
   61.47 +            print "Successfully enabled the policy for having the system" \
   61.48 +                  " booted with."
   61.49 +        else:
   61.50 +            print "An error occurred during the operation: %s" % \
   61.51 +                  xsconstants.xserr2string(rc)
   61.52 +
   61.53  
   61.54  def main(argv):
   61.55      user_kver = None
   61.56 @@ -159,24 +197,27 @@ def main(argv):
   61.57      if not policy_name_re.match(policy):
   61.58          raise OptionError("Illegal policy name: '%s'" % policy)
   61.59  
   61.60 -    policy_file = '/'.join([policy_dir_prefix] + policy.split('.'))
   61.61 -    src_binary_policy_file = policy_file + ".bin"
   61.62 -    #check if .bin exists or if policy file exists
   61.63 -    if not os.path.isfile(src_binary_policy_file):
   61.64 -        if not os.path.isfile(policy_file + "-security_policy.xml"):
   61.65 -            raise OptionError("Unknown policy '%s'" % policy)
   61.66 -        else:
   61.67 -            err_msg = "Cannot find binary file for policy '%s'." % policy
   61.68 -            err_msg += " Please use makepolicy to create binary file."
   61.69 -            raise OptionError(err_msg)
   61.70 +    if xm_main.serverType == xm_main.SERVER_XEN_API:
   61.71 +        cfgbootpolicy_xapi(policy)
   61.72 +    else:
   61.73 +        policy_file = '/'.join([policy_dir_prefix] + policy.split('.'))
   61.74 +        src_binary_policy_file = policy_file + ".bin"
   61.75 +        #check if .bin exists or if policy file exists
   61.76 +        if not os.path.isfile(src_binary_policy_file):
   61.77 +            if not os.path.isfile(policy_file + "-security_policy.xml"):
   61.78 +                raise OptionError("Unknown policy '%s'" % policy)
   61.79 +            else:
   61.80 +                err_msg = "Cannot find binary file for policy '%s'." % policy
   61.81 +                err_msg += " Please use makepolicy to create binary file."
   61.82 +                raise OptionError(err_msg)
   61.83      
   61.84 -    dst_binary_policy_file = "/boot/" + policy + ".bin"
   61.85 -    shutil.copyfile(src_binary_policy_file, dst_binary_policy_file)
   61.86 +        dst_binary_policy_file = "/boot/" + policy + ".bin"
   61.87 +        shutil.copyfile(src_binary_policy_file, dst_binary_policy_file)
   61.88      
   61.89 -    entryname = insert_policy(boot_filename, altboot_filename,
   61.90 -                              user_title, policy)
   61.91 -    print "Boot entry '%s' extended and \'%s\' copied to /boot" \
   61.92 -          % (entryname, policy + ".bin")
   61.93 +        entryname = insert_policy(boot_filename, altboot_filename,
   61.94 +                                  user_title, policy)
   61.95 +        print "Boot entry '%s' extended and \'%s\' copied to /boot" \
   61.96 +              % (entryname, policy + ".bin")
   61.97  
   61.98  if __name__ == '__main__':
   61.99      try:
    62.1 --- a/tools/python/xen/xm/create.dtd	Thu Jul 26 14:35:01 2007 -0600
    62.2 +++ b/tools/python/xen/xm/create.dtd	Fri Jul 27 08:15:16 2007 -0600
    62.3 @@ -38,6 +38,7 @@
    62.4                   memory,
    62.5                   vbd*,
    62.6                   vif*,
    62.7 +                 vtpm*,
    62.8                   console*,
    62.9                   platform*,
   62.10                   vcpu_param*,
   62.11 @@ -49,7 +50,8 @@
   62.12                   actions_after_shutdown %NORMAL_EXIT; #REQUIRED 
   62.13                   actions_after_reboot   %NORMAL_EXIT; #REQUIRED
   62.14                   actions_after_crash    %CRASH_BEHAVIOUR; #REQUIRED
   62.15 -                 PCI_bus                CDATA #REQUIRED> 
   62.16 +                 PCI_bus                CDATA #REQUIRED
   62.17 +                 security_label         CDATA #IMPLIED>
   62.18  
   62.19  <!ELEMENT memory EMPTY> 
   62.20  <!ATTLIST memory static_min      CDATA #REQUIRED
   62.21 @@ -72,7 +74,11 @@
   62.22                   mtu             CDATA       #REQUIRED
   62.23                   device          CDATA       #REQUIRED
   62.24                   qos_algorithm_type CDATA    #REQUIRED
   62.25 -                 network         CDATA       #IMPLIED> 
   62.26 +                 network         CDATA       #IMPLIED
   62.27 +                 security_label  CDATA       #IMPLIED>
   62.28 +
   62.29 +<!ELEMENT vtpm   (name*)>
   62.30 +<!ATTLIST vtpm   backend         CDATA #REQUIRED>
   62.31  
   62.32  <!ELEMENT console (other_config*)>
   62.33  <!ATTLIST console protocol       (vt100|rfb|rdp) #REQUIRED>
    63.1 --- a/tools/python/xen/xm/create.py	Thu Jul 26 14:35:01 2007 -0600
    63.2 +++ b/tools/python/xen/xm/create.py	Fri Jul 27 08:15:16 2007 -0600
    63.3 @@ -643,22 +643,12 @@ def configure_security(config, vals):
    63.4                                   ['policy', policy],
    63.5                                   ['label', label] ]
    63.6  
    63.7 -        #ssidref cannot be specified together with access_control
    63.8 -        if sxp.child_value(config, 'ssidref'):
    63.9 -            err("ERROR: SSIDREF and access_control are mutually exclusive but both specified!")
   63.10 -        #else calculate ssidre from label
   63.11 +        #calculate ssidref from label
   63.12          ssidref = security.label2ssidref(label, policy, 'dom')
   63.13          if not ssidref :
   63.14              err("ERROR calculating ssidref from access_control.")
   63.15          security_label = ['security', [ config_access_control, ['ssidref' , ssidref ] ] ]
   63.16          config.append(security_label)
   63.17 -    elif num == 0:
   63.18 -        if hasattr(vals, 'ssidref'):
   63.19 -            if not security.on():
   63.20 -                err("ERROR: Security ssidref specified but no policy active.")
   63.21 -            ssidref = getattr(vals, 'ssidref')
   63.22 -            security_label = ['security', [ [ 'ssidref' , int(ssidref) ] ] ]
   63.23 -            config.append(security_label)
   63.24      elif num > 1:
   63.25          err("VM config error: Multiple access_control definitions!")
   63.26  
   63.27 @@ -714,7 +704,8 @@ def configure_vifs(config_devs, vals):
   63.28  
   63.29          def f(k):
   63.30              if k not in ['backend', 'bridge', 'ip', 'mac', 'script', 'type',
   63.31 -                         'vifname', 'rate', 'model', 'accel']:
   63.32 +                         'vifname', 'rate', 'model', 'accel',
   63.33 +                         'policy', 'label']:
   63.34                  err('Invalid vif option: ' + k)
   63.35  
   63.36              config_vif.append([k, d[k]])
   63.37 @@ -1231,13 +1222,13 @@ def config_security_check(config, verbos
   63.38  
   63.39          except security.ACMError:
   63.40              print "   %s: DENIED" % (resource)
   63.41 -            (res_label, res_policy) = security.get_res_label(resource)
   63.42 +            (poltype, res_label, res_policy) = security.get_res_label(resource)
   63.43              if not res_label:
   63.44                  res_label = ""
   63.45 -            print "   --> res: %s (%s)" % (str(res_label),
   63.46 -                                           str(res_policy))
   63.47 -            print "   --> dom: %s (%s)" % (str(domain_label),
   63.48 -                                           str(domain_policy))
   63.49 +            print "   --> res: %s (%s:%s)" % (str(res_label),
   63.50 +                                           str(poltype), str(res_policy))
   63.51 +            print "   --> dom: %s (%s:%s)" % (str(domain_label),
   63.52 +                                           str(poltype), str(domain_policy))
   63.53  
   63.54              answer = 0
   63.55  
    64.1 --- a/tools/python/xen/xm/getlabel.py	Thu Jul 26 14:35:01 2007 -0600
    64.2 +++ b/tools/python/xen/xm/getlabel.py	Fri Jul 27 08:15:16 2007 -0600
    64.3 @@ -21,14 +21,20 @@
    64.4  import sys, os, re
    64.5  from xen.util import dictio
    64.6  from xen.util import security
    64.7 +from xen.util import xsconstants
    64.8  from xen.xm.opts import OptionError
    64.9 +from xen.xm import main as xm_main
   64.10 +from xen.xm.main import server
   64.11  
   64.12  def help():
   64.13      return """
   64.14      Usage: xm getlabel dom <configfile>
   64.15 +           xm getlabel mgt <domain name>
   64.16             xm getlabel res <resource>
   64.17 +           xm getlabel vif-<idx> <vmname>
   64.18             
   64.19 -    This program shows the label for a domain or resource."""
   64.20 +    This program shows the label for a domain, resource or virtual network
   64.21 +    interface of a Xend-managed domain."""
   64.22  
   64.23  def get_resource_label(resource):
   64.24      """Gets the resource label
   64.25 @@ -37,17 +43,24 @@ def get_resource_label(resource):
   64.26      resource = security.unify_resname(resource)
   64.27  
   64.28      # read in the resource file
   64.29 -    file = security.res_label_filename
   64.30 +    fil = security.res_label_filename
   64.31      try:
   64.32 -        access_control = dictio.dict_read("resources", file)
   64.33 +        access_control = dictio.dict_read("resources", fil)
   64.34      except:
   64.35          raise OptionError("Resource label file not found")
   64.36  
   64.37      # get the entry and print label
   64.38      if access_control.has_key(resource):
   64.39 -        policy = access_control[resource][0]
   64.40 -        label = access_control[resource][1]
   64.41 -        print "policy="+policy+",label="+label
   64.42 +        tmp = access_control[resource]
   64.43 +        if len(tmp) == 2:
   64.44 +            policy, label = tmp
   64.45 +            policytype = xsconstants.ACM_POLICY_ID
   64.46 +        elif len(tmp) == 3:
   64.47 +            policytype, policy, label = tmp
   64.48 +        else:
   64.49 +            raise security.ACMError("Resource not properly labeled. "
   64.50 +                                    "Please relabel the resource.")
   64.51 +        print policytype+":"+policy+":"+label
   64.52      else:
   64.53          raise security.ACMError("Resource not labeled")
   64.54  
   64.55 @@ -89,8 +102,35 @@ def get_domain_label(configfile):
   64.56      data = data.strip()
   64.57      data = data.lstrip("[\'")
   64.58      data = data.rstrip("\']")
   64.59 -    print data
   64.60 +    print "policytype=%s," % xsconstants.ACM_POLICY_ID + data
   64.61  
   64.62 +def get_vif_label(vmname, idx):
   64.63 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   64.64 +        raise OptionError('xm needs to be configure to use the xen-api.')
   64.65 +    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
   64.66 +    if len(vm_refs) == 0:
   64.67 +        raise OptionError('A VM with the name %s does not exist.' %
   64.68 +                          vmname)
   64.69 +    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
   64.70 +    if len(vif_refs) <= idx:
   64.71 +        raise OptionError("Bad VIF index.")
   64.72 +    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
   64.73 +    if not vif_ref:
   64.74 +        print "No VIF with this UUID."
   64.75 +    sec_lab = server.xenapi.VIF.get_security_label(vif_ref)
   64.76 +    print "%s" % sec_lab
   64.77 +
   64.78 +def get_domain_label_xapi(domainname):
   64.79 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   64.80 +        raise OptionError('xm needs to be configure to use the xen-api.')
   64.81 +    uuids = server.xenapi.VM.get_by_name_label(domainname)
   64.82 +    if len(uuids) == 0:
   64.83 +        raise OptionError('A VM with that name does not exist.')
   64.84 +    if len(uuids) != 1:
   64.85 +        raise OptionError('There are multiple domains with the same name.')
   64.86 +    uuid = uuids[0]
   64.87 +    sec_lab = server.xenapi.VM.get_security_label(uuid)
   64.88 +    print "%s" %sec_lab
   64.89  
   64.90  def main(argv):
   64.91      if len(argv) != 3:
   64.92 @@ -99,11 +139,24 @@ def main(argv):
   64.93      if argv[1].lower() == "dom":
   64.94          configfile = argv[2]
   64.95          get_domain_label(configfile)
   64.96 +    elif argv[1].lower() == "mgt":
   64.97 +        domainname = argv[2]
   64.98 +        get_domain_label_xapi(domainname)
   64.99      elif argv[1].lower() == "res":
  64.100          resource = argv[2]
  64.101          get_resource_label(resource)
  64.102 +    elif argv[1].lower().startswith("vif-"):
  64.103 +        try:
  64.104 +            idx = int(argv[1][4:])
  64.105 +            if idx < 0:
  64.106 +                raise
  64.107 +        except:
  64.108 +            raise OptionError("Bad VIF device index.")
  64.109 +        vmname = argv[2]
  64.110 +        get_vif_label(vmname, idx)
  64.111      else:
  64.112 -        raise OptionError('First subcommand argument must be "dom" or "res"')
  64.113 +        raise OptionError('First subcommand argument must be "dom"'
  64.114 +                          ', "mgt" or "res"')
  64.115  
  64.116  if __name__ == '__main__':
  64.117      try:
  64.118 @@ -111,6 +164,4 @@ if __name__ == '__main__':
  64.119      except Exception, e:
  64.120          sys.stderr.write('Error: %s\n' % str(e))
  64.121          sys.exit(-1)
  64.122 -        
  64.123  
  64.124 -
    65.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    65.2 +++ b/tools/python/xen/xm/getpolicy.py	Fri Jul 27 08:15:16 2007 -0600
    65.3 @@ -0,0 +1,94 @@
    65.4 +#============================================================================
    65.5 +# This library is free software; you can redistribute it and/or
    65.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
    65.7 +# License as published by the Free Software Foundation.
    65.8 +#
    65.9 +# This library is distributed in the hope that it will be useful,
   65.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
   65.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   65.12 +# Lesser General Public License for more details.
   65.13 +#
   65.14 +# You should have received a copy of the GNU Lesser General Public
   65.15 +# License along with this library; if not, write to the Free Software
   65.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   65.17 +#============================================================================
   65.18 +# Copyright (C) 2007 International Business Machines Corp.
   65.19 +# Author: Stefan Berger <stefanb@us.ibm.com>
   65.20 +#============================================================================
   65.21 +
   65.22 +"""Get the managed policy of the system.
   65.23 +"""
   65.24 +
   65.25 +import sys
   65.26 +from xen.util import xsconstants
   65.27 +from xml.dom import minidom
   65.28 +from xen.xm.opts import OptionError
   65.29 +from xen.util.acmpolicy import ACMPolicy
   65.30 +from xen.xm import main as xm_main
   65.31 +from xen.xm.main import server
   65.32 +
   65.33 +def help():
   65.34 +    return """
   65.35 +    Usage: xm getpolicy [options]
   65.36 +
   65.37 +    The following options are defined
   65.38 +      --dumpxml     Display the XML of the policy
   65.39 +
   65.40 +    Get the policy managed by xend."""
   65.41 +
   65.42 +def getpolicy(dumpxml):
   65.43 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   65.44 +        raise OptionError('xm needs to be configured to use the xen-api.')
   65.45 +    types = []
   65.46 +    xstype = int(server.xenapi.XSPolicy.get_xstype())
   65.47 +    if xstype & xsconstants.XS_POLICY_ACM:
   65.48 +        types.append("ACM")
   65.49 +        xstype ^= xsconstants.XS_POLICY_ACM
   65.50 +    if xstype != 0:
   65.51 +        types.append("unsupported (%08x)" % xstype)
   65.52 +    print "Supported security subsystems   : %s \n" % ", ".join(types)
   65.53 +
   65.54 +    policystate = server.xenapi.XSPolicy.get_xspolicy()
   65.55 +    if int(policystate['type']) == 0:
   65.56 +        print "No policy is installed."
   65.57 +        return
   65.58 +    if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
   65.59 +        print "Unknown policy type '%s'." % policystate['type']
   65.60 +    else:
   65.61 +        xml = policystate['repr']
   65.62 +        acmpol = None
   65.63 +        if xml:
   65.64 +            acmpol = ACMPolicy(xml=xml)
   65.65 +        print "Policy installed on the system:"
   65.66 +        if acmpol:
   65.67 +            print "Policy name           : %s" % acmpol.get_name()
   65.68 +        print "Policy type           : %s" % xsconstants.ACM_POLICY_ID
   65.69 +        print "Reference             : %s" % policystate['xs_ref']
   65.70 +        print "Version of XML policy : %s" % policystate['version']
   65.71 +        state = []
   65.72 +        flags = int(policystate['flags'])
   65.73 +        if flags & xsconstants.XS_INST_LOAD:
   65.74 +            state.append("loaded")
   65.75 +        if flags & xsconstants.XS_INST_BOOT:
   65.76 +            state.append("system booted with")
   65.77 +        print "State of the policy   : %s" % ", ".join(state)
   65.78 +        if dumpxml:
   65.79 +            xml = policystate['repr']
   65.80 +            if xml:
   65.81 +                dom = minidom.parseString(xml.encode("utf-8"))
   65.82 +                print "%s" % dom.toprettyxml(indent="   ",newl="\n")
   65.83 +
   65.84 +def main(argv):
   65.85 +    dumpxml = False
   65.86 +
   65.87 +    if '--dumpxml' in argv:
   65.88 +        dumpxml = True
   65.89 +
   65.90 +    getpolicy(dumpxml)
   65.91 +
   65.92 +if __name__ == '__main__':
   65.93 +    try:
   65.94 +        main(sys.argv)
   65.95 +    except Exception, e:
   65.96 +        sys.stderr.write('Error: %s\n' % str(e))
   65.97 +        sys.exit(-1)
    66.1 --- a/tools/python/xen/xm/labels.py	Thu Jul 26 14:35:01 2007 -0600
    66.2 +++ b/tools/python/xen/xm/labels.py	Fri Jul 27 08:15:16 2007 -0600
    66.3 @@ -24,6 +24,10 @@ import string
    66.4  from xen.util.security import ACMError, err, list_labels, active_policy
    66.5  from xen.util.security import vm_label_re, res_label_re, all_label_re
    66.6  from xen.xm.opts import OptionError
    66.7 +from xen.util.acmpolicy import ACMPolicy
    66.8 +from xen.util import xsconstants
    66.9 +from xen.xm.main import server
   66.10 +from xen.xm import main as xm_main
   66.11  
   66.12  
   66.13  def help():
   66.14 @@ -48,6 +52,12 @@ def main(argv):
   66.15          else:
   66.16              raise OptionError('Unrecognised option: %s' % arg)
   66.17  
   66.18 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   66.19 +        labels(policy, ptype)
   66.20 +    else:
   66.21 +        labels_xapi(policy, ptype)
   66.22 +
   66.23 +def labels(policy, ptype):
   66.24      if not policy:
   66.25          policy = active_policy
   66.26          if active_policy in ['NULL', 'INACTIVE', 'DEFAULT']:
   66.27 @@ -73,7 +83,30 @@ def main(argv):
   66.28      except:
   66.29          traceback.print_exc(limit = 1)
   66.30  
   66.31 +def labels_xapi(policy, ptype):
   66.32 +    policystate = server.xenapi.XSPolicy.get_xspolicy()
   66.33 +    if int(policystate['type']) == xsconstants.XS_POLICY_ACM:
   66.34 +        acmpol = ACMPolicy(xml=policystate['repr'])
   66.35 +        if policy and policy != acmpol.get_name():
   66.36 +            print "Warning: '%s' is not the currently loaded policy." % policy
   66.37 +            return labels(policy, ptype)
   66.38 +        names1 = []
   66.39 +        names2 = []
   66.40 +        if not ptype or ptype == 'dom' or ptype == 'any':
   66.41 +            names1 = acmpol.policy_get_virtualmachinelabel_names()
   66.42 +        if ptype == 'res' or ptype == 'any':
   66.43 +            names2 = acmpol.policy_get_resourcelabel_names()
   66.44 +        if len(names1) > 0:
   66.45 +            names = set(names1)
   66.46 +            names.union(names2)
   66.47 +        else:
   66.48 +            names = set(names2)
   66.49 +        for n in names:
   66.50 +            print n
   66.51 +    elif int(policystate['type']) == 0:
   66.52 +        print "No policy installed on the system."
   66.53 +    else:
   66.54 +        print "Unsupported type of policy installed on the system."
   66.55 +
   66.56  if __name__ == '__main__':
   66.57      main(sys.argv)
   66.58 -
   66.59 -
    67.1 --- a/tools/python/xen/xm/loadpolicy.py	Thu Jul 26 14:35:01 2007 -0600
    67.2 +++ b/tools/python/xen/xm/loadpolicy.py	Fri Jul 27 08:15:16 2007 -0600
    67.3 @@ -22,6 +22,11 @@ import sys
    67.4  import traceback
    67.5  from xen.util.security import ACMError, err, load_policy
    67.6  from xen.xm.opts import OptionError
    67.7 +from xen.xm import main as xm_main
    67.8 +from xen.util import xsconstants
    67.9 +from xen.xm.activatepolicy import activate_policy
   67.10 +from xen.xm.main import server
   67.11 +from xen.util.acmpolicy import ACMPolicy
   67.12  
   67.13  def help():
   67.14      return """Load the compiled binary (.bin) policy into the running
   67.15 @@ -30,8 +35,31 @@ def help():
   67.16  def main(argv):
   67.17      if len(argv) != 2:
   67.18          raise OptionError('No policy defined')
   67.19 -    
   67.20 -    load_policy(argv[1])
   67.21 +    if xm_main.serverType == xm_main.SERVER_XEN_API:
   67.22 +        policy = argv[1]
   67.23 +        print "This command is deprecated for use with Xen-API " \
   67.24 +              "configuration. Consider using\n'xm activatepolicy'."
   67.25 +        policystate = server.xenapi.XSPolicy.get_xspolicy()
   67.26 +        if int(policystate['type']) == 0:
   67.27 +            print "No policy is installed."
   67.28 +            return
   67.29 +
   67.30 +        if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
   67.31 +            print "Unknown policy type '%s'." % policystate['type']
   67.32 +            return
   67.33 +        else:
   67.34 +            xml = policystate['repr']
   67.35 +            xs_ref = policystate['xs_ref']
   67.36 +            if not xml:
   67.37 +                OptionError("No policy installed on system?")
   67.38 +            acmpol = ACMPolicy(xml=xml)
   67.39 +            if acmpol.get_name() != policy:
   67.40 +                OptionError("Policy installed on system '%s' does not match"\
   67.41 +                            " the request policy '%s'" % \
   67.42 +                            (acmpol.get_name(), policy))
   67.43 +            activate_policy(xsconstants.XS_INST_LOAD)
   67.44 +    else:
   67.45 +        load_policy(argv[1])
   67.46  
   67.47  if __name__ == '__main__':
   67.48      try:
    68.1 --- a/tools/python/xen/xm/main.py	Thu Jul 26 14:35:01 2007 -0600
    68.2 +++ b/tools/python/xen/xm/main.py	Fri Jul 27 08:15:16 2007 -0600
    68.3 @@ -50,6 +50,7 @@ from xen.xend.XendConstants import *
    68.4  from xen.xm.opts import OptionError, Opts, wrap, set_true
    68.5  from xen.xm import console
    68.6  from xen.util.xmlrpcclient import ServerProxy
    68.7 +from xen.util.security import ACMError
    68.8  
    68.9  import XenAPI
   68.10  
   68.11 @@ -171,11 +172,12 @@ SUBCOMMAND_HELP = {
   68.12  
   68.13      # security
   68.14  
   68.15 -    'addlabel'      :  ('<label> {dom <ConfigFile>|res <resource>} [<policy>]',
   68.16 +    'addlabel'      :  ('<label> {dom <ConfigFile>|res <resource>|mgt <managed domain>}\n'
   68.17 +                        '                   [<policy>]',
   68.18                          'Add security label to domain.'),
   68.19 -    'rmlabel'       :  ('{dom <ConfigFile>|res <Resource>}',
   68.20 +    'rmlabel'       :  ('{dom <ConfigFile>|res <Resource>|mgt<managed domain>}',
   68.21                          'Remove a security label from domain.'),
   68.22 -    'getlabel'      :  ('{dom <ConfigFile>|res <Resource>}',
   68.23 +    'getlabel'      :  ('{dom <ConfigFile>|res <Resource>|mgt <managed domain>}',
   68.24                          'Show security label for domain or resource.'),
   68.25      'dry-run'       :  ('<ConfigFile>',
   68.26                          'Test if a domain can access its resources.'),
   68.27 @@ -186,6 +188,10 @@ SUBCOMMAND_HELP = {
   68.28      'loadpolicy'    :  ('<policy.bin>', 'Load binary policy into hypervisor.'),
   68.29      'makepolicy'    :  ('<policy>', 'Build policy and create .bin/.map '
   68.30                          'files.'),
   68.31 +    'setpolicy'     :  ('<policytype> <policyfile> [options]',
   68.32 +                        'Set the policy of the system.'),
   68.33 +    'getpolicy'     :  ('[options]', 'Get the policy of the system.'),
   68.34 +    'activatepolicy':  ('[options]', 'Activate the xend-managed policy.'),
   68.35      'labels'        :  ('[policy] [type=dom|res|any]',
   68.36                          'List <type> labels for (active) policy.'),
   68.37      'serve'         :  ('', 'Proxy Xend XMLRPC over stdio.'),
   68.38 @@ -343,6 +349,9 @@ acm_commands = [
   68.39      "loadpolicy",
   68.40      "cfgbootpolicy",
   68.41      "dumppolicy",
   68.42 +    "activatepolicy",
   68.43 +    "setpolicy",
   68.44 +    "getpolicy",
   68.45      ]
   68.46  
   68.47  all_commands = (domain_commands + host_commands + scheduler_commands +
   68.48 @@ -861,13 +870,13 @@ def parse_doms_info(info):
   68.49          'up_time'  : up_time
   68.50          }
   68.51  
   68.52 -    # We're not supporting security stuff just yet via XenAPI
   68.53 -
   68.54 -    if serverType != SERVER_XEN_API:
   68.55 -        from xen.util import security
   68.56 -        parsed_info['seclabel'] = security.get_security_printlabel(info)
   68.57 +    security_label = get_info('security_label', str, '')
   68.58 +    tmp = security_label.split(":")
   68.59 +    if len(tmp) != 3:
   68.60 +        seclabel = ""
   68.61      else:
   68.62 -        parsed_info['seclabel'] = ""
   68.63 +        seclabel = tmp[2]
   68.64 +    parsed_info['seclabel'] = seclabel
   68.65  
   68.66      if serverType == SERVER_XEN_API:
   68.67          parsed_info['mem'] = get_info('memory_actual', int, 0) / 1024
   68.68 @@ -925,28 +934,26 @@ def xm_brief_list(doms):
   68.69          print format % d
   68.70  
   68.71  def xm_label_list(doms):
   68.72 -    print '%-32s %5s %5s %5s %5s %9s %-8s' % \
   68.73 +    print '%-32s %5s %5s %5s %10s %9s %-8s' % \
   68.74            ('Name', 'ID', 'Mem', 'VCPUs', 'State', 'Time(s)', 'Label')
   68.75      
   68.76      output = []
   68.77      format = '%(name)-32s %(domid)5s %(mem)5d %(vcpus)5d %(state)10s ' \
   68.78               '%(cpu_time)8.1f %(seclabel)9s'
   68.79  
   68.80 -    if serverType != SERVER_XEN_API:
   68.81 -        from xen.util import security
   68.82 +    from xen.util import security
   68.83          
   68.84 -        for dom in doms:
   68.85 -            d = parse_doms_info(dom)
   68.86 +    for dom in doms:
   68.87 +        d = parse_doms_info(dom)
   68.88 +        if security.active_policy not in ['INACTIVE', 'NULL', 'DEFAULT']:
   68.89 +            if not d['seclabel']:
   68.90 +                d['seclabel'] = 'ERROR'
   68.91 +        elif security.active_policy in ['DEFAULT']:
   68.92 +            d['seclabel'] = 'DEFAULT'
   68.93 +        else:
   68.94 +            d['seclabel'] = 'INACTIVE'
   68.95  
   68.96 -            if security.active_policy not in ['INACTIVE', 'NULL', 'DEFAULT']:
   68.97 -                if not d['seclabel']:
   68.98 -                    d['seclabel'] = 'ERROR'
   68.99 -            elif security.active_policy in ['DEFAULT']:
  68.100 -                d['seclabel'] = 'DEFAULT'
  68.101 -            else:
  68.102 -                d['seclabel'] = 'INACTIVE'
  68.103 -
  68.104 -            output.append((format % d, d['seclabel']))
  68.105 +        output.append((format % d, d['seclabel']))
  68.106          
  68.107      #sort by labels
  68.108      output.sort(lambda x,y: cmp( x[1].lower(), y[1].lower()))
  68.109 @@ -1016,13 +1023,13 @@ def xm_vcpu_list(args):
  68.110          if args:
  68.111              dominfo = map(server.xend.domain.getVCPUInfo, args)
  68.112          else:
  68.113 -            doms = server.xend.domains(False)
  68.114 +            doms = server.xend.domains_with_state(False, 'all', False)
  68.115              dominfo = map(server.xend.domain.getVCPUInfo, doms)
  68.116  
  68.117      print '%-32s %5s %5s %5s %5s %9s %s' % \
  68.118            ('Name', 'ID', 'VCPU', 'CPU', 'State', 'Time(s)', 'CPU Affinity')
  68.119  
  68.120 -    format = '%(name)-32s %(domid)5d %(number)5d %(c)5s %(s)5s ' \
  68.121 +    format = '%(name)-32s %(domid)5s %(number)5d %(c)5s %(s)5s ' \
  68.122               ' %(cpu_time)8.1f %(cpumap)s'
  68.123  
  68.124      for dom in dominfo:
  68.125 @@ -1091,8 +1098,12 @@ def xm_vcpu_list(args):
  68.126  
  68.127              return format_pairs(list_to_rangepairs(cpumap))
  68.128  
  68.129 -        name  =     get_info('name')
  68.130 -        domid = int(get_info('domid'))
  68.131 +        name  = get_info('name')
  68.132 +        domid = get_info('domid')
  68.133 +        if domid is not None:
  68.134 +            domid = str(domid)
  68.135 +        else:
  68.136 +            domid = ''
  68.137  
  68.138          for vcpu in sxp.children(dom, 'vcpu'):
  68.139              def vinfo(n, t):
  68.140 @@ -1106,7 +1117,10 @@ def xm_vcpu_list(args):
  68.141              running  = vinfo('running',  int)
  68.142              blocked  = vinfo('blocked',  int)
  68.143  
  68.144 -            if online:
  68.145 +            if cpu < 0:
  68.146 +                c = ''
  68.147 +                s = ''
  68.148 +            elif online:
  68.149                  c = str(cpu)
  68.150                  if running:
  68.151                      s = 'r'
  68.152 @@ -1118,8 +1132,8 @@ def xm_vcpu_list(args):
  68.153                      s += '-'
  68.154                  s += '-'
  68.155              else:
  68.156 -                c = "-"
  68.157 -                s = "--p"
  68.158 +                c = '-'
  68.159 +                s = '--p'
  68.160  
  68.161              print format % locals()
  68.162  
  68.163 @@ -1722,14 +1736,16 @@ def xm_uptime(args):
  68.164          if k in ['-s', '--short']:
  68.165              short_mode = 1
  68.166  
  68.167 -    doms = getDomains(params, 'running')
  68.168 +    doms = getDomains(params, 'all')
  68.169  
  68.170      if short_mode == 0:
  68.171          print '%-33s %4s %s ' % ('Name','ID','Uptime')
  68.172  
  68.173      for dom in doms:
  68.174          d = parse_doms_info(dom)
  68.175 -        if int(d['domid']) > 0:
  68.176 +        if d['domid'] == '':
  68.177 +            uptime = 0
  68.178 +        elif int(d['domid']) > 0:
  68.179              uptime = int(round(d['up_time']))
  68.180          else:
  68.181              f=open('/proc/uptime', 'r')
  68.182 @@ -1989,16 +2005,24 @@ def xm_block_list(args):
  68.183                     % ni)
  68.184  
  68.185  def xm_vtpm_list(args):
  68.186 -    xenapi_unsupported()
  68.187      (use_long, params) = arg_check_for_resource_list(args, "vtpm-list")
  68.188  
  68.189      dom = params[0]
  68.190 +
  68.191 +    if serverType == SERVER_XEN_API:
  68.192 +        vtpm_refs = server.xenapi.VM.get_VTPMs(get_single_vm(dom))
  68.193 +        vtpm_properties = \
  68.194 +            map(server.xenapi.VTPM.get_runtime_properties, vtpm_refs)
  68.195 +        devs = map(lambda (handle, properties): [handle, map2sxp(properties)],
  68.196 +                   zip(range(len(vtpm_properties)), vtpm_properties))
  68.197 +    else:
  68.198 +        devs = server.xend.domain.getDeviceSxprs(dom, 'vtpm')
  68.199 +
  68.200      if use_long:
  68.201 -        devs = server.xend.domain.getDeviceSxprs(dom, 'vtpm')
  68.202          map(PrettyPrint.prettyprint, devs)
  68.203      else:
  68.204          hdr = 0
  68.205 -        for x in server.xend.domain.getDeviceSxprs(dom, 'vtpm'):
  68.206 +        for x in devs:
  68.207              if hdr == 0:
  68.208                  print 'Idx  BE handle state evt-ch ring-ref BE-path'
  68.209                  hdr = 1
  68.210 @@ -2029,18 +2053,6 @@ def parse_block_configuration(args):
  68.211      if len(args) == 5:
  68.212          vbd.append(['backend', args[4]])
  68.213  
  68.214 -    if serverType != SERVER_XEN_API:
  68.215 -        # verify that policy permits attaching this resource
  68.216 -        from xen.util import security
  68.217 -    
  68.218 -        if security.on():
  68.219 -            dominfo = server.xend.domain(dom)
  68.220 -            label = security.get_security_printlabel(dominfo)
  68.221 -        else:
  68.222 -            label = None
  68.223 -
  68.224 -        security.res_security_check(args[1], label)
  68.225 -
  68.226      return (dom, vbd)
  68.227  
  68.228  
  68.229 @@ -2440,6 +2452,9 @@ IMPORTED_COMMANDS = [
  68.230      'getlabel',
  68.231      'dry-run',
  68.232      'resources',
  68.233 +    'getpolicy',
  68.234 +    'setpolicy',
  68.235 +    'activatepolicy',
  68.236      ]
  68.237  
  68.238  for c in IMPORTED_COMMANDS:
  68.239 @@ -2563,6 +2578,8 @@ def _run_cmd(cmd, cmd_name, args):
  68.240          print e.usage
  68.241      except XenAPIUnsupportedException, e:
  68.242          err(str(e))
  68.243 +    except ACMError, e:
  68.244 +        err(str(e))
  68.245      except Exception, e:
  68.246          if serverType != SERVER_XEN_API:
  68.247             from xen.util import security
    69.1 --- a/tools/python/xen/xm/makepolicy.py	Thu Jul 26 14:35:01 2007 -0600
    69.2 +++ b/tools/python/xen/xm/makepolicy.py	Fri Jul 27 08:15:16 2007 -0600
    69.3 @@ -20,7 +20,10 @@
    69.4  import sys
    69.5  import traceback
    69.6  from xen.util.security import ACMError, err, make_policy
    69.7 +from xen.util import xsconstants
    69.8  from xen.xm.opts import OptionError
    69.9 +from xen.xm import main as xm_main
   69.10 +from xen.xm.setpolicy import setpolicy
   69.11  
   69.12  def usage():
   69.13      print "\nUsage: xm makepolicy <policy>\n"
   69.14 @@ -32,8 +35,13 @@ def usage():
   69.15  def main(argv):
   69.16      if len(argv) != 2:
   69.17          raise OptionError('No XML policy file specified')
   69.18 -
   69.19 -    make_policy(argv[1])
   69.20 +    if xm_main.serverType == xm_main.SERVER_XEN_API:
   69.21 +        print "This command is deprecated for use with Xen-API " \
   69.22 +              "configuration. Consider using\n'xm setpolicy'."
   69.23 +        setpolicy(xsconstants.ACM_POLICY_ID, argv[1],
   69.24 +                  xsconstants.XS_INST_LOAD, True)
   69.25 +    else:
   69.26 +        make_policy(argv[1])
   69.27  
   69.28  if __name__ == '__main__':
   69.29      try:
   69.30 @@ -41,5 +49,3 @@ if __name__ == '__main__':
   69.31      except Exception, e:
   69.32          sys.stderr.write('Error: %s\n' % str(e))
   69.33          sys.exit(-1)
   69.34 -
   69.35 -
    70.1 --- a/tools/python/xen/xm/resources.py	Thu Jul 26 14:35:01 2007 -0600
    70.2 +++ b/tools/python/xen/xm/resources.py	Fri Jul 27 08:15:16 2007 -0600
    70.3 @@ -21,7 +21,10 @@
    70.4  import sys
    70.5  from xen.util import dictio
    70.6  from xen.util import security
    70.7 +from xen.util import xsconstants
    70.8  from xen.xm.opts import OptionError
    70.9 +from xen.xm import main as xm_main
   70.10 +from xen.xm.main import server
   70.11  
   70.12  def help():
   70.13      return """
   70.14 @@ -32,20 +35,32 @@ def print_resource_data(access_control):
   70.15      """Prints out a resource dictionary to stdout
   70.16      """
   70.17      for resource in access_control:
   70.18 -        (policy, label) = access_control[resource]
   70.19 +        tmp = access_control[resource]
   70.20 +        if len(tmp) == 2:
   70.21 +            policytype = xsconstants.ACM_POLICY_ID
   70.22 +            (policy, label) = access_control[resource]
   70.23 +        elif len(tmp) == 3:
   70.24 +            policytype, policy, label = access_control[resource]
   70.25          print resource
   70.26 -        print "    policy: "+policy
   70.27 -        print "    label:  "+label
   70.28 +        print "      type: "+ policytype
   70.29 +        print "    policy: "+ policy
   70.30 +        print "    label:  "+ label
   70.31  
   70.32  def main (argv):
   70.33      if len(argv) > 1:
   70.34          raise OptionError("No arguments required")
   70.35 -    
   70.36 -    try:
   70.37 -        filename = security.res_label_filename
   70.38 -        access_control = dictio.dict_read("resources", filename)
   70.39 -    except:
   70.40 -        raise OptionError("Resource file not found")
   70.41 +
   70.42 +    if xm_main.serverType == xm_main.SERVER_XEN_API:
   70.43 +        access_control = server.xenapi.XSPolicy.get_labeled_resources()
   70.44 +        for key, value in access_control.items():
   70.45 +            access_control[key] = tuple(value.split(':'))
   70.46 +    else:
   70.47 +        try:
   70.48 +            filename = security.res_label_filename
   70.49 +            access_control = dictio.dict_read("resources", filename)
   70.50 +            print access_control
   70.51 +        except:
   70.52 +            raise OptionError("Resource file not found")
   70.53  
   70.54      print_resource_data(access_control)
   70.55  
    71.1 --- a/tools/python/xen/xm/rmlabel.py	Thu Jul 26 14:35:01 2007 -0600
    71.2 +++ b/tools/python/xen/xm/rmlabel.py	Fri Jul 27 08:15:16 2007 -0600
    71.3 @@ -22,35 +22,53 @@ import sys, os, re
    71.4  from xen.util import dictio
    71.5  from xen.util import security
    71.6  from xen.xm.opts import OptionError
    71.7 +from xen.xm import main as xm_main
    71.8 +from xen.xm.main import server
    71.9  
   71.10  def help():
   71.11      return """
   71.12      Example: xm rmlabel dom <configfile>
   71.13               xm rmlabel res <resource>
   71.14 +             xm rmlabel mgt <domain name>
   71.15 +             xm rmlabel vif-<idx> <domain name>
   71.16  
   71.17      This program removes an acm_label entry from the 'configfile'
   71.18 -    for a domain or from the global resource label file for a
   71.19 -    resource. If the label does not exist for the given domain or
   71.20 -    resource, then rmlabel fails."""
   71.21 +    for a domain, from a Xend-managed domain, from the global resource label
   71.22 +    file for a resource or from the virtual network interface of a Xend-managed
   71.23 +    domain. If the label does not exist for the given domain or resource, then
   71.24 +    rmlabel fails."""
   71.25  
   71.26  
   71.27  def rm_resource_label(resource):
   71.28      """Removes a resource label from the global resource label file.
   71.29      """
   71.30 +    # Try Xen-API first if configured to use it
   71.31 +    if xm_main.serverType == xm_main.SERVER_XEN_API:
   71.32 +        try:
   71.33 +            oldlabel = server.xenapi.XSPolicy.get_resource_label(resource)
   71.34 +            if oldlabel != "":
   71.35 +                server.xenapi.XSPolicy.set_resource_label(resource,"",
   71.36 +                                                          oldlabel)
   71.37 +            else:
   71.38 +                raise security.ACMError("Resource not labeled")
   71.39 +        except Exception, e:
   71.40 +            print "Could not remove label from resource: %s" % e
   71.41 +        return
   71.42 +
   71.43      #build canonical resource name
   71.44      resource = security.unify_resname(resource)
   71.45  
   71.46      # read in the resource file
   71.47 -    file = security.res_label_filename
   71.48 +    fil = security.res_label_filename
   71.49      try:
   71.50 -        access_control = dictio.dict_read("resources", file)
   71.51 +        access_control = dictio.dict_read("resources", fil)
   71.52      except:
   71.53          raise security.ACMError("Resource file not found, cannot remove label!")
   71.54  
   71.55      # remove the entry and update file
   71.56      if access_control.has_key(resource):
   71.57          del access_control[resource]
   71.58 -        dictio.dict_write(access_control, "resources", file)
   71.59 +        dictio.dict_write(access_control, "resources", fil)
   71.60      else:
   71.61          raise security.ACMError("Resource not labeled")
   71.62  
   71.63 @@ -58,15 +76,15 @@ def rm_resource_label(resource):
   71.64  def rm_domain_label(configfile):
   71.65      # open the domain config file
   71.66      fd = None
   71.67 -    file = None
   71.68 +    fil = None
   71.69      if configfile[0] == '/':
   71.70 -        file = configfile
   71.71 -        fd = open(file, "rb")
   71.72 +        fil = configfile
   71.73 +        fd = open(fil, "rb")
   71.74      else:
   71.75          for prefix in [".", "/etc/xen"]:
   71.76 -            file = prefix + "/" + configfile
   71.77 -            if os.path.isfile(file):
   71.78 -                fd = open(file, "rb")
   71.79 +            fil = prefix + "/" + configfile
   71.80 +            if os.path.isfile(fil):
   71.81 +                fd = open(fil, "rb")
   71.82                  break
   71.83      if not fd:
   71.84          raise OptionError("Configuration file '%s' not found." % configfile)
   71.85 @@ -93,25 +111,74 @@ def rm_domain_label(configfile):
   71.86          raise security.ACMError('Domain not labeled')
   71.87  
   71.88      # write the data back out to the file
   71.89 -    fd = open(file, "wb")
   71.90 +    fd = open(fil, "wb")
   71.91      fd.writelines(file_contents)
   71.92      fd.close()
   71.93  
   71.94 +def rm_domain_label_xapi(domainname):
   71.95 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   71.96 +        raise OptionError('Need to be configure for using xen-api.')
   71.97 +    uuids = server.xenapi.VM.get_by_name_label(domainname)
   71.98 +    if len(uuids) == 0:
   71.99 +        raise OptionError('A VM with that name does not exist.')
  71.100 +    if len(uuids) != 1:
  71.101 +        raise OptionError('Too many domains with the same name.')
  71.102 +    uuid = uuids[0]
  71.103 +    try:
  71.104 +        old_lab = server.xenapi.VM.get_security_label(uuid)
  71.105 +        server.xenapi.VM.set_security_label(uuid, "", old_lab)
  71.106 +    except Exception, e:
  71.107 +        print('Could not remove label from domain: %s' % e)
  71.108 +
  71.109 +def rm_vif_label(vmname, idx):
  71.110 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
  71.111 +        raise OptionError('Need to be configure for using xen-api.')
  71.112 +    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
  71.113 +    if len(vm_refs) == 0:
  71.114 +        raise OptionError('A VM with the name %s does not exist.' %
  71.115 +                          vmname)
  71.116 +    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
  71.117 +    if len(vif_refs) <= idx:
  71.118 +        raise OptionError("Bad VIF index.")
  71.119 +    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
  71.120 +    if not vif_ref:
  71.121 +        print "A VIF with this UUID does not exist."
  71.122 +    try:
  71.123 +        old_lab = server.xenapi.VIF.get_security_label(vif_ref)
  71.124 +        rc = server.xenapi.VIF.set_security_label(vif_ref, "", old_lab)
  71.125 +        if int(rc) != 0:
  71.126 +            print "Could not remove the label from the VIF."
  71.127 +        else:
  71.128 +            print "Successfully removed the label from the VIF."
  71.129 +    except Exception, e:
  71.130 +        print "Could not remove the label the VIF: %s" % str(e)
  71.131 +
  71.132  
  71.133  def main (argv):
  71.134  
  71.135      if len(argv) != 3:
  71.136          raise OptionError('Requires 2 arguments')
  71.137      
  71.138 -    if argv[1].lower() not in ('dom', 'res'):
  71.139 -        raise OptionError('Unrecognised type argument: %s' % argv[1])
  71.140 -
  71.141      if argv[1].lower() == "dom":
  71.142          configfile = argv[2]
  71.143          rm_domain_label(configfile)
  71.144 +    elif argv[1].lower() == "mgt":
  71.145 +        domain = argv[2]
  71.146 +        rm_domain_label_xapi(domain)
  71.147 +    elif argv[1].lower().startswith("vif-"):
  71.148 +        try:
  71.149 +            idx = int(argv[1][4:])
  71.150 +            if idx < 0:
  71.151 +                raise
  71.152 +        except:
  71.153 +            raise OptionError("Bad VIF device index.")
  71.154 +        vmname = argv[2]
  71.155 +        rm_vif_label(vmname, idx)
  71.156      elif argv[1].lower() == "res":
  71.157          resource = argv[2]
  71.158          rm_resource_label(resource)
  71.159 +    else:
  71.160 +        raise OptionError('Unrecognised type argument: %s' % argv[1])
  71.161  
  71.162  if __name__ == '__main__':
  71.163      try:
  71.164 @@ -119,5 +186,3 @@ if __name__ == '__main__':
  71.165      except Exception, e:
  71.166          sys.stderr.write('Error: %s\n' % str(e))
  71.167          sys.exit(-1)    
  71.168 -
  71.169 -
    72.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    72.2 +++ b/tools/python/xen/xm/setpolicy.py	Fri Jul 27 08:15:16 2007 -0600
    72.3 @@ -0,0 +1,117 @@
    72.4 +#============================================================================
    72.5 +# This library is free software; you can redistribute it and/or
    72.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
    72.7 +# License as published by the Free Software Foundation.
    72.8 +#
    72.9 +# This library is distributed in the hope that it will be useful,
   72.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
   72.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   72.12 +# Lesser General Public License for more details.
   72.13 +#
   72.14 +# You should have received a copy of the GNU Lesser General Public
   72.15 +# License along with this library; if not, write to the Free Software
   72.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   72.17 +#============================================================================
   72.18 +# Copyright (C) 2007 International Business Machines Corp.
   72.19 +# Author: Stefan Berger <stefanb@us.ibm.com>
   72.20 +#============================================================================
   72.21 +
   72.22 +"""Get the managed policy of the system.
   72.23 +"""
   72.24 +
   72.25 +import base64
   72.26 +import struct
   72.27 +import sys
   72.28 +import string
   72.29 +from xen.util import xsconstants
   72.30 +from xen.xm.opts import OptionError
   72.31 +from xen.util.security import policy_dir_prefix
   72.32 +from xen.xm import main as xm_main
   72.33 +from xen.xm.main import server
   72.34 +
   72.35 +def help():
   72.36 +    return """
   72.37 +    Usage: xm setpolicy <policytype> <policy> [options]
   72.38 +
   72.39 +    Set the policy managed by xend.
   72.40 +
   72.41 +    The only policytype that is currently supported is 'ACM'.
   72.42 +
   72.43 +    The following options are defined
   72.44 +      --load     Load the policy immediately
   72.45 +      --boot     Have the system load the policy during boot
   72.46 +    """
   72.47 +
   72.48 +def setpolicy(policytype, policy_name, flags, overwrite):
   72.49 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   72.50 +        raise OptionError('xm needs to be configured to use the xen-api.')
   72.51 +    if policytype != xsconstants.ACM_POLICY_ID:
   72.52 +        raise OptionError("Unsupported policytype '%s'." % policytype)
   72.53 +    else:
   72.54 +        xs_type = xsconstants.XS_POLICY_ACM
   72.55 +
   72.56 +        policy_file = policy_dir_prefix + "/" + \
   72.57 +                      string.join(string.split(policy_name, "."), "/")
   72.58 +        policy_file += "-security_policy.xml"
   72.59 +
   72.60 +        try:
   72.61 +            f = open(policy_file,"r")
   72.62 +            xml = f.read(-1)
   72.63 +            f.close()
   72.64 +        except:
   72.65 +            raise OptionError("Not a valid policy file")
   72.66 +
   72.67 +        try:
   72.68 +            policystate = server.xenapi.XSPolicy.set_xspolicy(xs_type,
   72.69 +                                                              xml,
   72.70 +                                                              flags,
   72.71 +                                                              overwrite)
   72.72 +        except Exception, e:
   72.73 +            print "An error occurred setting the policy: %s" % str(e)
   72.74 +            return
   72.75 +        xserr = int(policystate['xserr'])
   72.76 +        if xserr != 0:
   72.77 +            print "An error occurred trying to set the policy: %s" % \
   72.78 +                  xsconstants.xserr2string(abs(xserr))
   72.79 +            errors = policystate['errors']
   72.80 +            if len(errors) > 0:
   72.81 +                print "Hypervisor reported errors:"
   72.82 +                err = base64.b64decode(errors)
   72.83 +                i = 0
   72.84 +                while i + 7 < len(err):
   72.85 +                    code, data = struct.unpack("!ii", errors[i:i+8])
   72.86 +                    print "(0x%08x, 0x%08x)" % (code, data)
   72.87 +                    i += 8
   72.88 +        else:
   72.89 +            print "Successfully set the new policy."
   72.90 +
   72.91 +
   72.92 +def main(argv):
   72.93 +    if len(argv) < 3:
   72.94 +       raise OptionError("Need at least 3 arguments.")
   72.95 +
   72.96 +    if "-?" in argv:
   72.97 +        help()
   72.98 +        return
   72.99 +
  72.100 +    policytype  = argv[1]
  72.101 +    policy_name = argv[2]
  72.102 +
  72.103 +    flags = 0
  72.104 +    if '--load' in argv:
  72.105 +        flags |= xsconstants.XS_INST_LOAD
  72.106 +    if '--boot' in argv:
  72.107 +        flags |= xsconstants.XS_INST_BOOT
  72.108 +
  72.109 +    overwrite = True
  72.110 +    if '--nooverwrite' in argv:
  72.111 +        overwrite = False
  72.112 +
  72.113 +    setpolicy(policytype, policy_name, flags, overwrite)
  72.114 +
  72.115 +if __name__ == '__main__':
  72.116 +    try:
  72.117 +        main(sys.argv)
  72.118 +    except Exception, e:
  72.119 +        sys.stderr.write('Error: %s\n' % str(e))
  72.120 +        sys.exit(-1)
    73.1 --- a/tools/python/xen/xm/xenapi_create.py	Thu Jul 26 14:35:01 2007 -0600
    73.2 +++ b/tools/python/xen/xm/xenapi_create.py	Fri Jul 27 08:15:16 2007 -0600
    73.3 @@ -25,6 +25,7 @@ from xen.xend import sxp
    73.4  from xen.xend.XendAPIConstants import XEN_API_ON_NORMAL_EXIT, \
    73.5       XEN_API_ON_CRASH_BEHAVIOUR
    73.6  from xen.xm.opts import OptionError
    73.7 +from xen.util import xsconstants
    73.8  
    73.9  import sys
   73.10  import os
   73.11 @@ -308,6 +309,12 @@ class xenapi_create:
   73.12                 ""
   73.13              }
   73.14  
   73.15 +        if vm.attributes.has_key("security_label"):
   73.16 +            vm_record.update({
   73.17 +                "security_label":
   73.18 +                    vm.attributes["security_label"].value
   73.19 +                })
   73.20 +
   73.21          if len(vm.getElementsByTagName("pv")) > 0:
   73.22              vm_record.update({
   73.23                  "PV_bootloader":
   73.24 @@ -348,6 +355,12 @@ class xenapi_create:
   73.25  
   73.26              self.create_vifs(vm_ref, vifs, networks)
   73.27  
   73.28 +            # Now create vtpms
   73.29 +
   73.30 +            vtpms = vm.getElementsByTagName("vtpm")
   73.31 +
   73.32 +            self.create_vtpms(vm_ref, vtpms)
   73.33 +
   73.34              # Now create consoles
   73.35  
   73.36              consoles = vm.getElementsByTagName("console")
   73.37 @@ -427,7 +440,9 @@ class xenapi_create:
   73.38                  vif.attributes["qos_algorithm_type"].value,
   73.39              "qos_algorithm_params":
   73.40                  get_child_nodes_as_dict(vif,
   73.41 -                    "qos_algorithm_param", "key", "value")
   73.42 +                    "qos_algorithm_param", "key", "value"),
   73.43 +            "security_label":
   73.44 +                vif.attributes["security_label"].value
   73.45          }
   73.46  
   73.47          return server.xenapi.VIF.create(vif_record)
   73.48 @@ -441,6 +456,21 @@ class xenapi_create:
   73.49              self._network_refs = server.xenapi.network.get_all()
   73.50              return self._network_refs.pop(0)
   73.51  
   73.52 +    def create_vtpms(self, vm_ref, vtpms):
   73.53 +        if len(vtpms) > 1:
   73.54 +            vtpms = [ vtpms[0] ]
   73.55 +        log(DEBUG, "create_vtpms")
   73.56 +        return map(lambda vtpm: self.create_vtpm(vm_ref, vtpm), vtpms)
   73.57 +
   73.58 +    def create_vtpm(self, vm_ref, vtpm):
   73.59 +        vtpm_record = {
   73.60 +            "VM":
   73.61 +                vm_ref,
   73.62 +            "backend":
   73.63 +                vtpm.attributes["backend"].value
   73.64 +        }
   73.65 +        return server.xenapi.VTPM.create(vtpm_record)
   73.66 +
   73.67      def create_consoles(self, vm_ref, consoles):
   73.68          log(DEBUG, "create_consoles")
   73.69          return map(lambda console: self.create_console(vm_ref, console),
   73.70 @@ -482,6 +512,10 @@ class sxp2xml:
   73.71  
   73.72          vifs_sxp = map(lambda x: x[1], [device for device in devices
   73.73                                          if device[1][0] == "vif"])
   73.74 +
   73.75 +        vtpms_sxp = map(lambda x: x[1], [device for device in devices
   73.76 +                                         if device[1][0] == "vtpm"])
   73.77 +
   73.78          # Create XML Document
   73.79          
   73.80          impl = getDOMImplementation()
   73.81 @@ -531,6 +565,14 @@ class sxp2xml:
   73.82          vm.attributes["vcpus_at_startup"] \
   73.83              = str(get_child_by_name(config, "vcpus", 1))
   73.84  
   73.85 +        sec_data = get_child_by_name(config, "security")
   73.86 +        if sec_data:
   73.87 +            try :
   73.88 +                vm.attributes['security_label'] = \
   73.89 +                      "%s:%s:%s" % (xsconstants.ACM_POLICY_ID, sec_data[0][1][1],sec_data[0][2][1])
   73.90 +            except Exception, e:
   73.91 +                raise "Invalid security data format: %s" % str(sec_data)
   73.92 +
   73.93          # Make the name tag
   73.94  
   73.95          vm.appendChild(self.make_name_tag(
   73.96 @@ -601,6 +643,12 @@ class sxp2xml:
   73.97  
   73.98          map(vm.appendChild, vifs)
   73.99  
  73.100 +        # And now the vTPMs
  73.101 +
  73.102 +        vtpms = map(lambda vtpm: self.extract_vtpm(vtpm, document), vtpms_sxp)
  73.103 +
  73.104 +        map(vm.appendChild, vtpms)
  73.105 +
  73.106          # Last but not least the consoles...
  73.107  
  73.108          consoles = self.extract_consoles(image, document)
  73.109 @@ -702,12 +750,30 @@ class sxp2xml:
  73.110          vif.attributes["device"] = dev
  73.111          vif.attributes["qos_algorithm_type"] = ""
  73.112  
  73.113 +        policy = get_child_by_name(vif_sxp, "policy")
  73.114 +        label = get_child_by_name(vif_sxp, "label")
  73.115 +
  73.116 +        if label and policy:
  73.117 +            vif.attributes["security_label"] \
  73.118 +                 = "%s:%s:%s" % (xsconstants.ACM_POLICY_ID, policy, label)
  73.119 +        else:
  73.120 +            vif.attributes["security_label"] = ""
  73.121 +
  73.122          if get_child_by_name(vif_sxp, "bridge") is not None:
  73.123              vif.attributes["network"] \
  73.124                  = get_child_by_name(vif_sxp, "bridge")
  73.125          
  73.126          return vif
  73.127  
  73.128 +    def extract_vtpm(self, vtpm_sxp, document):
  73.129 +
  73.130 +        vtpm = document.createElement("vtpm")
  73.131 +
  73.132 +        vtpm.attributes["backend"] \
  73.133 +             = get_child_by_name(vtpm_sxp, "backend", "0")
  73.134 +
  73.135 +        return vtpm
  73.136 +
  73.137      _eths = -1
  73.138  
  73.139      def mk_other_config(self, key, value, document):
    74.1 --- a/tools/security/policies/security_policy.xsd	Thu Jul 26 14:35:01 2007 -0600
    74.2 +++ b/tools/security/policies/security_policy.xsd	Fri Jul 27 08:15:16 2007 -0600
    74.3 @@ -99,7 +99,7 @@
    74.4  			<xsd:sequence>
    74.5  				<xsd:element name="Name" type="NameWithFrom"></xsd:element>
    74.6  				<xsd:element ref="SimpleTypeEnforcementTypes" minOccurs="0" maxOccurs="unbounded" />
    74.7 -				<xsd:element name="ChineseWallTypes" type="SingleChineseWallType" />
    74.8 +				<xsd:element ref="ChineseWallTypes" minOccurs="0" maxOccurs="unbounded" />
    74.9  			</xsd:sequence>
   74.10  		</xsd:complexType>
   74.11  	</xsd:element>
   74.12 @@ -143,9 +143,4 @@
   74.13  			<xsd:element maxOccurs="1" minOccurs="1" ref="Type" />
   74.14  		</xsd:sequence>
   74.15  	</xsd:complexType>
   74.16 -	<xsd:complexType name="SingleChineseWallType">
   74.17 -		<xsd:sequence>
   74.18 -			<xsd:element maxOccurs="1" minOccurs="1" ref="Type" />
   74.19 -		</xsd:sequence>
   74.20 -	</xsd:complexType>
   74.21  </xsd:schema>
    75.1 --- a/tools/vtpm_manager/util/hashtable_itr.c	Thu Jul 26 14:35:01 2007 -0600
    75.2 +++ b/tools/vtpm_manager/util/hashtable_itr.c	Fri Jul 27 08:15:16 2007 -0600
    75.3 @@ -225,7 +225,7 @@ hashtable_iterator_search(struct hashtab
    75.4      
    75.5  egress:
    75.6  #ifdef HASHTABLE_THREADED
    75.7 -    pthread_mutex_lock(&h->mutex);
    75.8 +    pthread_mutex_unlock(&h->mutex);
    75.9  #endif 
   75.10      return ret;
   75.11  }
    76.1 --- a/tools/xcutils/xc_save.c	Thu Jul 26 14:35:01 2007 -0600
    76.2 +++ b/tools/xcutils/xc_save.c	Fri Jul 27 08:15:16 2007 -0600
    76.3 @@ -54,8 +54,18 @@ static int suspend(int domid)
    76.4  
    76.5  static char *qemu_active_path;
    76.6  static char *qemu_next_active_path;
    76.7 +static int qemu_shmid = -1;
    76.8  static struct xs_handle *xs;
    76.9  
   76.10 +
   76.11 +/* Mark the shared-memory segment for destruction */
   76.12 +static void qemu_destroy_buffer(void)
   76.13 +{
   76.14 +    if (qemu_shmid != -1)
   76.15 +        shmctl(qemu_shmid, IPC_RMID, NULL);
   76.16 +    qemu_shmid = -1;
   76.17 +}
   76.18 +
   76.19  /* Get qemu to change buffers. */
   76.20  static void qemu_flip_buffer(int domid, int next_active)
   76.21  {
   76.22 @@ -97,22 +107,23 @@ static void * init_qemu_maps(int domid, 
   76.23  {
   76.24      key_t key;
   76.25      char key_ascii[17] = {0,};
   76.26 -    int shmid = -1;
   76.27      void *seg; 
   76.28      char *path, *p;
   76.29  
   76.30      /* Make a shared-memory segment */
   76.31 -    while (shmid == -1)
   76.32 -    {
   76.33 +    do {
   76.34          key = rand(); /* No security, just a sequence of numbers */
   76.35 -        shmid = shmget(key, 2 * bitmap_size, 
   76.36 +        qemu_shmid = shmget(key, 2 * bitmap_size, 
   76.37                         IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR);
   76.38 -        if (shmid == -1 && errno != EEXIST)
   76.39 +        if (qemu_shmid == -1 && errno != EEXIST)
   76.40              errx(1, "can't get shmem to talk to qemu-dm");
   76.41 -    }
   76.42 +    } while (qemu_shmid == -1);
   76.43 +
   76.44 +    /* Remember to tidy up after ourselves */
   76.45 +    atexit(qemu_destroy_buffer);
   76.46  
   76.47      /* Map it into our address space */
   76.48 -    seg = shmat(shmid, NULL, 0);
   76.49 +    seg = shmat(qemu_shmid, NULL, 0);
   76.50      if (seg == (void *) -1) 
   76.51          errx(1, "can't map shmem to talk to qemu-dm");
   76.52      memset(seg, 0, 2 * bitmap_size);
   76.53 @@ -123,11 +134,13 @@ static void * init_qemu_maps(int domid, 
   76.54      /* Tell qemu about it */
   76.55      if ((xs = xs_daemon_open()) == NULL)
   76.56          errx(1, "Couldn't contact xenstore");
   76.57 -    if (!(path = xs_get_domain_path(xs, domid)))
   76.58 +    if (!(path = strdup("/local/domain/0/device-model/")))
   76.59          errx(1, "can't get domain path in store");
   76.60      if (!(path = realloc(path, strlen(path) 
   76.61 +                         + 10 
   76.62                           + strlen("/logdirty/next-active") + 1))) 
   76.63          errx(1, "no memory for constructing xenstore path");
   76.64 +    snprintf(path + strlen(path), 11, "%i", domid);
   76.65      strcat(path, "/logdirty/");
   76.66      p = path + strlen(path);
   76.67  
    77.1 --- a/tools/xenfb/vncfb.c	Thu Jul 26 14:35:01 2007 -0600
    77.2 +++ b/tools/xenfb/vncfb.c	Fri Jul 27 08:15:16 2007 -0600
    77.3 @@ -55,12 +55,47 @@ static unsigned char atkbd_unxlate_table
    77.4  unsigned char keycode_table[512];
    77.5  
    77.6  static void *kbd_layout;
    77.7 +uint8_t modifiers_state[256];
    77.8  
    77.9  static int btnmap[] = {
   77.10  	BTN_LEFT, BTN_MIDDLE, BTN_RIGHT, BTN_SIDE,
   77.11  	BTN_EXTRA, BTN_FORWARD, BTN_BACK, BTN_TASK
   77.12  };
   77.13  
   77.14 +static void press_key_shift_down(struct xenfb* xenfb, int down, int scancode)
   77.15 +{
   77.16 +	if (down)
   77.17 +		xenfb_send_key(xenfb, 1, keycode_table[0x2a]);
   77.18 +
   77.19 +	if (xenfb_send_key(xenfb, down, keycode_table[scancode]) < 0)
   77.20 +		fprintf(stderr, "Key %d %s lost (%s)\n",
   77.21 +			scancode, "down", strerror(errno));
   77.22 +
   77.23 +	if (!down)
   77.24 +		xenfb_send_key(xenfb, 0, keycode_table[0x2a]);
   77.25 +}
   77.26 +
   77.27 +static void press_key_shift_up(struct xenfb* xenfb, int down, int scancode)
   77.28 +{
   77.29 +	if (down) {
   77.30 +		if (modifiers_state[0x2a])
   77.31 +			xenfb_send_key(xenfb, 0, keycode_table[0x2a]);
   77.32 +		if (modifiers_state[0x36])
   77.33 +			xenfb_send_key(xenfb, 0, keycode_table[0x36]);
   77.34 +	}
   77.35 +
   77.36 +	if (xenfb_send_key(xenfb, down, keycode_table[scancode]) < 0)
   77.37 +		fprintf(stderr, "Key %d %s lost (%s)\n",
   77.38 +			scancode, "down", strerror(errno));
   77.39 +
   77.40 +	if (!down) {
   77.41 +		if (modifiers_state[0x2a])
   77.42 +			xenfb_send_key(xenfb, 1, keycode_table[0x2a]);
   77.43 +		if (modifiers_state[0x36])
   77.44 +			xenfb_send_key(xenfb, 1, keycode_table[0x36]);
   77.45 +	}
   77.46 +}
   77.47 +
   77.48  static void on_kbd_event(rfbBool down, rfbKeySym keycode, rfbClientPtr cl)
   77.49  {
   77.50  	/*
   77.51 @@ -75,14 +110,75 @@ static void on_kbd_event(rfbBool down, r
   77.52  	rfbScreenInfoPtr server = cl->screen;
   77.53  	struct xenfb *xenfb = server->screenData;
   77.54  	int scancode;
   77.55 +	int shift = 0;
   77.56 +	int shift_keys = 0;
   77.57  
   77.58 -	if (keycode >= 'A' && keycode <= 'Z')
   77.59 +	if (keycode >= 'A' && keycode <= 'Z') {
   77.60  		keycode += 'a' - 'A';
   77.61 +		shift = 1;
   77.62 +	}
   77.63 +	else {
   77.64 +		shift = keysymIsShift(kbd_layout, keycode);
   77.65 +	}
   77.66 +	shift_keys = modifiers_state[0x2a] | modifiers_state[0x36];	
   77.67  
   77.68 -	scancode = keycode_table[keysym2scancode(kbd_layout, keycode)];
   77.69 +	scancode = keysym2scancode(kbd_layout, keycode);
   77.70  	if (scancode == 0)
   77.71  		return;
   77.72 -	if (xenfb_send_key(xenfb, down, scancode) < 0)
   77.73 +
   77.74 +	switch(scancode) {
   77.75 +	case 0x2a:			/* Left Shift */
   77.76 +	case 0x36:			/* Right Shift */
   77.77 +	case 0x1d:			/* Left CTRL */
   77.78 +	case 0x9d:			/* Right CTRL */
   77.79 +	case 0x38:			/* Left ALT */
   77.80 +	case 0xb8:			/* Right ALT */
   77.81 +		if (down)
   77.82 +			modifiers_state[scancode] = 1;
   77.83 +		else
   77.84 +			modifiers_state[scancode] = 0;
   77.85 +		xenfb_send_key(xenfb, down, keycode_table[scancode]); 
   77.86 +		return;
   77.87 +	case 0x45:			/* NumLock */
   77.88 +		if (!down)
   77.89 +			modifiers_state[scancode] ^= 1;
   77.90 +		xenfb_send_key(xenfb, down, keycode_table[scancode]);
   77.91 +		return;
   77.92 +	}
   77.93 +
   77.94 +	if (keycodeIsKeypad(kbd_layout, scancode)) {
   77.95 +	/* If the numlock state needs to change then simulate an additional
   77.96 +	   keypress before sending this one.  This will happen if the user
   77.97 +	   toggles numlock away from the VNC window.
   77.98 +	*/
   77.99 +		if (keysymIsNumlock(kbd_layout, keycode)) {
  77.100 +			if (!modifiers_state[0x45]) {
  77.101 +				modifiers_state[0x45] = 1;
  77.102 +				xenfb_send_key(xenfb, 1, keycode_table[0x45]);
  77.103 +				xenfb_send_key(xenfb, 0, keycode_table[0x45]);
  77.104 +			}
  77.105 +		} else {
  77.106 +			if (modifiers_state[0x45]) {
  77.107 +				modifiers_state[0x45] = 0;
  77.108 +				xenfb_send_key(xenfb, 1, keycode_table[0x45]);
  77.109 +				xenfb_send_key(xenfb, 0, keycode_table[0x45]);
  77.110 +			}
  77.111 +		}
  77.112 +	}
  77.113 +
  77.114 +	/* If the shift state needs to change then simulate an additional
  77.115 +	   keypress before sending this one.
  77.116 +	*/
  77.117 +	if (shift && !shift_keys) {
  77.118 +		press_key_shift_down(xenfb, down, scancode);
  77.119 +		return;
  77.120 +	}
  77.121 +	else if (!shift && shift_keys) {
  77.122 +		press_key_shift_up(xenfb, down, scancode);
  77.123 +		return;
  77.124 +	}
  77.125 +
  77.126 +	if (xenfb_send_key(xenfb, down, keycode_table[scancode]) < 0)
  77.127  		fprintf(stderr, "Key %d %s lost (%s)\n",
  77.128  			scancode, down ? "down" : "up",
  77.129  			strerror(errno));
  77.130 @@ -314,6 +410,10 @@ int main(int argc, char **argv)
  77.131  			atkbd_set2_keycode[atkbd_unxlate_table[i] | 0x80];
  77.132  	}
  77.133  
  77.134 +	for (i = 0; i < 256; i++ ) {
  77.135 +		modifiers_state[i] = 0;
  77.136 +	}
  77.137 +
  77.138  	fake_argv[2] = portstr;
  77.139  
  77.140          if (title != NULL)
    78.1 --- a/tools/xenstore/talloc.c	Thu Jul 26 14:35:01 2007 -0600
    78.2 +++ b/tools/xenstore/talloc.c	Fri Jul 27 08:15:16 2007 -0600
    78.3 @@ -97,6 +97,7 @@ struct talloc_chunk {
    78.4  	struct talloc_chunk *next, *prev;
    78.5  	struct talloc_chunk *parent, *child;
    78.6  	struct talloc_reference_handle *refs;
    78.7 +	unsigned int null_refs; /* references from null_context */
    78.8  	talloc_destructor_t destructor;
    78.9  	const char *name;
   78.10  	size_t size;
   78.11 @@ -189,6 +190,7 @@ void *_talloc(const void *context, size_
   78.12  	tc->child = NULL;
   78.13  	tc->name = NULL;
   78.14  	tc->refs = NULL;
   78.15 +	tc->null_refs = 0;
   78.16  
   78.17  	if (context) {
   78.18  		struct talloc_chunk *parent = talloc_chunk_from_ptr(context);
   78.19 @@ -225,7 +227,11 @@ void talloc_set_destructor(const void *p
   78.20  */
   78.21  void talloc_increase_ref_count(const void *ptr)
   78.22  {
   78.23 -	talloc_reference(null_context, ptr);
   78.24 +	struct talloc_chunk *tc;
   78.25 +	if (ptr == NULL) return;
   78.26 +
   78.27 +	tc = talloc_chunk_from_ptr(ptr);
   78.28 +	tc->null_refs++;
   78.29  }
   78.30  
   78.31  /*
   78.32 @@ -287,6 +293,11 @@ static int talloc_unreference(const void
   78.33  		context = null_context;
   78.34  	}
   78.35  
   78.36 +	if ((context == null_context) && tc->null_refs) {
   78.37 +		tc->null_refs--;
   78.38 +		return 0;
   78.39 +	}
   78.40 +
   78.41  	for (h=tc->refs;h;h=h->next) {
   78.42  		struct talloc_chunk *p = talloc_parent_chunk(h);
   78.43  		if (p == NULL) {
   78.44 @@ -539,6 +550,11 @@ int talloc_free(void *ptr)
   78.45  
   78.46  	tc = talloc_chunk_from_ptr(ptr);
   78.47  
   78.48 +	if (tc->null_refs) {
   78.49 +		tc->null_refs--;
   78.50 +		return -1;
   78.51 +	}
   78.52 +
   78.53  	if (tc->refs) {
   78.54  		talloc_reference_destructor(tc->refs);
   78.55  		return -1;
    79.1 --- a/tools/xenstore/xenstored_core.c	Thu Jul 26 14:35:01 2007 -0600
    79.2 +++ b/tools/xenstore/xenstored_core.c	Fri Jul 27 08:15:16 2007 -0600
    79.3 @@ -299,11 +299,15 @@ static void set_fd(int fd, fd_set *set, 
    79.4  }
    79.5  
    79.6  
    79.7 -static int initialize_set(fd_set *inset, fd_set *outset, int sock, int ro_sock)
    79.8 +static int initialize_set(fd_set *inset, fd_set *outset, int sock, int ro_sock,
    79.9 +			  struct timeval **ptimeout)
   79.10  {
   79.11 -	struct connection *i;
   79.12 +	static struct timeval zero_timeout = { 0 };
   79.13 +	struct connection *conn;
   79.14  	int max = -1;
   79.15  
   79.16 +	*ptimeout = NULL;
   79.17 +
   79.18  	FD_ZERO(inset);
   79.19  	FD_ZERO(outset);
   79.20  
   79.21 @@ -314,13 +318,19 @@ static int initialize_set(fd_set *inset,
   79.22  	if (xce_handle != -1)
   79.23  		set_fd(xc_evtchn_fd(xce_handle), inset, &max);
   79.24  
   79.25 -	list_for_each_entry(i, &connections, list) {
   79.26 -		if (i->domain)
   79.27 -			continue;
   79.28 -		set_fd(i->fd, inset, &max);
   79.29 -		if (!list_empty(&i->out_list))
   79.30 -			FD_SET(i->fd, outset);
   79.31 +	list_for_each_entry(conn, &connections, list) {
   79.32 +		if (conn->domain) {
   79.33 +			if (domain_can_read(conn) ||
   79.34 +			    (domain_can_write(conn) &&
   79.35 +			     !list_empty(&conn->out_list)))
   79.36 +				*ptimeout = &zero_timeout;
   79.37 +		} else {
   79.38 +			set_fd(conn->fd, inset, &max);
   79.39 +			if (!list_empty(&conn->out_list))
   79.40 +				FD_SET(conn->fd, outset);
   79.41 +		}
   79.42  	}
   79.43 +
   79.44  	return max;
   79.45  }
   79.46  
   79.47 @@ -1256,7 +1266,7 @@ static void handle_input(struct connecti
   79.48  	if (in->inhdr) {
   79.49  		bytes = conn->read(conn, in->hdr.raw + in->used,
   79.50  				   sizeof(in->hdr) - in->used);
   79.51 -		if (bytes <= 0)
   79.52 +		if (bytes < 0)
   79.53  			goto bad_client;
   79.54  		in->used += bytes;
   79.55  		if (in->used != sizeof(in->hdr))
   79.56 @@ -1278,7 +1288,7 @@ static void handle_input(struct connecti
   79.57  
   79.58  	bytes = conn->read(conn, in->buffer + in->used,
   79.59  			   in->hdr.msg.len - in->used);
   79.60 -	if (bytes <= 0)
   79.61 +	if (bytes < 0)
   79.62  		goto bad_client;
   79.63  
   79.64  	in->used += bytes;
   79.65 @@ -1331,12 +1341,40 @@ struct connection *new_connection(connwr
   79.66  
   79.67  static int writefd(struct connection *conn, const void *data, unsigned int len)
   79.68  {
   79.69 -	return write(conn->fd, data, len);
   79.70 +	int rc;
   79.71 +
   79.72 +	while ((rc = write(conn->fd, data, len)) < 0) {
   79.73 +		if (errno == EAGAIN) {
   79.74 +			rc = 0;
   79.75 +			break;
   79.76 +		}
   79.77 +		if (errno != EINTR)
   79.78 +			break;
   79.79 +	}
   79.80 +
   79.81 +	return rc;
   79.82  }
   79.83  
   79.84  static int readfd(struct connection *conn, void *data, unsigned int len)
   79.85  {
   79.86 -	return read(conn->fd, data, len);
   79.87 +	int rc;
   79.88 +
   79.89 +	while ((rc = read(conn->fd, data, len)) < 0) {
   79.90 +		if (errno == EAGAIN) {
   79.91 +			rc = 0;
   79.92 +			break;
   79.93 +		}
   79.94 +		if (errno != EINTR)
   79.95 +			break;
   79.96 +	}
   79.97 +
   79.98 +	/* Reading zero length means we're done with this connection. */
   79.99 +	if ((rc == 0) && (len != 0)) {
  79.100 +		errno = EBADF;
  79.101 +		rc = -1;
  79.102 +	}
  79.103 +
  79.104 +	return rc;
  79.105  }
  79.106  
  79.107  static void accept_connection(int sock, bool canwrite)
  79.108 @@ -1429,13 +1467,13 @@ static void setup_structure(void)
  79.109  static unsigned int hash_from_key_fn(void *k)
  79.110  {
  79.111  	char *str = k;
  79.112 -        unsigned int hash = 5381;
  79.113 -        char c;
  79.114 +	unsigned int hash = 5381;
  79.115 +	char c;
  79.116  
  79.117 -        while ((c = *str++))
  79.118 +	while ((c = *str++))
  79.119  		hash = ((hash << 5) + hash) + (unsigned int)c;
  79.120  
  79.121 -        return hash;
  79.122 +	return hash;
  79.123  }
  79.124  
  79.125  
  79.126 @@ -1709,6 +1747,7 @@ int main(int argc, char *argv[])
  79.127  	bool no_domain_init = false;
  79.128  	const char *pidfile = NULL;
  79.129  	int evtchn_fd = -1;
  79.130 +	struct timeval *timeout;
  79.131  
  79.132  	while ((opt = getopt_long(argc, argv, "DE:F:HNPS:t:T:RLVW:", options,
  79.133  				  NULL)) != -1) {
  79.134 @@ -1850,17 +1889,16 @@ int main(int argc, char *argv[])
  79.135  		evtchn_fd = xc_evtchn_fd(xce_handle);
  79.136  
  79.137  	/* Get ready to listen to the tools. */
  79.138 -	max = initialize_set(&inset, &outset, *sock, *ro_sock);
  79.139 +	max = initialize_set(&inset, &outset, *sock, *ro_sock, &timeout);
  79.140  
  79.141  	/* Tell the kernel we're up and running. */
  79.142  	xenbus_notify_running();
  79.143  
  79.144  	/* Main loop. */
  79.145 -	/* FIXME: Rewrite so noone can starve. */
  79.146  	for (;;) {
  79.147 -		struct connection *i;
  79.148 +		struct connection *conn, *old_conn;
  79.149  
  79.150 -		if (select(max+1, &inset, &outset, NULL, NULL) < 0) {
  79.151 +		if (select(max+1, &inset, &outset, NULL, timeout) < 0) {
  79.152  			if (errno == EINTR)
  79.153  				continue;
  79.154  			barf_perror("Select failed");
  79.155 @@ -1882,41 +1920,31 @@ int main(int argc, char *argv[])
  79.156  		if (evtchn_fd != -1 && FD_ISSET(evtchn_fd, &inset))
  79.157  			handle_event();
  79.158  
  79.159 -		list_for_each_entry(i, &connections, list) {
  79.160 -			if (i->domain)
  79.161 -				continue;
  79.162 +		conn = list_entry(connections.next, typeof(*conn), list);
  79.163 +		while (&conn->list != &connections) {
  79.164 +			talloc_increase_ref_count(conn);
  79.165  
  79.166 -			/* Operations can delete themselves or others
  79.167 -			 * (xs_release): list is not safe after input,
  79.168 -			 * so break. */
  79.169 -			if (FD_ISSET(i->fd, &inset)) {
  79.170 -				handle_input(i);
  79.171 -				break;
  79.172 +			if (conn->domain) {
  79.173 +				if (domain_can_read(conn))
  79.174 +					handle_input(conn);
  79.175 +				if (domain_can_write(conn) &&
  79.176 +				    !list_empty(&conn->out_list))
  79.177 +					handle_output(conn);
  79.178 +			} else {
  79.179 +				if (FD_ISSET(conn->fd, &inset))
  79.180 +					handle_input(conn);
  79.181 +				if (FD_ISSET(conn->fd, &outset))
  79.182 +					handle_output(conn);
  79.183  			}
  79.184 -			if (FD_ISSET(i->fd, &outset)) {
  79.185 -				handle_output(i);
  79.186 -				break;
  79.187 -			}
  79.188 +
  79.189 +			old_conn = conn;
  79.190 +			conn = list_entry(old_conn->list.next,
  79.191 +					  typeof(*conn), list);
  79.192 +			talloc_free(old_conn);
  79.193  		}
  79.194  
  79.195 -		/* Handle all possible I/O for domain connections. */
  79.196 -	more:
  79.197 -		list_for_each_entry(i, &connections, list) {
  79.198 -			if (!i->domain)
  79.199 -				continue;
  79.200 -
  79.201 -			if (domain_can_read(i)) {
  79.202 -				handle_input(i);
  79.203 -				goto more;
  79.204 -			}
  79.205 -
  79.206 -			if (domain_can_write(i) && !list_empty(&i->out_list)) {
  79.207 -				handle_output(i);
  79.208 -				goto more;
  79.209 -			}
  79.210 -		}
  79.211 -
  79.212 -		max = initialize_set(&inset, &outset, *sock, *ro_sock);
  79.213 +		max = initialize_set(&inset, &outset, *sock, *ro_sock,
  79.214 +				     &timeout);
  79.215  	}
  79.216  }
  79.217  
    80.1 --- a/tools/xenstore/xenstored_domain.c	Thu Jul 26 14:35:01 2007 -0600
    80.2 +++ b/tools/xenstore/xenstored_domain.c	Fri Jul 27 08:15:16 2007 -0600
    80.3 @@ -76,7 +76,6 @@ struct domain
    80.4  
    80.5  static LIST_HEAD(domains);
    80.6  
    80.7 -/* FIXME: Mark connection as broken (close it?) when this happens. */
    80.8  static bool check_indexes(XENSTORE_RING_IDX cons, XENSTORE_RING_IDX prod)
    80.9  {
   80.10  	return ((prod - cons) <= XENSTORE_RING_SIZE);
   80.11 @@ -102,7 +101,8 @@ static const void *get_input_chunk(XENST
   80.12  	return buf + MASK_XENSTORE_IDX(cons);
   80.13  }
   80.14  
   80.15 -static int writechn(struct connection *conn, const void *data, unsigned int len)
   80.16 +static int writechn(struct connection *conn,
   80.17 +		    const void *data, unsigned int len)
   80.18  {
   80.19  	uint32_t avail;
   80.20  	void *dest;
   80.21 @@ -113,6 +113,7 @@ static int writechn(struct connection *c
   80.22  	cons = intf->rsp_cons;
   80.23  	prod = intf->rsp_prod;
   80.24  	mb();
   80.25 +
   80.26  	if (!check_indexes(cons, prod)) {
   80.27  		errno = EIO;
   80.28  		return -1;
   80.29 @@ -175,6 +176,8 @@ static int destroy_domain(void *_domain)
   80.30  	if (domain->interface)
   80.31  		munmap(domain->interface, getpagesize());
   80.32  
   80.33 +	fire_watches(NULL, "@releaseDomain", false);
   80.34 +
   80.35  	return 0;
   80.36  }
   80.37  
   80.38 @@ -197,7 +200,7 @@ static void domain_cleanup(void)
   80.39  				continue;
   80.40  		}
   80.41  		talloc_free(domain->conn);
   80.42 -		notify = 1;
   80.43 +		notify = 0; /* destroy_domain() fires the watch */
   80.44  	}
   80.45  
   80.46  	if (notify)
   80.47 @@ -247,7 +250,6 @@ static struct domain *new_domain(void *c
   80.48  	struct domain *domain;
   80.49  	int rc;
   80.50  
   80.51 -
   80.52  	domain = talloc(context, struct domain);
   80.53  	domain->port = 0;
   80.54  	domain->shutdown = 0;
   80.55 @@ -361,7 +363,7 @@ void do_introduce(struct connection *con
   80.56  		/* Now domain belongs to its connection. */
   80.57  		talloc_steal(domain->conn, domain);
   80.58  
   80.59 -		fire_watches(conn, "@introduceDomain", false);
   80.60 +		fire_watches(NULL, "@introduceDomain", false);
   80.61  	} else if ((domain->mfn == mfn) && (domain->conn != conn)) {
   80.62  		/* Use XS_INTRODUCE for recreating the xenbus event-channel. */
   80.63  		if (domain->port)
   80.64 @@ -414,8 +416,6 @@ void do_release(struct connection *conn,
   80.65  
   80.66  	talloc_free(domain->conn);
   80.67  
   80.68 -	fire_watches(conn, "@releaseDomain", false);
   80.69 -
   80.70  	send_ack(conn, XS_RELEASE);
   80.71  }
   80.72  
    81.1 --- a/tools/xenstore/xenstored_watch.c	Thu Jul 26 14:35:01 2007 -0600
    81.2 +++ b/tools/xenstore/xenstored_watch.c	Fri Jul 27 08:15:16 2007 -0600
    81.3 @@ -73,11 +73,10 @@ static void add_event(struct connection 
    81.4  	data = talloc_array(watch, char, len);
    81.5  	strcpy(data, name);
    81.6  	strcpy(data + strlen(name) + 1, watch->token);
    81.7 -        send_reply(conn, XS_WATCH_EVENT, data, len);
    81.8 +	send_reply(conn, XS_WATCH_EVENT, data, len);
    81.9  	talloc_free(data);
   81.10  }
   81.11  
   81.12 -/* FIXME: we fail to fire on out of memory.  Should drop connections. */
   81.13  void fire_watches(struct connection *conn, const char *name, bool recurse)
   81.14  {
   81.15  	struct connection *i;
   81.16 @@ -130,7 +129,7 @@ void do_watch(struct connection *conn, s
   81.17  	/* Check for duplicates. */
   81.18  	list_for_each_entry(watch, &conn->watches, list) {
   81.19  		if (streq(watch->node, vec[0]) &&
   81.20 -                    streq(watch->token, vec[1])) {
   81.21 +		    streq(watch->token, vec[1])) {
   81.22  			send_error(conn, EEXIST);
   81.23  			return;
   81.24  		}
    82.1 --- a/tools/xenstore/xsls.c	Thu Jul 26 14:35:01 2007 -0600
    82.2 +++ b/tools/xenstore/xsls.c	Fri Jul 27 08:15:16 2007 -0600
    82.3 @@ -8,6 +8,7 @@
    82.4  #include <sys/ioctl.h>
    82.5  #include <termios.h>
    82.6  
    82.7 +#define STRING_MAX PATH_MAX
    82.8  static int max_width = 80;
    82.9  static int desired_width = 60;
   82.10  
   82.11 @@ -19,7 +20,8 @@ static int desired_width = 60;
   82.12  void print_dir(struct xs_handle *h, char *path, int cur_depth, int show_perms)
   82.13  {
   82.14      char **e;
   82.15 -    char newpath[512], *val;
   82.16 +    char newpath[STRING_MAX], *val;
   82.17 +    int newpath_len;
   82.18      int i;
   82.19      unsigned int num, len;
   82.20  
   82.21 @@ -33,13 +35,26 @@ void print_dir(struct xs_handle *h, char
   82.22          unsigned int nperms;
   82.23          int linewid;
   82.24  
   82.25 -        for (linewid=0; linewid<cur_depth; linewid++) putchar(' ');
   82.26 +        /* Print indent and path basename */
   82.27 +        for (linewid=0; linewid<cur_depth; linewid++) {
   82.28 +            putchar(' ');
   82.29 +        }
   82.30          linewid += printf("%.*s",
   82.31                            (int) (max_width - TAG_LEN - linewid), e[i]);
   82.32 -        sprintf(newpath, "%s%s%s", path, 
   82.33 +
   82.34 +        /* Compose fullpath and fetch value */
   82.35 +        newpath_len = snprintf(newpath, sizeof(newpath), "%s%s%s", path, 
   82.36                  path[strlen(path)-1] == '/' ? "" : "/", 
   82.37                  e[i]);
   82.38 -        val = xs_read(h, XBT_NULL, newpath, &len);
   82.39 +        if ( newpath_len < sizeof(newpath) ) {
   82.40 +            val = xs_read(h, XBT_NULL, newpath, &len);
   82.41 +        }
   82.42 +        else {
   82.43 +            /* Path was truncated and thus invalid */
   82.44 +            val = NULL;
   82.45 +        }
   82.46 +
   82.47 +        /* Print value */
   82.48          if (val == NULL) {
   82.49              printf(":\n");
   82.50          }
   82.51 @@ -88,7 +103,7 @@ void print_dir(struct xs_handle *h, char
   82.52  
   82.53  void usage(int argc, char *argv[])
   82.54  {
   82.55 -    fprintf(stderr, "Usage: %s [-p] [path]\n", argv[0]);
   82.56 +    fprintf(stderr, "Usage: %s [-w] [-p] [path]\n", argv[0]);
   82.57  }
   82.58  
   82.59  int main(int argc, char *argv[])
   82.60 @@ -104,11 +119,14 @@ int main(int argc, char *argv[])
   82.61      if (!ret)
   82.62          max_width = ws.ws_col - PAD;
   82.63  
   82.64 -    while (0 < (c = getopt(argc, argv, "ps"))) {
   82.65 +    while (0 < (c = getopt(argc, argv, "psw"))) {
   82.66          switch (c) {
   82.67 +        case 'w':
   82.68 +            max_width= STRING_MAX - PAD;
   82.69 +            desired_width = 0;
   82.70 +            break;
   82.71          case 'p':
   82.72              show_perm = 1;
   82.73 -            max_width -= 16;
   82.74              break;
   82.75          case 's':
   82.76              socket = 1;
   82.77 @@ -121,6 +139,11 @@ int main(int argc, char *argv[])
   82.78          }
   82.79      }
   82.80  
   82.81 +    /* Adjust the width here to avoid argument order dependency */
   82.82 +    if ( show_perm ) {
   82.83 +        max_width -= 16;
   82.84 +    }
   82.85 +
   82.86      xsh = socket ? xs_daemon_open() : xs_domain_open();
   82.87      if (xsh == NULL)
   82.88          err(1, socket ? "xs_daemon_open" : "xs_domain_open");
    83.1 --- a/tools/xm-test/lib/XmTestLib/XenAPIDomain.py	Thu Jul 26 14:35:01 2007 -0600
    83.2 +++ b/tools/xm-test/lib/XmTestLib/XenAPIDomain.py	Fri Jul 27 08:15:16 2007 -0600
    83.3 @@ -23,6 +23,7 @@ import os
    83.4  import sys
    83.5  from XmTestLib import *
    83.6  from types import DictType
    83.7 +from acm import *
    83.8  
    83.9  
   83.10  class XenAPIConfig:
   83.11 @@ -38,6 +39,9 @@ class XenAPIConfig:
   83.12                             'kernel' : 'PV_kernel',
   83.13                             'ramdisk': 'PV_ramdisk',
   83.14                             'root'   : 'PV_args'}
   83.15 +        if isACMEnabled():
   83.16 +            #A default so every VM can start with ACM enabled
   83.17 +            self.opts["security_label"] = "ACM:xm-test:red"
   83.18  
   83.19      def setOpt(self, name, value):
   83.20          """Set an option in the config"""
    84.1 --- a/tools/xm-test/lib/XmTestLib/acm.py	Thu Jul 26 14:35:01 2007 -0600
    84.2 +++ b/tools/xm-test/lib/XmTestLib/acm.py	Fri Jul 27 08:15:16 2007 -0600
    84.3 @@ -19,6 +19,9 @@
    84.4  """
    84.5  from Test import *
    84.6  from xen.util import security
    84.7 +from xen.xm.main import server
    84.8 +from xen.util import xsconstants
    84.9 +import re
   84.10  
   84.11  try:
   84.12      from acm_config import *
   84.13 @@ -32,16 +35,47 @@ def isACMEnabled():
   84.14      return security.on()
   84.15  
   84.16  
   84.17 +def getSystemPolicyName():
   84.18 +    s,o = traceCommand("xm getpolicy")
   84.19 +    m = re.compile("Policy name[\s]*: ([A-z\-]+)").search(o)
   84.20 +    if m:
   84.21 +        polname = m.group(1)
   84.22 +        return polname
   84.23 +    return ""
   84.24 +
   84.25 +
   84.26 +def ACMLoadPolicy_XenAPI(policy='xm-test'):
   84.27 +    polname = getSystemPolicyName()
   84.28 +    if polname != policy:
   84.29 +        # Try it, maybe it's not activated
   84.30 +        traceCommand("xm setpolicy %s %s" %
   84.31 +                     (xsconstants.XS_POLICY_ACM, policy))
   84.32 +        polname = getSystemPolicyName()
   84.33 +        if polname != policy:
   84.34 +            FAIL("Need to have a system with no or policy '%s' active, "
   84.35 +                 "not %s" % (policy,polname))
   84.36 +        else:
   84.37 +            s, o = traceCommand("xm activatepolicy --load")
   84.38 +    else:
   84.39 +        s, o = traceCommand("xm activatepolicy --load")
   84.40 +        if not re.search("Successfully", o):
   84.41 +            FAIL("Could not set the policy '%s'." % policy)
   84.42 +
   84.43 +
   84.44  def ACMLoadPolicy(policy='xm-test'):
   84.45 -    s, o = traceCommand("xm makepolicy %s" % (policy))
   84.46 -    if s != 0:
   84.47 -        FAIL("Need to be able to do 'xm makepolicy %s' but could not" %
   84.48 -             (policy))
   84.49 -    s, o = traceCommand("xm loadpolicy %s" % (policy))
   84.50 -    if s != 0:
   84.51 -        FAIL("Could not load the required policy '%s'.\n"
   84.52 -             "Start the system without any policy.\n%s" %
   84.53 -             (policy, o))
   84.54 +    from xen.xm import main
   84.55 +    if main.serverType == main.SERVER_XEN_API:
   84.56 +        ACMLoadPolicy_XenAPI()
   84.57 +    else:
   84.58 +        s, o = traceCommand("xm makepolicy %s" % (policy))
   84.59 +        if s != 0:
   84.60 +            FAIL("Need to be able to do 'xm makepolicy %s' but could not" %
   84.61 +                 (policy))
   84.62 +        s, o = traceCommand("xm loadpolicy %s" % (policy))
   84.63 +        if s != 0:
   84.64 +            FAIL("Could not load the required policy '%s'.\n"
   84.65 +                 "Start the system without any policy.\n%s" %
   84.66 +                 (policy, o))
   84.67  
   84.68  def ACMPrepareSystem(resources):
   84.69      if isACMEnabled():
    85.1 --- a/tools/xm-test/tests/security-acm/01_security-acm_basic.py	Thu Jul 26 14:35:01 2007 -0600
    85.2 +++ b/tools/xm-test/tests/security-acm/01_security-acm_basic.py	Fri Jul 27 08:15:16 2007 -0600
    85.3 @@ -15,6 +15,7 @@
    85.4  
    85.5  from XmTestLib import *
    85.6  from xen.util import security
    85.7 +from xen.util import xsconstants
    85.8  import commands
    85.9  import os
   85.10  import re
   85.11 @@ -28,7 +29,7 @@ if not isACMEnabled():
   85.12      SKIP("Not running this test since ACM not enabled.")
   85.13  
   85.14  status, output = traceCommand("xm makepolicy %s" % (testpolicy))
   85.15 -if status != 0 or output != "":
   85.16 +if status != 0:
   85.17      FAIL("'xm makepolicy' failed with status %d and output\n%s" %
   85.18           (status,output));
   85.19  
   85.20 @@ -47,7 +48,7 @@ status, output = traceCommand("xm rmlabe
   85.21  status, output = traceCommand("xm addlabel %s dom %s %s" %
   85.22                                (testlabel, vmconfigfile, testpolicy))
   85.23  if status != 0:
   85.24 -    FAIL("'xm addlabel' failed with status %d.\n" % status)
   85.25 +    FAIL("(1) 'xm addlabel' failed with status %d.\n" % status)
   85.26  
   85.27  status, output = traceCommand("xm getlabel dom %s" %
   85.28                                (vmconfigfile))
   85.29 @@ -55,8 +56,9 @@ status, output = traceCommand("xm getlab
   85.30  if status != 0:
   85.31      FAIL("'xm getlabel' failed with status %d, output:\n%s" %
   85.32           (status, output))
   85.33 -if output != "policy=%s,label=%s" % (testpolicy,testlabel):
   85.34 -    FAIL("Received unexpected output from 'xm getlabel': \n%s" %
   85.35 +if output != "policytype=%s,policy=%s,label=%s" % \
   85.36 +             (xsconstants.ACM_POLICY_ID, testpolicy, testlabel):
   85.37 +    FAIL("(1) Received unexpected output from 'xm getlabel dom': \n%s" %
   85.38           (output))
   85.39  
   85.40  
   85.41 @@ -74,30 +76,34 @@ status, output = traceCommand("xm getlab
   85.42                                (vmconfigfile))
   85.43  
   85.44  if output != "Error: 'Domain not labeled'":
   85.45 -    FAIL("Received unexpected output from 'xm getlabel': \n%s" %
   85.46 +    FAIL("(2) Received unexpected output from 'xm getlabel dom': \n%s" %
   85.47           (output))
   85.48  
   85.49  #Whatever label the resource might have, remove it
   85.50  status, output = traceCommand("xm rmlabel res %s" %
   85.51                                (testresource))
   85.52 +if status != 0:
   85.53 +    FAIL("'xm rmlabel' on resource failed with status %d.\n" % status)
   85.54  
   85.55  status, output = traceCommand("xm addlabel %s res %s %s" %
   85.56                                (testlabel, testresource, testpolicy))
   85.57  if status != 0:
   85.58 -    FAIL("'xm addlabel' on resource failed with status %d.\n" % status)
   85.59 +    FAIL("(2) 'xm addlabel' on resource failed with status %d.\n" % status)
   85.60  
   85.61  status, output = traceCommand("xm getlabel res %s" % (testresource))
   85.62  
   85.63  if status != 0:
   85.64      FAIL("'xm getlabel' on resource failed with status %d, output:\n%s" %
   85.65           (status, output))
   85.66 -if output != "policy=%s,label=%s" % (testpolicy,testlabel):
   85.67 -    FAIL("Received unexpected output from 'xm getlabel': \n%s" %
   85.68 +if output != "%s:%s:%s" % (xsconstants.ACM_POLICY_ID,\
   85.69 +                           testpolicy,testlabel):
   85.70 +    FAIL("Received unexpected output from 'xm getlabel res': \n%s" %
   85.71           (output))
   85.72  
   85.73  status, output = traceCommand("xm resources")
   85.74  
   85.75  if status != 0:
   85.76 +    print "status = %s" % str(status)
   85.77      FAIL("'xm resources' did not run properly")
   85.78  if not re.search(security.unify_resname(testresource), output):
   85.79      FAIL("'xm resources' did not show the tested resource '%s'." %
   85.80 @@ -117,5 +123,5 @@ status, output = traceCommand("xm getlab
   85.81                                (testresource))
   85.82  
   85.83  if output != "Error: 'Resource not labeled'":
   85.84 -    FAIL("Received unexpected output from 'xm getlabel': \n%s" %
   85.85 +    FAIL("Received unexpected output from 'xm getlabel res': \n%s" %
   85.86           (output))
    86.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    86.2 +++ b/tools/xm-test/tests/security-acm/07_security-acm_pol_update.py	Fri Jul 27 08:15:16 2007 -0600
    86.3 @@ -0,0 +1,303 @@
    86.4 +#!/usr/bin/python
    86.5 +
    86.6 +# Copyright (C) International Business Machines Corp., 2006
    86.7 +# Author: Stefan Berger <stefanb@us.ibm.com>
    86.8 +
    86.9 +# Test to exercise the xspolicy class
   86.10 +
   86.11 +from XmTestLib import xapi
   86.12 +from XmTestLib.XenAPIDomain import XmTestAPIDomain
   86.13 +from XmTestLib import *
   86.14 +from xen.xend import XendAPIConstants
   86.15 +from xen.util import acmpolicy, security, xsconstants
   86.16 +from xen.util.acmpolicy import ACMPolicy
   86.17 +from xen.xend.XendDomain import DOM0_UUID
   86.18 +
   86.19 +import commands
   86.20 +import os
   86.21 +import base64
   86.22 +
   86.23 +xm_test = {}
   86.24 +xm_test['policyname'] = "xm-test"
   86.25 +xm_test['date'] = "Fri Sep 29 14:44:38 2006"
   86.26 +xm_test['url']  = None
   86.27 +
   86.28 +vm_label_red   = "%s:xm-test:red" % xsconstants.ACM_POLICY_ID
   86.29 +vm_label_green = "%s:xm-test:green" % xsconstants.ACM_POLICY_ID
   86.30 +vm_label_blue  = "%s:xm-test:blue" % xsconstants.ACM_POLICY_ID
   86.31 +vm_label_sys   = "%s:xm-test:SystemManagement" % xsconstants.ACM_POLICY_ID
   86.32 +
   86.33 +vm_label_black = "%s:xm-test:black"
   86.34 +
   86.35 +session = xapi.connect()
   86.36 +
   86.37 +oldlabel = session.xenapi.VM.get_security_label(DOM0_UUID)
   86.38 +
   86.39 +ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
   86.40 +                                               vm_label_sys,
   86.41 +                                               oldlabel)
   86.42 +if int(ssidref) <= 0 or int(ssidref) != 0x00010001:
   86.43 +    FAIL("(0) Domain-0 label for '%s' has unexpected failure: %08x" %
   86.44 +         (vm_label_sys, int(ssidref)))
   86.45 +print "ssidref for '%s' is 0x%08x" % (vm_label_sys, int(ssidref))
   86.46 +
   86.47 +
   86.48 +xstype = session.xenapi.XSPolicy.get_xstype()
   86.49 +if int(xstype) & xsconstants.XS_POLICY_ACM == 0:
   86.50 +    SKIP("ACM not enabled/compiled in Xen")
   86.51 +
   86.52 +policystate = session.xenapi.XSPolicy.get_xspolicy()
   86.53 +if not policystate.has_key('xs_ref'):
   86.54 +    FAIL("get_xspolicy must return member 'xs_ref'")
   86.55 +
   86.56 +xs_ref = policystate['xs_ref']
   86.57 +if xs_ref != "":
   86.58 +    origpolicyxml = session.xenapi.ACMPolicy.get_xml(xs_ref)
   86.59 +else:
   86.60 +    origpolicyxml = ""
   86.61 +
   86.62 +f = open("xm-test-security_policy.xml", 'r')
   86.63 +if f:
   86.64 +    newpolicyxml = f.read()
   86.65 +    f.close()
   86.66 +else:
   86.67 +    FAIL("Could not read 'xm-test' policy")
   86.68 +
   86.69 +try:
   86.70 +    os.unlink("/boot/xm-test.bin")
   86.71 +except:
   86.72 +    pass
   86.73 +
   86.74 +policystate = session.xenapi.XSPolicy.get_xspolicy()
   86.75 +
   86.76 +if int(policystate['type']) == 0:
   86.77 +    policystate = session.xenapi.XSPolicy.set_xspolicy(
   86.78 +                          xsconstants.XS_POLICY_ACM,
   86.79 +                          newpolicyxml,
   86.80 +                          xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT,
   86.81 +                          1)
   86.82 +    if int(policystate['flags']) == -1:
   86.83 +        FAIL("Could not set the new policy.")
   86.84 +
   86.85 +print "state of policy = %s " % policystate
   86.86 +
   86.87 +rc = session.xenapi.XSPolicy.activate_xspolicy(
   86.88 +                          policystate['xs_ref'],
   86.89 +                          xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT)
   86.90 +if int(rc) != xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT:
   86.91 +    FAIL("Could not activate the current policy: rc = %08x" % int(rc))
   86.92 +
   86.93 +if not os.path.exists("/boot/xm-test.bin"):
   86.94 +    FAIL("Binary policy was not installed. Check grub config file.")
   86.95 +
   86.96 +policystate = session.xenapi.XSPolicy.get_xspolicy()
   86.97 +
   86.98 +if int(policystate['flags']) != xsconstants.XS_INST_BOOT | \
   86.99 +                                xsconstants.XS_INST_LOAD:
  86.100 +    FAIL("Flags (%x) are not indicating the correct state of the policy.",
  86.101 +         int(policystate['flags']))
  86.102 +
  86.103 +policystate = session.xenapi.XSPolicy.get_xspolicy()
  86.104 +xs_ref = policystate['xs_ref']
  86.105 +
  86.106 +newpolicyxml = None
  86.107 +f = open("xm-test-new-security_policy.xml", 'r')
  86.108 +if f:
  86.109 +    newpolicyxml = f.read()
  86.110 +    f.close()
  86.111 +else:
  86.112 +    FAIL("Could not read 'xm-test-new' policy")
  86.113 +
  86.114 +cur_acmpol = ACMPolicy(xml = policystate['repr'])
  86.115 +new_acmpol = ACMPolicy(xml = newpolicyxml)
  86.116 +
  86.117 +new_acmpol.update_frompolicy(cur_acmpol)
  86.118 +
  86.119 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  86.120 +                          new_acmpol.toxml(),
  86.121 +                          xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT,
  86.122 +                          1)
  86.123 +
  86.124 +f = open("xm-test-security_policy.xml", 'r')
  86.125 +if f:
  86.126 +    newpolicyxml = f.read()
  86.127 +    f.close()
  86.128 +else:
  86.129 +    FAIL("Could not read 'xm-test-new' policy")
  86.130 +
  86.131 +cur_acmpol = new_acmpol
  86.132 +new_acmpol = ACMPolicy(xml = newpolicyxml)
  86.133 +
  86.134 +new_acmpol.update_frompolicy(cur_acmpol)
  86.135 +
  86.136 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  86.137 +                          new_acmpol.toxml(),
  86.138 +                          xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT,
  86.139 +                          1)
  86.140 +
  86.141 +dom0_lab = session.xenapi.VM.get_security_label(DOM0_UUID)
  86.142 +
  86.143 +ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
  86.144 +                                               vm_label_sys, dom0_lab)
  86.145 +if int(ssidref) <= 0 or int(ssidref) != 0x00010001:
  86.146 +    FAIL("(1) Domain-0 label for '%s' has unexpected failure: %08x" %
  86.147 +         (vm_label_sys, int(ssidref)))
  86.148 +print "ssidref for '%s' is 0x%08x" % (vm_label_sys, int(ssidref))
  86.149 +
  86.150 +try:
  86.151 +    ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
  86.152 +                                                   vm_label_black,
  86.153 +                                                   vm_label_sys)
  86.154 +    FAIL("Could set label '%s', although it's not in the policy. "
  86.155 +         "ssidref=%s" % (vm_label_black, ssidref))
  86.156 +except:
  86.157 +    pass
  86.158 +
  86.159 +ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
  86.160 +                                               vm_label_red,
  86.161 +                                               vm_label_sys)
  86.162 +if int(ssidref) <= 0:
  86.163 +    FAIL("(2) Domain-0 label for '%s' has unexpected failure: %08x" %
  86.164 +         (vm_label_red, int(ssidref)))
  86.165 +print "ssidref for '%s' is 0x%08x" % (vm_label_red, int(ssidref))
  86.166 +
  86.167 +label = session.xenapi.VM.get_security_label(DOM0_UUID)
  86.168 +
  86.169 +if label != vm_label_red:
  86.170 +    FAIL("Dom0 label '%s' not as expected '%s'" % (label, vm_label_red))
  86.171 +
  86.172 +
  86.173 +ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
  86.174 +                                               vm_label_sys,
  86.175 +                                               vm_label_red)
  86.176 +if int(ssidref) <= 0 or int(ssidref) != 0x00010001:
  86.177 +    FAIL("(3) Domain-0 label for '%s' has unexpected failure: %08x" %
  86.178 +         (vm_label_sys, int(ssidref)))
  86.179 +
  86.180 +label = session.xenapi.VM.get_security_label(DOM0_UUID)
  86.181 +
  86.182 +if label != vm_label_sys:
  86.183 +    FAIL("Dom0 label '%s' not as expected '%s'" % label, dom0_label)
  86.184 +
  86.185 +header = session.xenapi.ACMPolicy.get_header(xs_ref)
  86.186 +
  86.187 +if header['policyname'] != xm_test['policyname']:
  86.188 +    FAIL("Name in header is '%s', expected is '%s'." %
  86.189 +         (header['policyname'],xm_test['policyname']))
  86.190 +if header['date'] != xm_test['date']:
  86.191 +    FAIL("Date in header is '%s', expected is '%s'." %
  86.192 +         (header['date'],xm_test['date']))
  86.193 +if header.has_key("url") and header['url' ] != xm_test['url' ]:
  86.194 +    FAIL("URL  in header is '%s', expected is '%s'." %
  86.195 +         (header['url' ],xm_test['url' ]))
  86.196 +
  86.197 +# Create another domain
  86.198 +try:
  86.199 +    # XmTestAPIDomain tries to establish a connection to XenD
  86.200 +    domain = XmTestAPIDomain(extraConfig={ 'security_label' : vm_label_blue })
  86.201 +except Exception, e:
  86.202 +    SKIP("Skipping test. Error: %s" % str(e))
  86.203 +
  86.204 +
  86.205 +vm_uuid = domain.get_uuid()
  86.206 +
  86.207 +res = session.xenapi.VM.get_security_label(vm_uuid)
  86.208 +if res != vm_label_blue:
  86.209 +    FAIL("VM has security label '%s', expected is '%s'" %
  86.210 +         (res, vm_label_blue))
  86.211 +
  86.212 +try:
  86.213 +    domain.start(noConsole=True)
  86.214 +except:
  86.215 +    FAIL("Could not create domain")
  86.216 +
  86.217 +
  86.218 +# Attempt to relabel the running domain
  86.219 +ssidref = session.xenapi.VM.set_security_label(vm_uuid,
  86.220 +                                               vm_label_red,
  86.221 +                                               vm_label_blue)
  86.222 +if int(ssidref) <= 0:
  86.223 +    FAIL("Could not relabel running domain to '%s'." % vm_label_red)
  86.224 +
  86.225 +# user domain is 'red', dom0 is current 'SystemManagement'.
  86.226 +# Try to move domain-0 to 'red' first, then to 'blue'.
  86.227 +
  86.228 +# Moving domain-0 to 'red' should work
  86.229 +ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
  86.230 +                                               vm_label_red,
  86.231 +                                               vm_label_sys)
  86.232 +if int(ssidref) <= 0:
  86.233 +    FAIL("Could not label domain-0 '%s'" % vm_label_red)
  86.234 +
  86.235 +# Moving the guest domain to 'blue' should not work due to conflict set
  86.236 +try:
  86.237 +    ssidref = session.xenapi.VM.set_security_label(vm_uuid,
  86.238 +                                                   vm_label_blue,
  86.239 +                                                   vm_label_red)
  86.240 +    FAIL("Could label guest domain with '%s', although this is in a conflict "
  86.241 +         "set. ssidref=%x" % (vm_label_blue,int(ssidref)))
  86.242 +except:
  86.243 +    pass
  86.244 +
  86.245 +label = session.xenapi.VM.get_security_label(vm_uuid)
  86.246 +if label != vm_label_red:
  86.247 +    FAIL("User domain has wrong label '%s', expected '%s'." %
  86.248 +         (label, vm_label_red))
  86.249 +
  86.250 +label = session.xenapi.VM.get_security_label(DOM0_UUID)
  86.251 +if label != vm_label_red:
  86.252 +    FAIL("Domain-0 has wrong label '%s'; expected '%s'." %
  86.253 +         (label, vm_label_red))
  86.254 +
  86.255 +ssidref = session.xenapi.VM.set_security_label(DOM0_UUID,
  86.256 +                                               vm_label_sys,
  86.257 +                                               vm_label_red)
  86.258 +if int(ssidref) < 0:
  86.259 +    FAIL("Could not set the domain-0 security label to '%s'." %
  86.260 +         (vm_label_sys))
  86.261 +
  86.262 +# pause the domain and relabel it...
  86.263 +session.xenapi.VM.pause(vm_uuid)
  86.264 +
  86.265 +label = session.xenapi.VM.get_security_label(vm_uuid)
  86.266 +if label != vm_label_red:
  86.267 +    FAIL("User domain has wrong label '%s', expected '%s'." %
  86.268 +         (label, vm_label_red))
  86.269 +
  86.270 +ssidref = session.xenapi.VM.set_security_label(vm_uuid,
  86.271 +                                               vm_label_blue,
  86.272 +                                               vm_label_red)
  86.273 +print "guest domain new label '%s'; ssidref is 0x%08x" % \
  86.274 +      (vm_label_blue, int(ssidref))
  86.275 +if int(ssidref) <= 0:
  86.276 +    FAIL("Could not label guest domain with '%s'" % (vm_label_blue))
  86.277 +
  86.278 +label = session.xenapi.VM.get_security_label(vm_uuid)
  86.279 +if label != vm_label_blue:
  86.280 +    FAIL("User domain has wrong label '%s', expected '%s'." %
  86.281 +         (label, vm_label_blue))
  86.282 +
  86.283 +session.xenapi.VM.unpause(vm_uuid)
  86.284 +
  86.285 +rc = session.xenapi.VM.suspend(vm_uuid)
  86.286 +
  86.287 +ssidref = session.xenapi.VM.set_security_label(vm_uuid,
  86.288 +                                               vm_label_green,
  86.289 +                                               vm_label_blue)
  86.290 +print "guest domain new label '%s'; ssidref is 0x%08x" % \
  86.291 +      (vm_label_green, int(ssidref))
  86.292 +if int(ssidref) < 0:
  86.293 +    FAIL("Could not label suspended guest domain with '%s'" % (vm_label_blue))
  86.294 +
  86.295 +label = session.xenapi.VM.get_security_label(vm_uuid)
  86.296 +if label != vm_label_green:
  86.297 +    FAIL("User domain has wrong label '%s', expected '%s'." %
  86.298 +         (label, vm_label_green))
  86.299 +
  86.300 +
  86.301 +rc = session.xenapi.VM.resume(vm_uuid, False)
  86.302 +
  86.303 +label = session.xenapi.VM.get_security_label(vm_uuid)
  86.304 +if label != vm_label_green:
  86.305 +    FAIL("User domain has wrong label '%s', expected '%s'." %
  86.306 +         (label, vm_label_green))
    87.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    87.2 +++ b/tools/xm-test/tests/security-acm/08_security-acm_xapi.py	Fri Jul 27 08:15:16 2007 -0600
    87.3 @@ -0,0 +1,354 @@
    87.4 +#!/usr/bin/python
    87.5 +
    87.6 +# Copyright (C) International Business Machines Corp., 2007
    87.7 +# Author: Stefan Berger <stefanb@us.ibm.com>
    87.8 +
    87.9 +# VM creation test with labeled VM and labeled VDI
   87.10 +
   87.11 +from XmTestLib import xapi
   87.12 +from XmTestLib.XenAPIDomain import XmTestAPIDomain
   87.13 +from XmTestLib import *
   87.14 +from xen.xend import XendAPIConstants
   87.15 +from xen.util import acmpolicy, security, xsconstants
   87.16 +import commands
   87.17 +import os
   87.18 +
   87.19 +vm_label_red    = xsconstants.ACM_POLICY_ID + ":xm-test:red"
   87.20 +vm_label_green  = xsconstants.ACM_POLICY_ID + ":xm-test:green"
   87.21 +vdi_label_red   = xsconstants.ACM_POLICY_ID + ":xm-test:red"
   87.22 +vdi_label_green = xsconstants.ACM_POLICY_ID + ":xm-test:green"
   87.23 +
   87.24 +vdi_file = "/dev/ram0"
   87.25 +vdi_path = "phy:" + vdi_file
   87.26 +
   87.27 +#Note:
   87.28 +# If during the suspend/resume operations 'red' instead of 'green' is
   87.29 +# used, the Chinese Wall policy goes into effect and disallows the
   87.30 +# suspended VM from being resumed...
   87.31 +
   87.32 +try:
   87.33 +    # XmTestAPIDomain tries to establish a connection to XenD
   87.34 +    domain = XmTestAPIDomain(extraConfig={ 'security_label' : vm_label_red })
   87.35 +except Exception, e:
   87.36 +    SKIP("Skipping test. Error: %s" % str(e))
   87.37 +
   87.38 +vm_uuid = domain.get_uuid()
   87.39 +
   87.40 +session = xapi.connect()
   87.41 +xstype = session.xenapi.XSPolicy.get_xstype()
   87.42 +if int(xstype) & xsconstants.XS_POLICY_ACM == 0:
   87.43 +    SKIP("ACM not enabled/compiled in Xen")
   87.44 +
   87.45 +f = open("xm-test-security_policy.xml", 'r')
   87.46 +if f:
   87.47 +    newpolicyxml = f.read()
   87.48 +    f.close()
   87.49 +else:
   87.50 +    FAIL("Could not read 'xm-test' policy")
   87.51 +
   87.52 +policystate = session.xenapi.XSPolicy.get_xspolicy()
   87.53 +if int(policystate['type']) == 0:
   87.54 +    policystate = session.xenapi.XSPolicy.set_xspolicy(
   87.55 +                         xsconstants.XS_POLICY_ACM,
   87.56 +                         newpolicyxml,
   87.57 +                         xsconstants.XS_INST_BOOT | xsconstants.XS_INST_LOAD,
   87.58 +                         True)
   87.59 +    if int(policystate['flags']) == -1:
   87.60 +        FAIL("Could not set the new policy.")
   87.61 +
   87.62 +policystate = session.xenapi.XSPolicy.get_xspolicy()
   87.63 +print "policystate = %s" % policystate
   87.64 +acm_ref = policystate['xs_ref']
   87.65 +
   87.66 +
   87.67 +#
   87.68 +# Some tests with labeling of resources
   87.69 +#
   87.70 +labels = session.xenapi.XSPolicy.get_labeled_resources()
   87.71 +print "labeled resources are:\n%s" % labels
   87.72 +
   87.73 +oldlabel = session.xenapi.XSPolicy.get_resource_label("phy:/dev/ram0")
   87.74 +
   87.75 +rc  = session.xenapi.XSPolicy.set_resource_label("phy:/dev/ram0", "",
   87.76 +                                                 oldlabel)
   87.77 +
   87.78 +rc  = session.xenapi.XSPolicy.set_resource_label("phy:/dev/ram0",
   87.79 +                                                 vdi_label_green,
   87.80 +                                                 "")
   87.81 +
   87.82 +res = session.xenapi.XSPolicy.get_resource_label("phy:/dev/ram0")
   87.83 +if res != vdi_label_green:
   87.84 +    FAIL("(1) get_resource_label returned unexpected result %s, wanted %s" %
   87.85 +         (res, vdi_label_green))
   87.86 +
   87.87 +
   87.88 +#
   87.89 +# Some test with labeling of VMs
   87.90 +#
   87.91 +
   87.92 +res = session.xenapi.VM.get_security_label(vm_uuid)
   87.93 +
   87.94 +if res != vm_label_red:
   87.95 +    FAIL("VM.get_security_label returned wrong security label '%s'." % res)
   87.96 +
   87.97 +res = session.xenapi.VM.set_security_label(vm_uuid, vm_label_green,
   87.98 +                                                    vm_label_red)
   87.99 +
  87.100 +res = session.xenapi.VM.get_security_label(vm_uuid)
  87.101 +if res != vm_label_green:
  87.102 +     FAIL("VM does not show expected label '%s' but '%s'." %
  87.103 +          (vm_label_green, res))
  87.104 +
  87.105 +res = session.xenapi.VM.set_security_label(vm_uuid, "", vm_label_green)
  87.106 +if int(res) != 0:
  87.107 +    FAIL("Should be able to unlabel the domain while it's halted.")
  87.108 +
  87.109 +res = session.xenapi.VM.get_security_label(vm_uuid)
  87.110 +if res != "":
  87.111 +    FAIL("Unexpected VM security label after removal: %s" % res)
  87.112 +
  87.113 +res = session.xenapi.VM.set_security_label(vm_uuid, vm_label_red, res)
  87.114 +if int(res) != 0:
  87.115 +    FAIL("Could not label the VM to '%s'" % vm_label_red)
  87.116 +
  87.117 +res = session.xenapi.VM.get_security_label(vm_uuid)
  87.118 +if res != vm_label_red:
  87.119 +    FAIL("VM has wrong label '%s', expected '%s'." % (res, vm_label_red))
  87.120 +
  87.121 +sr_uuid = session.xenapi.SR.get_by_name_label("Local")
  87.122 +if len(sr_uuid) == 0:
  87.123 +    FAIL("Could not get a handle on SR 'Local'")
  87.124 +
  87.125 +
  87.126 +vdi_rec = { 'name_label'  : "My disk",
  87.127 +            'SR'          : sr_uuid[0],
  87.128 +            'virtual_size': 0,
  87.129 +            'sector_size' : 512,
  87.130 +            'parent'      : '',
  87.131 +            'SR_name'     : 'Local',
  87.132 +            'type'        : 'system',
  87.133 +            'shareable'   : False,
  87.134 +            'read-only'   : False,
  87.135 +            'other_config': {'location': vdi_path}
  87.136 +}
  87.137 +
  87.138 +vdi_ref = session.xenapi.VDI.create(vdi_rec)
  87.139 +
  87.140 +res = session.xenapi.VDI.get_name_label(vdi_ref)
  87.141 +if res != vdi_rec['name_label']:
  87.142 +    print "Destroying VDI now"
  87.143 +    session.xenapi.VDI.destroy(vdi_ref)
  87.144 +    FAIL("VDI_get_name_label return wrong information")
  87.145 +
  87.146 +res = session.xenapi.VDI.get_record(vdi_ref)
  87.147 +print "vdi_record : %s" % res
  87.148 +
  87.149 +oldlabel = session.xenapi.XSPolicy.get_resource_label(vdi_path)
  87.150 +
  87.151 +#Remove label from VDI device
  87.152 +rc  = session.xenapi.XSPolicy.set_resource_label(vdi_path,
  87.153 +                                                 "",
  87.154 +                                                 oldlabel)
  87.155 +
  87.156 +
  87.157 +# Attach a VBD to the VM
  87.158 +
  87.159 +vbd_rec = { 'VM'      : vm_uuid,
  87.160 +            'VDI'     : vdi_ref,
  87.161 +            'device'  : "xvda1",
  87.162 +            'mode'    : 1,
  87.163 +            'bootable': 0,
  87.164 +}
  87.165 +
  87.166 +vbd_ref = session.xenapi.VBD.create(vbd_rec)
  87.167 +
  87.168 +res = session.xenapi.VBD.get_record(vbd_ref)
  87.169 +
  87.170 +try:
  87.171 +    domain.start(noConsole=True)
  87.172 +    # Should not get here.
  87.173 +    print "Destroying VDI now"
  87.174 +    session.xenapi.VDI.destroy(vdi_ref)
  87.175 +    FAIL("Could start VM with a VBD that it is not allowed to access.")
  87.176 +except:
  87.177 +    pass
  87.178 +    print "Could not create domain -- that's good"
  87.179 +
  87.180 +
  87.181 +#
  87.182 +# Label the VDI now
  87.183 +#
  87.184 +
  87.185 +rc    = session.xenapi.VDI.set_security_label(vdi_ref, vdi_label_red, "")
  87.186 +if int(rc) != 0:
  87.187 +    FAIL("Could not set the VDI label to '%s'" % vdi_label_red)
  87.188 +
  87.189 +label = session.xenapi.VDI.get_security_label(vdi_ref)
  87.190 +if label != vdi_label_red:
  87.191 +    session.xenapi.VDI.destroy(vdi_ref)
  87.192 +    FAIL("Unexpected label '%s' on VDI, wanted '%s'" %
  87.193 +         (label, vdi_label_red))
  87.194 +
  87.195 +rc    = session.xenapi.VDI.set_security_label(vdi_ref, "", label)
  87.196 +if int(rc) != 0:
  87.197 +    session.xenapi.VDI.destroy(vdi_ref)
  87.198 +    FAIL("Should be able to unlabel VDI.")
  87.199 +
  87.200 +rc    = session.xenapi.VDI.set_security_label(vdi_ref, vdi_label_red, "")
  87.201 +if int(rc) != 0:
  87.202 +    session.xenapi.VDI.destroy(vdi_ref)
  87.203 +    FAIL("Should be able to label VDI with label '%s'" % vid_label_red)
  87.204 +
  87.205 +res   = session.xenapi.XSPolicy.get_resource_label(vdi_path)
  87.206 +if res != vdi_label_red:
  87.207 +    session.xenapi.VDI.destroy(vdi_ref)
  87.208 +    FAIL("(2) get_resource_label on %s returned unexpected result %s, wanted '%s'" %
  87.209 +         (vdi_path, res, vdi_label_red))
  87.210 +
  87.211 +res = session.xenapi.VDI.get_security_label(vdi_ref)
  87.212 +if res != vdi_label_red:
  87.213 +    session.xenapi.VDI.destroy(vdi_ref)
  87.214 +    FAIL("get_security_label returned unexpected result %s, wanted '%s'" %
  87.215 +         (res, vdi_label_red))
  87.216 +
  87.217 +domain.start(noConsole=True)
  87.218 +
  87.219 +console = domain.getConsole()
  87.220 +
  87.221 +domName = domain.getName()
  87.222 +
  87.223 +try:
  87.224 +    run = console.runCmd("cat /proc/interrupts")
  87.225 +except ConsoleError, e:
  87.226 +    saveLog(console.getHistory())
  87.227 +    FAIL("Could not access proc-filesystem")
  87.228 +
  87.229 +# Try to relabel while VM is running
  87.230 +try:
  87.231 +    res = session.xenapi.VM.set_security_label(vm_uuid, vm_label_green,
  87.232 +                                               vm_label_red)
  87.233 +except:
  87.234 +    pass
  87.235 +
  87.236 +lab = session.xenapi.VM.get_security_label(vm_uuid)
  87.237 +if lab == vm_label_green:
  87.238 +    FAIL("Should not be able to reset the security label while running."
  87.239 +         "tried to set to %s, got %s, old: %s" %(vm_label_green, lab,
  87.240 +         vm_label_red))
  87.241 +
  87.242 +
  87.243 +#
  87.244 +# Suspend the domain and relabel it
  87.245 +#
  87.246 +
  87.247 +try:
  87.248 +    status, output = traceCommand("xm suspend %s" % domName,
  87.249 +                                  timeout=30)
  87.250 +except TimeoutError, e:
  87.251 +    session.xenapi.VDI.destroy(vdi_ref)
  87.252 +    FAIL("Failure from suspending VM: %s." % str(e))
  87.253 +
  87.254 +# Try to relabel while VM is suspended -- this should work
  87.255 +
  87.256 +rc  = session.xenapi.VM.set_security_label(vm_uuid, vm_label_green,
  87.257 +                                           vm_label_red)
  87.258 +if int(rc) != 0:
  87.259 +    FAIL("VM security label could not be set to %s" % vm_label_green)
  87.260 +
  87.261 +res = session.xenapi.VM.get_security_label(vm_uuid)
  87.262 +if res != vm_label_green:
  87.263 +    session.xenapi.VDI.destroy(vdi_ref)
  87.264 +    FAIL("VM (suspended) has label '%s', expected '%s'." %
  87.265 +         (res, vm_label_green))
  87.266 +
  87.267 +status, output = traceCommand("xm list")
  87.268 +
  87.269 +#Try to resume now -- should fail due to denied access to block device
  87.270 +try:
  87.271 +    status, output = traceCommand("xm resume %s" % domName,
  87.272 +                                  timeout=30)
  87.273 +    if status == 0:
  87.274 +        session.xenapi.VDI.destroy(vdi_ref)
  87.275 +        FAIL("Could resume re-labeled VM: %s" % output)
  87.276 +except Exception, e:
  87.277 +    session.xenapi.VDI.destroy(vdi_ref)
  87.278 +    FAIL("1. Error resuming the VM: %s." % str(e))
  87.279 +
  87.280 +# Relabel VM so it would resume
  87.281 +res = session.xenapi.VM.set_security_label(vm_uuid, vm_label_red,
  87.282 +                                           vm_label_green)
  87.283 +if int(res) != 0:
  87.284 +    session.xenapi.VDI.destroy(vdi_ref)
  87.285 +    FAIL("Could not relabel VM to have it resume.")
  87.286 +
  87.287 +res = session.xenapi.VM.get_security_label(vm_uuid)
  87.288 +if res != vm_label_red:
  87.289 +    session.xenapi.VDI.destroy(vdi_ref)
  87.290 +    FAIL("VM (suspended) has label '%s', expected '%s'." %
  87.291 +         (res, vm_label_red))
  87.292 +
  87.293 +
  87.294 +# Relabel the resource so VM should not resume
  87.295 +try:
  87.296 +    session.xenapi.XSPolicy.set_resource_label(vdi_path,
  87.297 +                                               vdi_label_green,
  87.298 +                                               "")
  87.299 +except Exception, e:
  87.300 +    session.xenapi.VDI.destroy(vdi_ref)
  87.301 +    FAIL("Could not label the VDI to '%s': %x" %
  87.302 +         (vdi_label_green, int(rc)))
  87.303 +
  87.304 +#Try to resume now -- should fail due to denied access to block device
  87.305 +try:
  87.306 +    status, output = traceCommand("xm resume %s" % domName,
  87.307 +                                  timeout=30)
  87.308 +    if status == 0:
  87.309 +        session.xenapi.VDI.destroy(vdi_ref)
  87.310 +        FAIL("Could resume re-labeled VM: %s" % output)
  87.311 +except Exception, e:
  87.312 +    session.xenapi.VDI.destroy(vdi_ref)
  87.313 +    FAIL("2. Error resuming the VM: %s." % str(e))
  87.314 +
  87.315 +
  87.316 +status, output = traceCommand("xm list")
  87.317 +
  87.318 +# Relabel the resource so VM can resume
  87.319 +try:
  87.320 +    session.xenapi.XSPolicy.set_resource_label(vdi_path,
  87.321 +                                               vdi_label_red,
  87.322 +                                               vdi_label_green)
  87.323 +except Exception, e:
  87.324 +    session.xenapi.VDI.destroy(vdi_ref)
  87.325 +    FAIL("Could not label the resource to '%s'" % vid_label_red)
  87.326 +
  87.327 +res = session.xenapi.XSPolicy.get_resource_label(vdi_path)
  87.328 +if res != vdi_label_red:
  87.329 +    session.xenapi.VDI.destroy(vdi_ref)
  87.330 +    FAIL("'%s' has label '%s', expected '%s'." %
  87.331 +         (vdi_path, res, vdi_label_red))
  87.332 +
  87.333 +#Try to resume now -- should work
  87.334 +try:
  87.335 +    status, output = traceCommand("xm resume %s" % domName,
  87.336 +                                  timeout=30)
  87.337 +    if status != 0:
  87.338 +        session.xenapi.VDI.destroy(vdi_ref)
  87.339 +        FAIL("Could not resume re-labeled VM: %s" % output)
  87.340 +except Exception, e:
  87.341 +    session.xenapi.VDI.destroy(vdi_ref)
  87.342 +    FAIL("3. Error resuming the VM: %s." % str(e))
  87.343 +
  87.344 +
  87.345 +status, output = traceCommand("xm list")
  87.346 +
  87.347 +console = domain.getConsole()
  87.348 +
  87.349 +try:
  87.350 +    run = console.runCmd("cat /proc/interrupts")
  87.351 +except ConsoleError, e:
  87.352 +    saveLog(console.getHistory())
  87.353 +    session.xenapi.VDI.destroy(vdi_ref)
  87.354 +    FAIL("Could not access proc-filesystem")
  87.355 +
  87.356 +domain.stop()
  87.357 +domain.destroy()
    88.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    88.2 +++ b/tools/xm-test/tests/security-acm/09_security-acm_pol_update.py	Fri Jul 27 08:15:16 2007 -0600
    88.3 @@ -0,0 +1,427 @@
    88.4 +#!/usr/bin/python
    88.5 +
    88.6 +# Copyright (C) International Business Machines Corp., 2007
    88.7 +# Author: Stefan Berger <stefanb@us.ibm.com>
    88.8 +
    88.9 +# Test to exercise the xspolicy and acmpolicy classes
   88.10 +
   88.11 +from XmTestLib import xapi
   88.12 +from XmTestLib.XenAPIDomain import XmTestAPIDomain
   88.13 +from XmTestLib import *
   88.14 +from xen.xend import XendAPIConstants
   88.15 +from xen.util import security, xsconstants
   88.16 +from xen.util.acmpolicy import ACMPolicy
   88.17 +from xen.xend.XendDomain import DOM0_UUID
   88.18 +import base64
   88.19 +import struct
   88.20 +import time
   88.21 +
   88.22 +def typestoxml(types):
   88.23 +    res = ""
   88.24 +    for t in types:
   88.25 +        res += "<Type>" + t + "</Type>\n"
   88.26 +    return res
   88.27 +
   88.28 +def cfstoxml(cfss):
   88.29 +    res = ""
   88.30 +    for cfs in cfss:
   88.31 +        res += "<Conflict name=\"" + cfs['name'] + "\">\n" + \
   88.32 +               typestoxml(cfs['chws']) + \
   88.33 +               "</Conflict>\n"
   88.34 +    return res
   88.35 +
   88.36 +def vmlabelstoxml(vmlabels, vmfrommap):
   88.37 +    res = ""
   88.38 +    for vmlabel in vmlabels:
   88.39 +        res += "<VirtualMachineLabel>\n"
   88.40 +        if vmlabel['name'] in vmfrommap:
   88.41 +            res += "<Name from=\""+ vmfrommap[vmlabel['name']] +"\">"
   88.42 +        else:
   88.43 +            res += "<Name>"
   88.44 +        res += vmlabel['name'] + "</Name>\n"
   88.45 +        res += "<SimpleTypeEnforcementTypes>\n" + \
   88.46 +                  typestoxml(vmlabel['stes']) + \
   88.47 +               "</SimpleTypeEnforcementTypes>\n"
   88.48 +        if vmlabel.has_key('chws'):
   88.49 +            res += "<ChineseWallTypes>\n" + \
   88.50 +                     typestoxml(vmlabel['chws']) + \
   88.51 +                   "</ChineseWallTypes>\n"
   88.52 +        res += "</VirtualMachineLabel>\n"
   88.53 +    return res
   88.54 +
   88.55 +
   88.56 +def reslabelstoxml(reslabels, resfrommap):
   88.57 +    res = ""
   88.58 +    for reslabel in reslabels:
   88.59 +        res += "<ResourceLabel>\n"
   88.60 +        if resfrommap.has_key(reslabel['name']):
   88.61 +            res += "<Name from=\""+ resfrommap[reslabel['name']] +"\">"
   88.62 +        else:
   88.63 +            res += "<Name>"
   88.64 +        res += reslabel['name'] + "</Name>\n"
   88.65 +        res += "<SimpleTypeEnforcementTypes>\n" + \
   88.66 +                  typestoxml(reslabel['stes']) + \
   88.67 +               "</SimpleTypeEnforcementTypes>\n"
   88.68 +        res += "</ResourceLabel>\n"
   88.69 +    return res
   88.70 +
   88.71 +def create_xml_policy(hdr, stes, chws,
   88.72 +                      vmlabels, vmfrommap, bootstrap,
   88.73 +                      reslabels, resfrommap,
   88.74 +                      cfss):
   88.75 +    hdr_xml ="<PolicyHeader>\n" + \
   88.76 +             "  <PolicyName>" + hdr['name'] + "</PolicyName>\n" + \
   88.77 +             "  <Version>"    + hdr['version'] + "</Version>\n" + \
   88.78 +             "  <FromPolicy>\n" + \
   88.79 +             "    <PolicyName>" + hdr['oldname'] + "</PolicyName>\n" + \
   88.80 +             "    <Version>"    + hdr['oldversion'] + "</Version>\n" + \
   88.81 +             "  </FromPolicy>\n" + \
   88.82 +               "</PolicyHeader>\n"
   88.83 +
   88.84 +    stes_xml = "<SimpleTypeEnforcement>\n" + \
   88.85 +               "  <SimpleTypeEnforcementTypes>\n" + \
   88.86 +                typestoxml(stes) + \
   88.87 +               "  </SimpleTypeEnforcementTypes>\n" + \
   88.88 +               "</SimpleTypeEnforcement>\n"
   88.89 +
   88.90 +    chws_xml = "<ChineseWall>\n" + \
   88.91 +               "  <ChineseWallTypes>\n" + \
   88.92 +               typestoxml(chws) + \
   88.93 +               "  </ChineseWallTypes>\n" + \
   88.94 +               "  <ConflictSets>\n" + \
   88.95 +               cfstoxml(cfss) + \
   88.96 +               "  </ConflictSets>\n" + \
   88.97 +               "</ChineseWall>\n"
   88.98 +
   88.99 +    subjlabel_xml = "<SubjectLabels bootstrap=\""+ bootstrap +"\">\n" + \
  88.100 +                     vmlabelstoxml(vmlabels, vmfrommap) + \
  88.101 +                    "</SubjectLabels>\n"
  88.102 +    objlabel_xml  = "<ObjectLabels>\n" + \
  88.103 +                      reslabelstoxml(reslabels, resfrommap) + \
  88.104 +                    "</ObjectLabels>\n"
  88.105 +
  88.106 +    policyxml = "<?xml version=\"1.0\" ?>\n" + \
  88.107 +                "<SecurityPolicyDefinition xmlns=\"http://www.ibm.com\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.ibm.com ../../security_policy.xsd \">\n" + \
  88.108 +                hdr_xml + \
  88.109 +                stes_xml + \
  88.110 +                chws_xml + \
  88.111 +                "<SecurityLabelTemplate>\n" + \
  88.112 +                  subjlabel_xml + \
  88.113 +                  objlabel_xml + \
  88.114 +                "</SecurityLabelTemplate>\n" + \
  88.115 +                "</SecurityPolicyDefinition>\n"
  88.116 +    return policyxml
  88.117 +
  88.118 +
  88.119 +def update_hdr(hdr):
  88.120 +    """ Update the version information in the header """
  88.121 +    hdr['oldversion'] = hdr['version']
  88.122 +    hdr['oldname']    = hdr['name']
  88.123 +    vers = hdr['version']
  88.124 +    tmp = vers.split('.')
  88.125 +    if len(tmp) == 1:
  88.126 +        rev = 1
  88.127 +    else:
  88.128 +        rev = int(tmp[1]) + 1
  88.129 +    hdr['version'] = "%s.%s" % (tmp[0],rev)
  88.130 +    return hdr
  88.131 +
  88.132 +session = xapi.connect()
  88.133 +
  88.134 +policystate = session.xenapi.XSPolicy.get_xspolicy()
  88.135 +
  88.136 +if policystate['repr'] != "":
  88.137 +    print "%s" % policystate['repr']
  88.138 +    try:
  88.139 +        acmpol = ACMPolicy(xml=policystate['repr'])
  88.140 +    except Exception, e:
  88.141 +        FAIL("Failure from creating ACMPolicy object: %s" % str(e))
  88.142 +    oldname = acmpol.policy_dom_get_hdr_item("PolicyName")
  88.143 +    oldvers = acmpol.policy_dom_get_hdr_item("Version")
  88.144 +    tmp = oldvers.split(".")
  88.145 +    if len(tmp) == 1:
  88.146 +        rev = 1
  88.147 +    else:
  88.148 +        rev = int(tmp[1]) + 1
  88.149 +    newvers = "%s.%s" % (tmp[0], str(rev))
  88.150 +    print "old name/version = %s/%s" % (oldname, oldvers)
  88.151 +else:
  88.152 +    oldname = None
  88.153 +    oldvers = None
  88.154 +    newvers = "1.0"
  88.155 +
  88.156 +# Initialize the header of the policy
  88.157 +hdr = {}
  88.158 +hdr['name'] = "xm-test"
  88.159 +hdr['version'] = newvers
  88.160 +
  88.161 +if oldname:
  88.162 +    hdr['oldname']    = oldname
  88.163 +    if oldvers and oldvers != "":
  88.164 +        hdr['oldversion'] = oldvers
  88.165 +
  88.166 +stes = [ "SystemManagement", "red", "green", "blue" ]
  88.167 +
  88.168 +chws = [ "SystemManagement", "red", "green", "blue" ]
  88.169 +
  88.170 +bootstrap = "SystemManagement"
  88.171 +
  88.172 +vm_sysmgt = { 'name' : bootstrap,
  88.173 +              'stes' : stes,
  88.174 +              'chws' : [ "SystemManagement" ] }
  88.175 +
  88.176 +vm_red   = { 'name' : "red" ,
  88.177 +             'stes' : ["red"] ,
  88.178 +             'chws' : ["red"] }
  88.179 +
  88.180 +vm_green = { 'name' : "green" ,
  88.181 +             'stes' : ["green"] ,
  88.182 +             'chws' : ["green"] }
  88.183 +
  88.184 +vm_blue  = { 'name' : "blue" ,
  88.185 +             'stes' : ["blue"] ,
  88.186 +             'chws' : ["blue"] }
  88.187 +
  88.188 +res_red   = { 'name' : "red" ,
  88.189 +              'stes' : ["red"] }
  88.190 +
  88.191 +res_green = { 'name' : "green" ,
  88.192 +              'stes' : ["green"] }
  88.193 +
  88.194 +res_blue  = { 'name' : "blue" ,
  88.195 +              'stes' : ["blue"] }
  88.196 +
  88.197 +cfs_1 = { 'name' : "CFS1",
  88.198 +          'chws' : [ "red" , "blue" ] }
  88.199 +
  88.200 +vmlabels = [ vm_sysmgt, vm_red, vm_green, vm_blue ]
  88.201 +vmfrommap = {}
  88.202 +reslabels = [ res_red, res_green, res_blue ]
  88.203 +resfrommap = {}
  88.204 +cfss = [ cfs_1 ]
  88.205 +
  88.206 +vm_label_red    = xsconstants.ACM_POLICY_ID + ":xm-test:red"
  88.207 +vm_label_green  = xsconstants.ACM_POLICY_ID + ":xm-test:green"
  88.208 +vm_label_blue   = xsconstants.ACM_POLICY_ID + ":xm-test:blue"
  88.209 +
  88.210 +xml = create_xml_policy(hdr, stes, chws,
  88.211 +                        vmlabels, vmfrommap, bootstrap,
  88.212 +                        reslabels, resfrommap,
  88.213 +                        cfss)
  88.214 +
  88.215 +xml_good = xml
  88.216 +
  88.217 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  88.218 +                                                   xml,
  88.219 +                                                   xsconstants.XS_INST_LOAD,
  88.220 +                                                   True)
  88.221 +
  88.222 +print "\n\npolicystate = %s" % policystate
  88.223 +
  88.224 +policystate = session.xenapi.XSPolicy.get_xspolicy()
  88.225 +
  88.226 +#
  88.227 +# Create two non-conflicting domains and start them
  88.228 +#
  88.229 +try:
  88.230 +    # XmTestAPIDomain tries to establish a connection to XenD
  88.231 +    domain1 = XmTestAPIDomain(extraConfig={ 'security_label' : vm_label_red })
  88.232 +except Exception, e:
  88.233 +    SKIP("Skipping test. Error: %s" % str(e))
  88.234 +
  88.235 +
  88.236 +vm1_uuid = domain1.get_uuid()
  88.237 +
  88.238 +try:
  88.239 +    domain1.start(noConsole=True)
  88.240 +except:
  88.241 +    FAIL("Could not start domain1")
  88.242 +
  88.243 +print "Domain 1 started"
  88.244 +
  88.245 +try:
  88.246 +    # XmTestAPIDomain tries to establish a connection to XenD
  88.247 +    domain2 = XmTestAPIDomain(extraConfig={'security_label': vm_label_green })
  88.248 +except Exception, e:
  88.249 +    SKIP("Skipping test. Error: %s" % str(e))
  88.250 +
  88.251 +vm2_uuid = domain2.get_uuid()
  88.252 +
  88.253 +try:
  88.254 +    domain2.start(noConsole=True)
  88.255 +except:
  88.256 +    FAIL("Could not start domain1")
  88.257 +
  88.258 +
  88.259 +print "Domain 2 started"
  88.260 +
  88.261 +# Try a policy that would put the two domains into conflict
  88.262 +cfs_2 = { 'name' : "CFS1",
  88.263 +          'chws' : [ "red" , "green" ] }
  88.264 +cfss = [ cfs_2 ]
  88.265 +
  88.266 +hdr = update_hdr(hdr)
  88.267 +xml = create_xml_policy(hdr, stes, chws,
  88.268 +                        vmlabels, vmfrommap, bootstrap,
  88.269 +                        reslabels, resfrommap,
  88.270 +                        cfss)
  88.271 +
  88.272 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  88.273 +                                                   xml,
  88.274 +                                                   xsconstants.XS_INST_LOAD,
  88.275 +                                                   True)
  88.276 +
  88.277 +print "policystate %s" % policystate
  88.278 +
  88.279 +if int(policystate['xserr']) == 0:
  88.280 +    FAIL("(1) Should not have been able to set this policy.")
  88.281 +
  88.282 +if len(policystate['errors']) == 0:
  88.283 +    FAIL("Hypervisor should have reported errros.")
  88.284 +
  88.285 +errors = base64.b64decode(policystate['errors'])
  88.286 +
  88.287 +print "Length of errors: %d" % len(errors)
  88.288 +a,b = struct.unpack("!ii",errors)
  88.289 +
  88.290 +print "%08x , %08x" % (a,b)
  88.291 +
  88.292 +#
  88.293 +# Create a faulty policy with 'red' STE missing
  88.294 +#
  88.295 +
  88.296 +cfss = [ cfs_1 ]
  88.297 +stes = [ "SystemManagement", "green", "blue" ]
  88.298 +
  88.299 +xml = create_xml_policy(hdr, stes, chws,
  88.300 +                        vmlabels, vmfrommap, bootstrap,
  88.301 +                        reslabels, resfrommap,
  88.302 +                        cfss)
  88.303 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  88.304 +                                                   xml,
  88.305 +                                                   xsconstants.XS_INST_LOAD,
  88.306 +                                                   True)
  88.307 +
  88.308 +print "Result from setting faulty(!) policy with STE 'red' missing:"
  88.309 +print "policystate %s" % policystate
  88.310 +
  88.311 +if int(policystate['xserr']) == 0:
  88.312 +    FAIL("(2) Should not have been able to set this policy.")
  88.313 +
  88.314 +#
  88.315 +# Create a policy with 'red' VMLabel missing -- should not work since it is
  88.316 +# in use.
  88.317 +#
  88.318 +stes = [ "SystemManagement", "red", "green", "blue" ]
  88.319 +
  88.320 +vmlabels = [ vm_sysmgt, vm_green, vm_blue ]
  88.321 +
  88.322 +xml = create_xml_policy(hdr, stes, chws,
  88.323 +                        vmlabels, vmfrommap, bootstrap,
  88.324 +                        reslabels, resfrommap,
  88.325 +                        cfss)
  88.326 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  88.327 +                                                   xml,
  88.328 +                                                   xsconstants.XS_INST_LOAD,
  88.329 +                                                   True)
  88.330 +print "Result from setting faulty(!) policy with VMlabel 'red' missing:"
  88.331 +print "policystate %s" % policystate
  88.332 +
  88.333 +if int(policystate['xserr']) == 0:
  88.334 +    FAIL("(3) Should not have been able to set this policy.")
  88.335 +
  88.336 +#
  88.337 +# Create a policy with 'blue' VMLabel missing -- should work since it is NOT
  88.338 +# in use.
  88.339 +#
  88.340 +vmlabels = [ vm_sysmgt, vm_red, vm_green ]
  88.341 +
  88.342 +xml = create_xml_policy(hdr, stes, chws,
  88.343 +                        vmlabels, vmfrommap, bootstrap,
  88.344 +                        reslabels, resfrommap,
  88.345 +                        cfss)
  88.346 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  88.347 +                                                   xml,
  88.348 +                                                   xsconstants.XS_INST_LOAD,
  88.349 +                                                   True)
  88.350 +
  88.351 +print "Result from setting (good) policy with VMlabel 'blue' missing:"
  88.352 +print "policystate %s" % policystate
  88.353 +
  88.354 +if int(policystate['xserr']) != 0:
  88.355 +    FAIL("(4) Should have been able to set this policy: %s" % xml)
  88.356 +
  88.357 +#
  88.358 +# Move the green VMLabel towards blue which should put the running
  88.359 +# domain with label blue into a conflict set
  88.360 +#
  88.361 +vmlabels = [ vm_sysmgt, vm_red, vm_blue ]
  88.362 +
  88.363 +vmfrommap = { "blue" : "green" }  #  new : old
  88.364 +
  88.365 +hdr = update_hdr(hdr)  #Needed, since last update was successful
  88.366 +xml = create_xml_policy(hdr, stes, chws,
  88.367 +                        vmlabels, vmfrommap, bootstrap,
  88.368 +                        reslabels, resfrommap,
  88.369 +                        cfss)
  88.370 +
  88.371 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  88.372 +                                                   xml,
  88.373 +                                                   xsconstants.XS_INST_LOAD,
  88.374 +                                                   True)
  88.375 +
  88.376 +print "policystate %s" % policystate
  88.377 +
  88.378 +if int(policystate['xserr']) == 0:
  88.379 +    FAIL("(5) Should not have been able to set this policy.")
  88.380 +
  88.381 +#
  88.382 +# Try to install a policy where a VM label has a faulty VM label name
  88.383 +#
  88.384 +vmfrommap = {}
  88.385 +
  88.386 +vm_blue_bad = { 'name' : "blue:x" ,   # ':' no allowed
  88.387 +                'stes' : ["blue"],
  88.388 +                'chws' : ["blue"] }
  88.389 +
  88.390 +vmlabels = [ vm_sysmgt, vm_red, vm_green, vm_blue_bad ]
  88.391 +
  88.392 +xml = create_xml_policy(hdr, stes, chws,
  88.393 +                        vmlabels, vmfrommap, bootstrap,
  88.394 +                        reslabels, resfrommap,
  88.395 +                        cfss)
  88.396 +
  88.397 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  88.398 +                                                   xml,
  88.399 +                                                   xsconstants.XS_INST_LOAD,
  88.400 +                                                   True)
  88.401 +
  88.402 +print "policystate %s" % policystate
  88.403 +
  88.404 +if int(policystate['xserr']) == 0:
  88.405 +    FAIL("(6) Should not have been able to set this policy.")
  88.406 +
  88.407 +#
  88.408 +# End the test by installing the initial policy again
  88.409 +#
  88.410 +
  88.411 +cur_version = hdr['version']
  88.412 +(maj, min) = cur_version.split(".")
  88.413 +cur_version = "%s.%s" % (maj, str(int(min)-1) )
  88.414 +
  88.415 +orig_acmpol = ACMPolicy(xml=xml_good)
  88.416 +orig_acmpol.set_frompolicy_version(cur_version)
  88.417 +orig_acmpol.set_policy_version(hdr['version'])
  88.418 +
  88.419 +policystate = session.xenapi.XSPolicy.set_xspolicy(xsconstants.XS_POLICY_ACM,
  88.420 +                                                   orig_acmpol.toxml(),
  88.421 +                                                   xsconstants.XS_INST_LOAD,
  88.422 +                                                   True)
  88.423 +
  88.424 +if int(policystate['xserr']) != 0:
  88.425 +    FAIL("(END) Should have been able to set this policy.")
  88.426 +
  88.427 +domain1.stop()
  88.428 +domain2.stop()
  88.429 +domain1.destroy()
  88.430 +domain2.destroy()
    89.1 --- a/tools/xm-test/tests/security-acm/Makefile.am	Thu Jul 26 14:35:01 2007 -0600
    89.2 +++ b/tools/xm-test/tests/security-acm/Makefile.am	Fri Jul 27 08:15:16 2007 -0600
    89.3 @@ -5,7 +5,10 @@ TESTS = 01_security-acm_basic.test \
    89.4          03_security-acm_dom_conflict.test \
    89.5          04_security-acm_dom_res.test \
    89.6          05_security-acm_dom_res_conf.test \
    89.7 -        06_security-acm_dom_block_attach.test
    89.8 +        06_security-acm_dom_block_attach.test \
    89.9 +        07_security-acm_pol_update.test \
   89.10 +        08_security-acm_xapi.test \
   89.11 +        09_security-acm_pol_update.test
   89.12  
   89.13  XFAIL_TESTS =
   89.14  
    90.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    90.2 +++ b/tools/xm-test/tests/security-acm/xm-test-new-security_policy.xml	Fri Jul 27 08:15:16 2007 -0600
    90.3 @@ -0,0 +1,97 @@
    90.4 +<?xml version="1.0" encoding="UTF-8"?>
    90.5 +<!-- Auto-generated by ezPolicy        -->
    90.6 +<SecurityPolicyDefinition xmlns="http://www.ibm.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ibm.com ../../security_policy.xsd ">
    90.7 +    <PolicyHeader>
    90.8 +        <PolicyName>xm-test</PolicyName>
    90.9 +        <Date>Fri Sep 29 14:44:38 2006</Date>
   90.10 +        <Version>1.1</Version>
   90.11 +        <FromPolicy>
   90.12 +            <PolicyName>xm-test</PolicyName>
   90.13 +            <Version>1.0</Version>
   90.14 +        </FromPolicy>
   90.15 +    </PolicyHeader>
   90.16 +
   90.17 +    <SimpleTypeEnforcement>
   90.18 +        <SimpleTypeEnforcementTypes>
   90.19 +            <Type>SystemManagement</Type>
   90.20 +            <Type>green</Type>
   90.21 +            <Type>red</Type>
   90.22 +        </SimpleTypeEnforcementTypes>
   90.23 +    </SimpleTypeEnforcement>
   90.24 +
   90.25 +    <ChineseWall priority="PrimaryPolicyComponent">
   90.26 +        <ChineseWallTypes>
   90.27 +            <Type>SystemManagement</Type>
   90.28 +            <Type>green</Type>
   90.29 +            <Type>red</Type>
   90.30 +        </ChineseWallTypes>
   90.31 +
   90.32 +        <ConflictSets>
   90.33 +            <Conflict name="RER">
   90.34 +                <Type>green</Type>
   90.35 +                <Type>red</Type>
   90.36 +            </Conflict>
   90.37 +       </ConflictSets>
   90.38 +    </ChineseWall>
   90.39 +
   90.40 +    <SecurityLabelTemplate>
   90.41 +        <SubjectLabels bootstrap="SystemManagement">
   90.42 +            <VirtualMachineLabel>
   90.43 +                <Name>SystemManagement</Name>
   90.44 +                <SimpleTypeEnforcementTypes>
   90.45 +                    <Type>SystemManagement</Type>
   90.46 +                    <Type>green</Type>
   90.47 +                    <Type>red</Type>
   90.48 +                </SimpleTypeEnforcementTypes>
   90.49 +                <ChineseWallTypes>
   90.50 +                    <Type>SystemManagement</Type>
   90.51 +                </ChineseWallTypes>
   90.52 +            </VirtualMachineLabel>
   90.53 +
   90.54 +            <VirtualMachineLabel>
   90.55 +                <Name>green</Name>
   90.56 +                <SimpleTypeEnforcementTypes>
   90.57 +                    <Type>green</Type>
   90.58 +                </SimpleTypeEnforcementTypes>
   90.59 +                <ChineseWallTypes>
   90.60 +                    <Type>green</Type>
   90.61 +                </ChineseWallTypes>
   90.62 +            </VirtualMachineLabel>
   90.63 +
   90.64 +            <VirtualMachineLabel>
   90.65 +                <Name>red</Name>
   90.66 +                <SimpleTypeEnforcementTypes>
   90.67 +                    <Type>red</Type>
   90.68 +                </SimpleTypeEnforcementTypes>
   90.69 +                <ChineseWallTypes>
   90.70 +                    <Type>red</Type>
   90.71 +                </ChineseWallTypes>
   90.72 +            </VirtualMachineLabel>
   90.73 +
   90.74 +        </SubjectLabels>
   90.75 +
   90.76 +        <ObjectLabels>
   90.77 +            <ResourceLabel>
   90.78 +                <Name>SystemManagement</Name>
   90.79 +                <SimpleTypeEnforcementTypes>
   90.80 +                    <Type>SystemManagement</Type>
   90.81 +                </SimpleTypeEnforcementTypes>
   90.82 +            </ResourceLabel>
   90.83 +
   90.84 +            <ResourceLabel>
   90.85 +                <Name>green</Name>
   90.86 +                <SimpleTypeEnforcementTypes>
   90.87 +                    <Type>green</Type>
   90.88 +                </SimpleTypeEnforcementTypes>
   90.89 +            </ResourceLabel>
   90.90 +
   90.91 +            <ResourceLabel>
   90.92 +                <Name>red</Name>
   90.93 +                <SimpleTypeEnforcementTypes>
   90.94 +                    <Type>red</Type>
   90.95 +                </SimpleTypeEnforcementTypes>
   90.96 +            </ResourceLabel>
   90.97 +
   90.98 +        </ObjectLabels>
   90.99 +    </SecurityLabelTemplate>
  90.100 +</SecurityPolicyDefinition>
    91.1 --- a/tools/xm-test/tests/vtpm/01_vtpm-list_pos.py	Thu Jul 26 14:35:01 2007 -0600
    91.2 +++ b/tools/xm-test/tests/vtpm/01_vtpm-list_pos.py	Fri Jul 27 08:15:16 2007 -0600
    91.3 @@ -11,6 +11,7 @@ from XmTestLib import *
    91.4  from vtpm_utils import *
    91.5  import commands
    91.6  import os
    91.7 +import atexit
    91.8  
    91.9  config = {"vtpm":"instance=1,backend=0"}
   91.10  domain = XmTestDomain(extraConfig=config)
   91.11 @@ -23,18 +24,17 @@ except DomainError, e:
   91.12      vtpm_cleanup(domain.getName())
   91.13      FAIL("Unable to create domain")
   91.14  
   91.15 +
   91.16  domName = domain.getName()
   91.17  
   91.18 +atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
   91.19 +
   91.20  status, output = traceCommand("xm vtpm-list %s" % domain.getId())
   91.21  eyecatcher = "/local/domain/0/backend/vtpm"
   91.22  where = output.find(eyecatcher)
   91.23  if status != 0:
   91.24 -    vtpm_cleanup(domName)
   91.25      FAIL("xm vtpm-list returned bad status, expected 0, status is %i" % status)
   91.26  elif where < 0:
   91.27 -    vtpm_cleanup(domName)
   91.28      FAIL("Fail to list virtual TPM device")
   91.29  
   91.30  domain.stop()
   91.31 -
   91.32 -vtpm_cleanup(domName)
    92.1 --- a/tools/xm-test/tests/vtpm/02_vtpm-cat_pcrs.py	Thu Jul 26 14:35:01 2007 -0600
    92.2 +++ b/tools/xm-test/tests/vtpm/02_vtpm-cat_pcrs.py	Fri Jul 27 08:15:16 2007 -0600
    92.3 @@ -11,6 +11,7 @@ from vtpm_utils import *
    92.4  import commands
    92.5  import os
    92.6  import os.path
    92.7 +import atexit
    92.8  
    92.9  config = {"vtpm":"instance=1,backend=0"}
   92.10  domain = XmTestDomain(extraConfig=config)
   92.11 @@ -21,32 +22,28 @@ try:
   92.12  except DomainError, e:
   92.13      if verbose:
   92.14          print e.extra
   92.15 -    vtpm_cleanup(domName)
   92.16      FAIL("Unable to create domain (%s)" % domName)
   92.17  
   92.18 +atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
   92.19 +
   92.20  try:
   92.21      console.sendInput("input")
   92.22  except ConsoleError, e:
   92.23      saveLog(console.getHistory())
   92.24 -    vtpm_cleanup(domName)
   92.25      FAIL(str(e))
   92.26  
   92.27  try:
   92.28      run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   92.29  except ConsoleError, e:
   92.30      saveLog(console.getHistory())
   92.31 -    vtpm_cleanup(domName)
   92.32      FAIL("No result from dumping the PCRs")
   92.33  
   92.34  if re.search("No such file",run["output"]):
   92.35 -    vtpm_cleanup(domName)
   92.36      FAIL("TPM frontend support not compiled into (domU?) kernel")
   92.37  
   92.38  domain.closeConsole()
   92.39  
   92.40  domain.stop()
   92.41  
   92.42 -vtpm_cleanup(domName)
   92.43 -
   92.44  if not re.search("PCR-00:",run["output"]):
   92.45      FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side")
    93.1 --- a/tools/xm-test/tests/vtpm/03_vtpm-susp_res.py	Thu Jul 26 14:35:01 2007 -0600
    93.2 +++ b/tools/xm-test/tests/vtpm/03_vtpm-susp_res.py	Fri Jul 27 08:15:16 2007 -0600
    93.3 @@ -12,6 +12,7 @@ from vtpm_utils import *
    93.4  import commands
    93.5  import os
    93.6  import os.path
    93.7 +import atexit
    93.8  
    93.9  config = {"vtpm":"instance=1,backend=0"}
   93.10  domain = XmTestDomain(extraConfig=config)
   93.11 @@ -23,25 +24,23 @@ try:
   93.12  except DomainError, e:
   93.13      if verbose:
   93.14          print e.extra
   93.15 -    vtpm_cleanup(domName)
   93.16      FAIL("Unable to create domain (%s)" % domName)
   93.17  
   93.18 +atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
   93.19 +
   93.20  try:
   93.21      console.sendInput("input")
   93.22  except ConsoleError, e:
   93.23      saveLog(console.getHistory())
   93.24 -    vtpm_cleanup(domName)
   93.25      FAIL(str(e))
   93.26  
   93.27  try:
   93.28      run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   93.29  except ConsoleError, e:
   93.30      saveLog(console.getHistory())
   93.31 -    vtpm_cleanup(domName)
   93.32      FAIL("No result from dumping the PCRs")
   93.33  
   93.34  if re.search("No such file",run["output"]):
   93.35 -    vtpm_cleanup(domName)
   93.36      FAIL("TPM frontend support not compiled into (domU?) kernel")
   93.37  
   93.38  consoleHistory = console.getHistory()
   93.39 @@ -56,12 +55,10 @@ while loop < 3:
   93.40  
   93.41      except TimeoutError, e:
   93.42          saveLog(consoleHistory)
   93.43 -        vtpm_cleanup(domName)
   93.44          FAIL(str(e))
   93.45  
   93.46      if status != 0:
   93.47          saveLog(consoleHistory)
   93.48 -        vtpm_cleanup(domName)
   93.49          FAIL("xm save did not succeed")
   93.50  
   93.51      try:
   93.52 @@ -71,32 +68,27 @@ while loop < 3:
   93.53      except TimeoutError, e:
   93.54          os.remove("%s.save" % domName)
   93.55          saveLog(consoleHistory)
   93.56 -        vtpm_cleanup(domName)
   93.57          FAIL(str(e))
   93.58  
   93.59      os.remove("%s.save" % domName)
   93.60  
   93.61      if status != 0:
   93.62          saveLog(consoleHistory)
   93.63 -        vtpm_cleanup(domName)
   93.64          FAIL("xm restore did not succeed")
   93.65  
   93.66      try:
   93.67          console = domain.getConsole()
   93.68      except ConsoleError, e:
   93.69 -        vtpm_cleanup(domName)
   93.70          FAIL(str(e))
   93.71  
   93.72      try:
   93.73          run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   93.74      except ConsoleError, e:
   93.75          saveLog(console.getHistory())
   93.76 -        vtpm_cleanup(domName)
   93.77          FAIL(str(e))
   93.78  
   93.79      if not re.search("PCR-00:",run["output"]):
   93.80          saveLog(console.getHistory())
   93.81 -        vtpm_cleanup(domName)
   93.82          FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side")
   93.83  
   93.84      loop += 1
   93.85 @@ -105,5 +97,3 @@ domain.closeConsole()
   93.86  
   93.87  domain.stop()
   93.88  
   93.89 -vtpm_cleanup(domName)
   93.90 -
    94.1 --- a/tools/xm-test/tests/vtpm/04_vtpm-loc_migr.py	Thu Jul 26 14:35:01 2007 -0600
    94.2 +++ b/tools/xm-test/tests/vtpm/04_vtpm-loc_migr.py	Fri Jul 27 08:15:16 2007 -0600
    94.3 @@ -13,6 +13,7 @@ from vtpm_utils import *
    94.4  import commands
    94.5  import os
    94.6  import os.path
    94.7 +import atexit
    94.8  
    94.9  config = {"vtpm":"instance=1,backend=0"}
   94.10  domain = XmTestDomain(extraConfig=config)
   94.11 @@ -24,25 +25,23 @@ try:
   94.12  except DomainError, e:
   94.13      if verbose:
   94.14          print e.extra
   94.15 -    vtpm_cleanup(domName)
   94.16      FAIL("Unable to create domain (%s)" % domName)
   94.17  
   94.18 +atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
   94.19 +
   94.20  try:
   94.21      console.sendInput("input")
   94.22  except ConsoleError, e:
   94.23      saveLog(console.getHistory())
   94.24 -    vtpm_cleanup(domName)
   94.25      FAIL(str(e))
   94.26  
   94.27  try:
   94.28      run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   94.29  except ConsoleError, e:
   94.30      saveLog(console.getHistory())
   94.31 -    vtpm_cleanup(domName)
   94.32      FAIL("No result from dumping the PCRs")
   94.33  
   94.34  if re.search("No such file",run["output"]):
   94.35 -    vtpm_cleanup(domName)
   94.36      FAIL("TPM frontend support not compiled into (domU?) kernel")
   94.37  
   94.38  consoleHistory = console.getHistory()
   94.39 @@ -58,12 +57,10 @@ while loop < 3:
   94.40                                        timeout=90)
   94.41      except TimeoutError, e:
   94.42          saveLog(consoleHistory)
   94.43 -        vtpm_cleanup(domName)
   94.44          FAIL(str(e))
   94.45  
   94.46      if status != 0:
   94.47          saveLog(consoleHistory)
   94.48 -        vtpm_cleanup(domName)
   94.49          FAIL("xm migrate did not succeed. External device migration activated?")
   94.50  
   94.51  
   94.52 @@ -71,26 +68,22 @@ while loop < 3:
   94.53      new_domid = domid(domName)
   94.54  
   94.55      if (old_domid == new_domid):
   94.56 -        vtpm_cleanup(domName)
   94.57          FAIL("xm migrate failed, domain id is still %s (loop=%d)" %
   94.58               (old_domid,loop))
   94.59  
   94.60      try:
   94.61          console = domain.getConsole()
   94.62      except ConsoleError, e:
   94.63 -        vtpm_cleanup(domName)
   94.64          FAIL(str(e))
   94.65  
   94.66      try:
   94.67          run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   94.68      except ConsoleError, e:
   94.69          saveLog(console.getHistory())
   94.70 -        vtpm_cleanup(domName)
   94.71          FAIL("No result from dumping the PCRs")
   94.72  
   94.73      if not re.search("PCR-00:",run["output"]):
   94.74          saveLog(console.getHistory())
   94.75 -        vtpm_cleanup(domName)
   94.76          FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side")
   94.77  
   94.78      loop += 1
   94.79 @@ -98,5 +91,3 @@ while loop < 3:
   94.80  domain.closeConsole()
   94.81  
   94.82  domain.stop()
   94.83 -
   94.84 -vtpm_cleanup(domName)
    95.1 --- a/tools/xm-test/tests/vtpm/05_vtpm-loc_migr.py	Thu Jul 26 14:35:01 2007 -0600
    95.2 +++ b/tools/xm-test/tests/vtpm/05_vtpm-loc_migr.py	Fri Jul 27 08:15:16 2007 -0600
    95.3 @@ -13,6 +13,7 @@ from vtpm_utils import *
    95.4  import commands
    95.5  import os
    95.6  import os.path
    95.7 +import atexit
    95.8  
    95.9  config = {"vtpm":"instance=1,backend=0"}
   95.10  domain = XmTestDomain(extraConfig=config)
   95.11 @@ -24,25 +25,23 @@ try:
   95.12  except DomainError, e:
   95.13      if verbose:
   95.14          print e.extra
   95.15 -    vtpm_cleanup(domName)
   95.16      FAIL("Unable to create domain (%s)" % domName)
   95.17  
   95.18 +atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
   95.19 +
   95.20  try:
   95.21      console.sendInput("input")
   95.22  except ConsoleError, e:
   95.23      saveLog(console.getHistory())
   95.24 -    vtpm_cleanup(domName)
   95.25      FAIL(str(e))
   95.26  
   95.27  try:
   95.28      run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   95.29  except ConsoleError, e:
   95.30      saveLog(console.getHistory())
   95.31 -    vtpm_cleanup(domName)
   95.32      FAIL("No result from dumping the PCRs")
   95.33  
   95.34  if re.search("No such file",run["output"]):
   95.35 -    vtpm_cleanup(domName)
   95.36      FAIL("TPM frontend support not compiled into (domU?) kernel")
   95.37  
   95.38  consoleHistory = console.getHistory()
   95.39 @@ -58,12 +57,10 @@ while loop < 3:
   95.40                                        timeout=90)
   95.41      except TimeoutError, e:
   95.42          saveLog(consoleHistory)
   95.43 -        vtpm_cleanup(domName)
   95.44          FAIL(str(e))
   95.45  
   95.46      if status != 0:
   95.47          saveLog(consoleHistory)
   95.48 -        vtpm_cleanup(domName)
   95.49          FAIL("xm migrate did not succeed. External device migration activated?")
   95.50  
   95.51  
   95.52 @@ -71,26 +68,22 @@ while loop < 3:
   95.53      new_domid = domid(domName)
   95.54  
   95.55      if (old_domid == new_domid):
   95.56 -        vtpm_cleanup(domName)
   95.57          FAIL("xm migrate failed, domain id is still %s (loop=%d)" %
   95.58               (old_domid,loop))
   95.59  
   95.60      try:
   95.61          console = domain.getConsole()
   95.62      except ConsoleError, e:
   95.63 -        vtpm_cleanup(domName)
   95.64          FAIL(str(e))
   95.65  
   95.66      try:
   95.67          run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   95.68      except ConsoleError, e:
   95.69          saveLog(console.getHistory())
   95.70 -        vtpm_cleanup(domName)
   95.71          FAIL("No result from dumping the PCRs")
   95.72  
   95.73      if not re.search("PCR-00:",run["output"]):
   95.74          saveLog(console.getHistory())
   95.75 -        vtpm_cleanup(domName)
   95.76          FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side")
   95.77  
   95.78      loop += 1
   95.79 @@ -98,5 +91,3 @@ while loop < 3:
   95.80  domain.closeConsole()
   95.81  
   95.82  domain.stop()
   95.83 -
   95.84 -vtpm_cleanup(domName)
    96.1 --- a/tools/xm-test/tests/vtpm/06_vtpm-susp_res_pcrs.py	Thu Jul 26 14:35:01 2007 -0600
    96.2 +++ b/tools/xm-test/tests/vtpm/06_vtpm-susp_res_pcrs.py	Fri Jul 27 08:15:16 2007 -0600
    96.3 @@ -13,6 +13,7 @@ from vtpm_utils import *
    96.4  import commands
    96.5  import os
    96.6  import os.path
    96.7 +import atexit
    96.8  
    96.9  config = {"vtpm":"instance=1,backend=0"}
   96.10  domain = XmTestDomain(extraConfig=config)
   96.11 @@ -24,45 +25,40 @@ try:
   96.12  except DomainError, e:
   96.13      if verbose:
   96.14          print e.extra
   96.15 -    vtpm_cleanup(domName)
   96.16      FAIL("Unable to create domain (%s)" % domName)
   96.17  
   96.18 +atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
   96.19 +
   96.20  try:
   96.21      console.sendInput("input")
   96.22  except ConsoleError, e:
   96.23      saveLog(console.getHistory())
   96.24 -    vtpm_cleanup(domName)
   96.25      FAIL(str(e))
   96.26  
   96.27  try:
   96.28      run = console.runCmd("mknod /dev/tpm0 c 10 224")
   96.29  except ConsoleError, e:
   96.30      saveLog(console.getHistory())
   96.31 -    vtpm_cleanup(domName)
   96.32      FAIL("Error while creating /dev/tpm0")
   96.33  
   96.34  try:
   96.35      run = console.runCmd("echo -ne \"\\x00\\xc1\\x00\\x00\\x00\\x22\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\0xf\\x10\\x11\\x12\\x13\\x14\" > seq; cat seq > /dev/tpm0")
   96.36  except ConsoleError, e:
   96.37      saveLog(console.getHistory())
   96.38 -    vtpm_cleanup(domName)
   96.39      FAIL("Error while extending PCR 0")
   96.40  
   96.41  try:
   96.42      run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   96.43  except ConsoleError, e:
   96.44      saveLog(console.getHistory())
   96.45 -    vtpm_cleanup(domName)
   96.46      FAIL("No result from dumping the PCRs")
   96.47  
   96.48  
   96.49  if re.search("No such file",run["output"]):
   96.50 -    vtpm_cleanup(domName)
   96.51      FAIL("TPM frontend support not compiled into (domU?) kernel")
   96.52  
   96.53  if not re.search("PCR-00:",run["output"]):
   96.54      saveLog(console.getHistory())
   96.55 -    vtpm_cleanup(domName)
   96.56      FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side: \n%s" % run["output"])
   96.57  
   96.58  if not re.search("PCR-00: 1E A7 BD",run["output"]):
   96.59 @@ -81,12 +77,10 @@ while loop < 3:
   96.60  
   96.61      except TimeoutError, e:
   96.62          saveLog(consoleHistory)
   96.63 -        vtpm_cleanup(domName)
   96.64          FAIL(str(e))
   96.65  
   96.66      if status != 0:
   96.67          saveLog(consoleHistory)
   96.68 -        vtpm_cleanup(domName)
   96.69          FAIL("xm save did not succeed")
   96.70  
   96.71      try:
   96.72 @@ -96,37 +90,31 @@ while loop < 3:
   96.73      except TimeoutError, e:
   96.74          os.remove("%s.save" % domName)
   96.75          saveLog(consoleHistory)
   96.76 -        vtpm_cleanup(domName)
   96.77          FAIL(str(e))
   96.78  
   96.79      os.remove("%s.save" % domName)
   96.80  
   96.81      if status != 0:
   96.82          saveLog(consoleHistory)
   96.83 -        vtpm_cleanup(domName)
   96.84          FAIL("xm restore did not succeed")
   96.85  
   96.86      try:
   96.87          console = domain.getConsole()
   96.88      except ConsoleError, e:
   96.89 -        vtpm_cleanup(domName)
   96.90          FAIL(str(e))
   96.91  
   96.92      try:
   96.93          run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   96.94      except ConsoleError, e:
   96.95          saveLog(console.getHistory())
   96.96 -        vtpm_cleanup(domName)
   96.97          FAIL(str(e))
   96.98  
   96.99      if not re.search("PCR-00:",run["output"]):
  96.100          saveLog(console.getHistory())
  96.101 -        vtpm_cleanup(domName)
  96.102          FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side")
  96.103  
  96.104      if not re.search("PCR-00: 1E A7 BD",run["output"]):
  96.105          saveLog(console.getHistory())
  96.106 -        vtpm_cleanup(domName)
  96.107          FAIL("Virtual TPM lost PCR 0 value: \n%s" % run["output"])
  96.108  
  96.109      loop += 1
  96.110 @@ -135,5 +123,3 @@ domain.closeConsole()
  96.111  
  96.112  domain.stop()
  96.113  
  96.114 -vtpm_cleanup(domName)
  96.115 -
    97.1 --- a/tools/xm-test/tests/vtpm/07_vtpm-mig_pcrs.py	Thu Jul 26 14:35:01 2007 -0600
    97.2 +++ b/tools/xm-test/tests/vtpm/07_vtpm-mig_pcrs.py	Fri Jul 27 08:15:16 2007 -0600
    97.3 @@ -14,6 +14,7 @@ from vtpm_utils import *
    97.4  import commands
    97.5  import os
    97.6  import os.path
    97.7 +import atexit
    97.8  
    97.9  config = {"vtpm":"instance=1,backend=0"}
   97.10  domain = XmTestDomain(extraConfig=config)
   97.11 @@ -25,45 +26,40 @@ try:
   97.12  except DomainError, e:
   97.13      if verbose:
   97.14          print e.extra
   97.15 -    vtpm_cleanup(domName)
   97.16      FAIL("Unable to create domain (%s)" % domName)
   97.17  
   97.18 +atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
   97.19 +
   97.20  try:
   97.21      console.sendInput("input")
   97.22  except ConsoleError, e:
   97.23      saveLog(console.getHistory())
   97.24 -    vtpm_cleanup(domName)
   97.25      FAIL(str(e))
   97.26  
   97.27  try:
   97.28      run = console.runCmd("mknod /dev/tpm0 c 10 224")
   97.29  except ConsoleError, e:
   97.30      saveLog(console.getHistory())
   97.31 -    vtpm_cleanup(domName)
   97.32      FAIL("Error while creating /dev/tpm0")
   97.33  
   97.34  try:
   97.35      run = console.runCmd("echo -ne \"\\x00\\xc1\\x00\\x00\\x00\\x22\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\0xf\\x10\\x11\\x12\\x13\\x14\" > seq; cat seq > /dev/tpm0")
   97.36  except ConsoleError, e:
   97.37      saveLog(console.getHistory())
   97.38 -    vtpm_cleanup(domName)
   97.39      FAIL("Error while extending PCR 0")
   97.40  
   97.41  try:
   97.42      run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   97.43  except ConsoleError, e:
   97.44      saveLog(console.getHistory())
   97.45 -    vtpm_cleanup(domName)
   97.46      FAIL("No result from dumping the PCRs")
   97.47  
   97.48  
   97.49  if re.search("No such file",run["output"]):
   97.50 -    vtpm_cleanup(domName)
   97.51      FAIL("TPM frontend support not compiled into (domU?) kernel")
   97.52  
   97.53  if not re.search("PCR-00:",run["output"]):
   97.54      saveLog(console.getHistory())
   97.55 -    vtpm_cleanup(domName)
   97.56      FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side: \n%s" % run["output"])
   97.57  
   97.58  if not re.search("PCR-00: 1E A7 BD",run["output"]):
   97.59 @@ -83,12 +79,10 @@ while loop < 3:
   97.60                                        timeout=90)
   97.61      except TimeoutError, e:
   97.62          saveLog(consoleHistory)
   97.63 -        vtpm_cleanup(domName)
   97.64          FAIL(str(e))
   97.65  
   97.66      if status != 0:
   97.67          saveLog(consoleHistory)
   97.68 -        vtpm_cleanup(domName)
   97.69          FAIL("xm migrate did not succeed. External device migration activated?")
   97.70  
   97.71  
   97.72 @@ -96,31 +90,26 @@ while loop < 3:
   97.73      new_domid = domid(domName)
   97.74  
   97.75      if (old_domid == new_domid):
   97.76 -        vtpm_cleanup(domName)
   97.77          FAIL("xm migrate failed, domain id is still %s (loop=%d)" %
   97.78               (old_domid,loop))
   97.79  
   97.80      try:
   97.81          console = domain.getConsole()
   97.82      except ConsoleError, e:
   97.83 -        vtpm_cleanup(domName)
   97.84          FAIL(str(e))
   97.85  
   97.86      try:
   97.87          run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   97.88      except ConsoleError, e:
   97.89          saveLog(console.getHistory())
   97.90 -        vtpm_cleanup(domName)
   97.91          FAIL("No result from dumping the PCRs")
   97.92  
   97.93      if not re.search("PCR-00:",run["output"]):
   97.94          saveLog(console.getHistory())
   97.95 -        vtpm_cleanup(domName)
   97.96          FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side")
   97.97  
   97.98      if not re.search("PCR-00: 1E A7 BD",run["output"]):
   97.99          saveLog(console.getHistory())
  97.100 -        vtpm_cleanup(domName)
  97.101          FAIL("Virtual TPM lost PCR 0 value: \n%s" % run["output"])
  97.102  
  97.103      loop += 1
  97.104 @@ -128,5 +117,3 @@ while loop < 3:
  97.105  domain.closeConsole()
  97.106  
  97.107  domain.stop()
  97.108 -
  97.109 -vtpm_cleanup(domName)
    98.1 --- a/tools/xm-test/tests/vtpm/08_vtpm-mig_pcrs.py	Thu Jul 26 14:35:01 2007 -0600
    98.2 +++ b/tools/xm-test/tests/vtpm/08_vtpm-mig_pcrs.py	Fri Jul 27 08:15:16 2007 -0600
    98.3 @@ -14,6 +14,7 @@ from vtpm_utils import *
    98.4  import commands
    98.5  import os
    98.6  import os.path
    98.7 +import atexit
    98.8  
    98.9  config = {"vtpm":"instance=1,backend=0"}
   98.10  domain = XmTestDomain(extraConfig=config)
   98.11 @@ -25,45 +26,40 @@ try:
   98.12  except DomainError, e:
   98.13      if verbose:
   98.14          print e.extra
   98.15 -    vtpm_cleanup(domName)
   98.16      FAIL("Unable to create domain (%s)" % domName)
   98.17  
   98.18 +atexit.register(vtpm_cleanup, vtpm_get_uuid(domid(domName)))
   98.19 +
   98.20  try:
   98.21      console.sendInput("input")
   98.22  except ConsoleError, e:
   98.23      saveLog(console.getHistory())
   98.24 -    vtpm_cleanup(domName)
   98.25      FAIL(str(e))
   98.26  
   98.27  try:
   98.28      run = console.runCmd("mknod /dev/tpm0 c 10 224")
   98.29  except ConsoleError, e:
   98.30      saveLog(console.getHistory())
   98.31 -    vtpm_cleanup(domName)
   98.32      FAIL("Error while creating /dev/tpm0")
   98.33  
   98.34  try:
   98.35      run = console.runCmd("echo -ne \"\\x00\\xc1\\x00\\x00\\x00\\x22\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\0xf\\x10\\x11\\x12\\x13\\x14\" > seq; cat seq > /dev/tpm0")
   98.36  except ConsoleError, e:
   98.37      saveLog(console.getHistory())
   98.38 -    vtpm_cleanup(domName)
   98.39      FAIL("Error while extending PCR 0")
   98.40  
   98.41  try:
   98.42      run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   98.43  except ConsoleError, e:
   98.44      saveLog(console.getHistory())
   98.45 -    vtpm_cleanup(domName)
   98.46      FAIL("No result from dumping the PCRs")
   98.47  
   98.48  
   98.49  if re.search("No such file",run["output"]):
   98.50 -    vtpm_cleanup(domName)
   98.51      FAIL("TPM frontend support not compiled into (domU?) kernel")
   98.52  
   98.53  if not re.search("PCR-00:",run["output"]):
   98.54      saveLog(console.getHistory())
   98.55 -    vtpm_cleanup(domName)
   98.56      FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side: \n%s" % run["output"])
   98.57  
   98.58  if not re.search("PCR-00: 1E A7 BD",run["output"]):
   98.59 @@ -83,12 +79,10 @@ while loop < 3:
   98.60                                        timeout=90)
   98.61      except TimeoutError, e:
   98.62          saveLog(consoleHistory)
   98.63 -        vtpm_cleanup(domName)
   98.64          FAIL(str(e))
   98.65  
   98.66      if status != 0:
   98.67          saveLog(consoleHistory)
   98.68 -        vtpm_cleanup(domName)
   98.69          FAIL("xm migrate did not succeed. External device migration activated?")
   98.70  
   98.71  
   98.72 @@ -96,31 +90,26 @@ while loop < 3:
   98.73      new_domid = domid(domName)
   98.74  
   98.75      if (old_domid == new_domid):
   98.76 -        vtpm_cleanup(domName)
   98.77          FAIL("xm migrate failed, domain id is still %s (loop=%d)" %
   98.78               (old_domid,loop))
   98.79  
   98.80      try:
   98.81          console = domain.getConsole()
   98.82      except ConsoleError, e:
   98.83 -        vtpm_cleanup(domName)
   98.84          FAIL(str(e))
   98.85  
   98.86      try:
   98.87          run = console.runCmd("cat /sys/devices/xen/vtpm-0/pcrs")
   98.88      except ConsoleError, e:
   98.89          saveLog(console.getHistory())
   98.90 -        vtpm_cleanup(domName)
   98.91          FAIL("No result from dumping the PCRs")
   98.92  
   98.93      if not re.search("PCR-00:",run["output"]):
   98.94          saveLog(console.getHistory())
   98.95 -        vtpm_cleanup(domName)
   98.96          FAIL("Virtual TPM is not working correctly on /dev/vtpm on backend side")
   98.97  
   98.98      if not re.search("PCR-00: 1E A7 BD",run["output"]):
   98.99          saveLog(console.getHistory())
  98.100 -        vtpm_cleanup(domName)
  98.101          FAIL("Virtual TPM lost PCR 0 value: \n%s" % run["output"])
  98.102  
  98.103      loop += 1
  98.104 @@ -128,5 +117,3 @@ while loop < 3:
  98.105  domain.closeConsole()
  98.106  
  98.107  domain.stop()
  98.108 -
  98.109 -vtpm_cleanup(domName)
    99.1 --- a/tools/xm-test/tests/vtpm/vtpm_utils.py	Thu Jul 26 14:35:01 2007 -0600
    99.2 +++ b/tools/xm-test/tests/vtpm/vtpm_utils.py	Fri Jul 27 08:15:16 2007 -0600
    99.3 @@ -15,4 +15,16 @@ if output == "":
    99.4           "need /dev/tpm0")
    99.5  
    99.6  def vtpm_cleanup(domName):
    99.7 -    traceCommand("/etc/xen/scripts/vtpm-delete %s" % domName)
    99.8 +    traceCommand("/etc/xen/scripts/vtpm-delete "
    99.9 +                 "`xenstore-read /local/domain/0/backend/vtpm/%s/0/uuid`" %
   99.10 +                 str(domid(domName)))
   99.11 +
   99.12 +def vtpm_cleanup(uuid):
   99.13 +    from xen.xm import main
   99.14 +    if main.serverType != main.SERVER_XEN_API:
   99.15 +        traceCommand("/etc/xen/scripts/vtpm-delete %s" % uuid)
   99.16 +
   99.17 +def vtpm_get_uuid(domainid):
   99.18 +    s, o = traceCommand("xenstore-read "
   99.19 +                        "/local/domain/0/backend/vtpm/%s/0/uuid" % domainid)
   99.20 +    return o
   100.1 --- a/unmodified_drivers/linux-2.6/compat-include/xen/platform-compat.h	Thu Jul 26 14:35:01 2007 -0600
   100.2 +++ b/unmodified_drivers/linux-2.6/compat-include/xen/platform-compat.h	Fri Jul 27 08:15:16 2007 -0600
   100.3 @@ -107,4 +107,13 @@ extern char *kasprintf(gfp_t gfp, const 
   100.4  #define __supported_pte_mask ((maddr_t)0)
   100.5  #endif
   100.6  
   100.7 +#if defined(_LINUX_NETDEVICE_H) && LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18)
   100.8 +#define netif_tx_lock_bh(dev) (spin_lock_bh(&(dev)->xmit_lock))
   100.9 +#define netif_tx_unlock_bh(dev) (spin_unlock_bh(&(dev)->xmit_lock))
  100.10  #endif
  100.11 +
  100.12 +#if defined(__LINUX_SEQLOCK_H) && !defined(DEFINE_SEQLOCK)
  100.13 +#define DEFINE_SEQLOCK(x) seqlock_t x = SEQLOCK_UNLOCKED
  100.14 +#endif
  100.15 +
  100.16 +#endif
   101.1 --- a/unmodified_drivers/linux-2.6/netfront/Kbuild	Thu Jul 26 14:35:01 2007 -0600
   101.2 +++ b/unmodified_drivers/linux-2.6/netfront/Kbuild	Fri Jul 27 08:15:16 2007 -0600
   101.3 @@ -2,3 +2,4 @@ include $(M)/overrides.mk
   101.4  
   101.5  obj-m  = xen-vnif.o
   101.6  xen-vnif-objs	:= netfront.o
   101.7 +xen-vnif-objs	+= accel.o
   102.1 --- a/xen/Makefile	Thu Jul 26 14:35:01 2007 -0600
   102.2 +++ b/xen/Makefile	Fri Jul 27 08:15:16 2007 -0600
   102.3 @@ -59,7 +59,6 @@ build install debug clean distclean csco
   102.4  	$(MAKE) -f $(BASEDIR)/Rules.mk -C arch/$(TARGET_ARCH) clean
   102.5  	rm -f include/asm *.o $(TARGET)* *~ core
   102.6  	rm -f include/asm-*/asm-offsets.h
   102.7 -	rm -f include/xen/acm_policy.h
   102.8  
   102.9  .PHONY: _distclean
  102.10  _distclean: clean
  102.11 @@ -72,7 +71,6 @@ build install debug clean distclean csco
  102.12  $(TARGET): delete-unfresh-files build-headers
  102.13  	$(MAKE) -C tools
  102.14  	$(MAKE) -f $(BASEDIR)/Rules.mk include/xen/compile.h
  102.15 -	$(MAKE) -f $(BASEDIR)/Rules.mk include/xen/acm_policy.h
  102.16  	[ -e include/asm ] || ln -sf asm-$(TARGET_ARCH) include/asm
  102.17  	$(MAKE) -f $(BASEDIR)/Rules.mk -C include
  102.18  	$(MAKE) -f $(BASEDIR)/Rules.mk -C arch/$(TARGET_ARCH) asm-offsets.s
  102.19 @@ -87,20 +85,6 @@ delete-unfresh-files:
  102.20  		rm -f include/xen/compile.h; \
  102.21  	fi
  102.22  
  102.23 -# acm_policy.h contains security policy for Xen
  102.24 -include/xen/acm_policy.h:
  102.25 -	@(set -e; \
  102.26 -	  echo "/*"; \
  102.27 -	  echo " * DO NOT MODIFY."; \
  102.28 -	  echo " *"; \
  102.29 -	  echo " * This file was auto-generated by xen/Makefile $<"; \
  102.30 -	  echo " *"; \
  102.31 -	  echo " */"; \
  102.32 -	  echo ""; \
  102.33 -	  echo "#ifndef ACM_DEFAULT_SECURITY_POLICY"; \
  102.34 -	  echo "#define ACM_DEFAULT_SECURITY_POLICY $(ACM_DEFAULT_SECURITY_POLICY)"; \
  102.35 -	  echo "#endif") >$@
  102.36 -
  102.37  # compile.h contains dynamic build info. Rebuilt on every 'make' invocation.
  102.38  include/xen/compile.h: include/xen/compile.h.in
  102.39  	@sed -e 's/@@date@@/$(shell LC_ALL=C date)/g' \
   103.1 --- a/xen/acm/acm_chinesewall_hooks.c	Thu Jul 26 14:35:01 2007 -0600
   103.2 +++ b/xen/acm/acm_chinesewall_hooks.c	Fri Jul 27 08:15:16 2007 -0600
   103.3 @@ -73,10 +73,10 @@ int acm_init_chwall_policy(void)
   103.4          (domaintype_t *) xmalloc_array(domaintype_t,
   103.5                                         chwall_bin_pol.max_types);
   103.6  
   103.7 -    if ((chwall_bin_pol.conflict_sets == NULL)
   103.8 +    if ( (chwall_bin_pol.conflict_sets == NULL)
   103.9          || (chwall_bin_pol.running_types == NULL)
  103.10          || (chwall_bin_pol.ssidrefs == NULL)
  103.11 -        || (chwall_bin_pol.conflict_aggregate_set == NULL))
  103.12 +        || (chwall_bin_pol.conflict_aggregate_set == NULL) )
  103.13          return ACM_INIT_SSID_ERROR;
  103.14  
  103.15      /* initialize state */
  103.16 @@ -97,14 +97,15 @@ static int chwall_init_domain_ssid(void 
  103.17  {
  103.18      struct chwall_ssid *chwall_ssidp = xmalloc(struct chwall_ssid);
  103.19      traceprintk("%s.\n", __func__);
  103.20 -    if (chwall_ssidp == NULL)
  103.21 +
  103.22 +    if ( chwall_ssidp == NULL )
  103.23          return ACM_INIT_SSID_ERROR;
  103.24  
  103.25      chwall_ssidp->chwall_ssidref =
  103.26          GET_SSIDREF(ACM_CHINESE_WALL_POLICY, ssidref);
  103.27  
  103.28 -    if ((chwall_ssidp->chwall_ssidref >= chwall_bin_pol.max_ssidrefs)
  103.29 -        || (chwall_ssidp->chwall_ssidref == ACM_DEFAULT_LOCAL_SSID))
  103.30 +    if ( (chwall_ssidp->chwall_ssidref >= chwall_bin_pol.max_ssidrefs)
  103.31 +        || (chwall_ssidp->chwall_ssidref == ACM_DEFAULT_LOCAL_SSID) )
  103.32      {
  103.33          printkd("%s: ERROR chwall_ssidref(%x) undefined (>max) or unset (0).\n",
  103.34                  __func__, chwall_ssidp->chwall_ssidref);
  103.35 @@ -119,7 +120,6 @@ static int chwall_init_domain_ssid(void 
  103.36  
  103.37  static void chwall_free_domain_ssid(void *chwall_ssid)
  103.38  {
  103.39 -    traceprintk("%s.\n", __func__);
  103.40      xfree(chwall_ssid);
  103.41      return;
  103.42  }
  103.43 @@ -132,7 +132,7 @@ static int chwall_dump_policy(u8 * buf, 
  103.44          (struct acm_chwall_policy_buffer *) buf;
  103.45      int ret = 0;
  103.46  
  103.47 -    if (buf_size < sizeof(struct acm_chwall_policy_buffer))
  103.48 +    if ( buf_size < sizeof(struct acm_chwall_policy_buffer) )
  103.49          return -EINVAL;
  103.50  
  103.51      chwall_buf->chwall_max_types = cpu_to_be32(chwall_bin_pol.max_types);
  103.52 @@ -159,7 +159,7 @@ static int chwall_dump_policy(u8 * buf, 
  103.53  
  103.54      ret = (ret + 7) & ~7;
  103.55  
  103.56 -    if (buf_size < ret)
  103.57 +    if ( buf_size < ret )
  103.58          return -EINVAL;
  103.59  
  103.60      /* now copy buffers over */
  103.61 @@ -214,12 +214,12 @@ chwall_init_state(struct acm_chwall_poli
  103.62          traceprintk("%s: validating policy for domain %x (chwall-REF=%x).\n",
  103.63                      __func__, d->domain_id, chwall_ssidref);
  103.64          /* a) adjust types ref-count for running domains */
  103.65 -        for (i = 0; i < chwall_buf->chwall_max_types; i++)
  103.66 +        for ( i = 0; i < chwall_buf->chwall_max_types; i++ )
  103.67              running_types[i] +=
  103.68                  ssidrefs[chwall_ssidref * chwall_buf->chwall_max_types + i];
  103.69  
  103.70          /* b) check for conflict */
  103.71 -        for (i = 0; i < chwall_buf->chwall_max_types; i++)
  103.72 +        for ( i = 0; i < chwall_buf->chwall_max_types; i++ )
  103.73              if (conflict_aggregate_set[i] &&
  103.74                  ssidrefs[chwall_ssidref * chwall_buf->chwall_max_types + i])
  103.75              {
  103.76 @@ -233,11 +233,11 @@ chwall_init_state(struct acm_chwall_poli
  103.77              }
  103.78          /* set violation and break out of the loop */
  103.79          /* c) adapt conflict aggregate set for this domain (notice conflicts) */
  103.80 -        for (i = 0; i < chwall_buf->chwall_max_conflictsets; i++)
  103.81 +        for ( i = 0; i < chwall_buf->chwall_max_conflictsets; i++ )
  103.82          {
  103.83              int common = 0;
  103.84              /* check if conflict_set_i and ssidref have common types */
  103.85 -            for (j = 0; j < chwall_buf->chwall_max_types; j++)
  103.86 +            for ( j = 0; j < chwall_buf->chwall_max_types; j++ )
  103.87                  if (conflict_sets[i * chwall_buf->chwall_max_types + j] &&
  103.88                      ssidrefs[chwall_ssidref *
  103.89                              chwall_buf->chwall_max_types + j])
  103.90 @@ -248,7 +248,7 @@ chwall_init_state(struct acm_chwall_poli
  103.91              if (common == 0)
  103.92                  continue;       /* try next conflict set */
  103.93              /* now add types of the conflict set to conflict_aggregate_set (except types in chwall_ssidref) */
  103.94 -            for (j = 0; j < chwall_buf->chwall_max_types; j++)
  103.95 +            for ( j = 0; j < chwall_buf->chwall_max_types; j++ )
  103.96                  if (conflict_sets[i * chwall_buf->chwall_max_types + j] &&
  103.97                      !ssidrefs[chwall_ssidref *
  103.98                               chwall_buf->chwall_max_types + j])
  103.99 @@ -268,7 +268,8 @@ chwall_init_state(struct acm_chwall_poli
 103.100  int
 103.101  do_chwall_init_state_curr(struct acm_sized_buffer *errors)
 103.102  {
 103.103 -    struct acm_chwall_policy_buffer chwall_buf = {
 103.104 +    struct acm_chwall_policy_buffer chwall_buf =
 103.105 +    {
 103.106           /* only these two are important */
 103.107           .chwall_max_types        = chwall_bin_pol.max_types,
 103.108           .chwall_max_conflictsets = chwall_bin_pol.max_conflictsets,
 103.109 @@ -300,8 +301,8 @@ static int _chwall_update_policy(u8 *buf
 103.110      /* policy write-locked already */
 103.111      struct acm_chwall_policy_buffer *chwall_buf =
 103.112          (struct acm_chwall_policy_buffer *) buf;
 103.113 -    void *ssids = NULL, *conflict_sets = NULL, *running_types =
 103.114 -        NULL, *conflict_aggregate_set = NULL;
 103.115 +    void *ssids = NULL, *conflict_sets = NULL, *running_types = NULL,
 103.116 +         *conflict_aggregate_set = NULL;
 103.117  
 103.118      /* 1. allocate new buffers */
 103.119      ssids =
 103.120 @@ -317,23 +318,23 @@ static int _chwall_update_policy(u8 *buf
 103.121      conflict_aggregate_set =
 103.122          xmalloc_array(domaintype_t, chwall_buf->chwall_max_types);
 103.123  
 103.124 -    if ((ssids == NULL) || (conflict_sets == NULL)
 103.125 -        || (running_types == NULL) || (conflict_aggregate_set == NULL))
 103.126 +    if ( (ssids == NULL) || (conflict_sets == NULL) ||
 103.127 +         (running_types == NULL) || (conflict_aggregate_set == NULL) )
 103.128          goto error_free;
 103.129  
 103.130      /* 2. set new policy */
 103.131 -    if (chwall_buf->chwall_ssid_offset + sizeof(domaintype_t) *
 103.132 -        chwall_buf->chwall_max_types * chwall_buf->chwall_max_ssidrefs >
 103.133 -        buf_size)
 103.134 +    if ( chwall_buf->chwall_ssid_offset + sizeof(domaintype_t) *
 103.135 +         chwall_buf->chwall_max_types * chwall_buf->chwall_max_ssidrefs >
 103.136 +         buf_size )
 103.137          goto error_free;
 103.138  
 103.139      arrcpy(ssids, buf + chwall_buf->chwall_ssid_offset,
 103.140             sizeof(domaintype_t),
 103.141             chwall_buf->chwall_max_types * chwall_buf->chwall_max_ssidrefs);
 103.142  
 103.143 -    if (chwall_buf->chwall_conflict_sets_offset + sizeof(domaintype_t) *
 103.144 -        chwall_buf->chwall_max_types *
 103.145 -        chwall_buf->chwall_max_conflictsets > buf_size)
 103.146 +    if ( chwall_buf->chwall_conflict_sets_offset + sizeof(domaintype_t) *
 103.147 +         chwall_buf->chwall_max_types *
 103.148 +         chwall_buf->chwall_max_conflictsets > buf_size )
 103.149          goto error_free;
 103.150  
 103.151      arrcpy(conflict_sets, buf + chwall_buf->chwall_conflict_sets_offset,
 103.152 @@ -349,10 +350,10 @@ static int _chwall_update_policy(u8 *buf
 103.153  
 103.154      /* 3. now re-calculate the state for the new policy based on running domains;
 103.155       *    this can fail if new policy is conflicting with running domains */
 103.156 -    if (chwall_init_state(chwall_buf, ssids,
 103.157 -                          conflict_sets, running_types,
 103.158 -                          conflict_aggregate_set,
 103.159 -                          errors))
 103.160 +    if ( chwall_init_state(chwall_buf, ssids,
 103.161 +                           conflict_sets, running_types,
 103.162 +                           conflict_aggregate_set,
 103.163 +                           errors))
 103.164      {
 103.165          printk("%s: New policy conflicts with running domains. Policy load aborted.\n",
 103.166                 __func__);
 103.167 @@ -360,7 +361,8 @@ static int _chwall_update_policy(u8 *buf
 103.168      }
 103.169  
 103.170      /* if this was only a test run, exit with ACM_OK */
 103.171 -    if (test_only) {
 103.172 +    if ( test_only )
 103.173 +    {
 103.174          rc = ACM_OK;
 103.175          goto error_free;
 103.176      }
 103.177 @@ -377,10 +379,13 @@ static int _chwall_update_policy(u8 *buf
 103.178      chwall_bin_pol.conflict_aggregate_set = conflict_aggregate_set;
 103.179      chwall_bin_pol.running_types = running_types;
 103.180      chwall_bin_pol.conflict_sets = conflict_sets;
 103.181 +
 103.182      return ACM_OK;
 103.183  
 103.184   error_free:
 103.185 -    if (!test_only) printk("%s: ERROR setting policy.\n", __func__);
 103.186 +    if ( !test_only )
 103.187 +        printk("%s: ERROR setting policy.\n", __func__);
 103.188 +
 103.189      xfree(ssids);
 103.190      xfree(conflict_sets);
 103.191      xfree(running_types);
 103.192 @@ -397,7 +402,7 @@ static int chwall_test_policy(u8 *buf, u
 103.193      struct acm_chwall_policy_buffer *chwall_buf =
 103.194          (struct acm_chwall_policy_buffer *) buf;
 103.195  
 103.196 -    if (buf_size < sizeof(struct acm_chwall_policy_buffer))
 103.197 +    if ( buf_size < sizeof(struct acm_chwall_policy_buffer) )
 103.198          return -EINVAL;
 103.199  
 103.200      /* rewrite the policy due to endianess */
 103.201 @@ -419,16 +424,15 @@ static int chwall_test_policy(u8 *buf, u
 103.202          be32_to_cpu(chwall_buf->chwall_conflict_aggregate_offset);
 103.203  
 103.204      /* policy type and version checks */
 103.205 -    if ((chwall_buf->policy_code != ACM_CHINESE_WALL_POLICY) ||
 103.206 -        (chwall_buf->policy_version != ACM_CHWALL_VERSION))
 103.207 +    if ( (chwall_buf->policy_code != ACM_CHINESE_WALL_POLICY) ||
 103.208 +         (chwall_buf->policy_version != ACM_CHWALL_VERSION) )
 103.209          return -EINVAL;
 103.210  
 103.211      /* during boot dom0_chwall_ssidref is set */
 103.212 -    if (is_bootpolicy &&
 103.213 -        (dom0_chwall_ssidref >= chwall_buf->chwall_max_ssidrefs))
 103.214 +    if ( is_bootpolicy &&
 103.215 +         (dom0_chwall_ssidref >= chwall_buf->chwall_max_ssidrefs) )
 103.216          return -EINVAL;
 103.217  
 103.218 -
 103.219      return _chwall_update_policy(buf, buf_size, 1, errors);
 103.220  }
 103.221  
 103.222 @@ -448,17 +452,17 @@ static int chwall_dump_ssid_types(ssidre
 103.223      int i;
 103.224  
 103.225      /* fill in buffer */
 103.226 -    if (chwall_bin_pol.max_types > len)
 103.227 +    if ( chwall_bin_pol.max_types > len )
 103.228          return -EFAULT;
 103.229  
 103.230 -    if (ssidref >= chwall_bin_pol.max_ssidrefs)
 103.231 +    if ( ssidref >= chwall_bin_pol.max_ssidrefs )
 103.232          return -EFAULT;
 103.233  
 103.234      /* read types for chwall ssidref */
 103.235 -    for (i = 0; i < chwall_bin_pol.max_types; i++)
 103.236 +    for ( i = 0; i < chwall_bin_pol.max_types; i++ )
 103.237      {
 103.238 -        if (chwall_bin_pol.
 103.239 -            ssidrefs[ssidref * chwall_bin_pol.max_types + i])
 103.240 +        if ( chwall_bin_pol.
 103.241 +             ssidrefs[ssidref * chwall_bin_pol.max_types + i] )
 103.242              buf[i] = 1;
 103.243          else
 103.244              buf[i] = 0;
 103.245 @@ -476,15 +480,16 @@ static int _chwall_pre_domain_create(voi
 103.246  {
 103.247      ssidref_t chwall_ssidref;
 103.248      int i, j;
 103.249 -    traceprintk("%s.\n", __func__);
 103.250  
 103.251      chwall_ssidref = GET_SSIDREF(ACM_CHINESE_WALL_POLICY, ssidref);
 103.252 +
 103.253      if (chwall_ssidref == ACM_DEFAULT_LOCAL_SSID)
 103.254      {
 103.255          printk("%s: ERROR CHWALL SSID is NOT SET but policy enforced.\n",
 103.256                 __func__);
 103.257          return ACM_ACCESS_DENIED;       /* catching and indicating config error */
 103.258      }
 103.259 +
 103.260      if (chwall_ssidref >= chwall_bin_pol.max_ssidrefs)
 103.261      {
 103.262          printk("%s: ERROR chwall_ssidref > max(%x).\n",
 103.263 @@ -503,15 +508,15 @@ static int _chwall_pre_domain_create(voi
 103.264  
 103.265      /* B: chinese wall conflict set adjustment (so that other
 103.266       *      other domains simultaneously created are evaluated against this new set)*/
 103.267 -    for (i = 0; i < chwall_bin_pol.max_conflictsets; i++)
 103.268 +    for ( i = 0; i < chwall_bin_pol.max_conflictsets; i++ )
 103.269      {
 103.270          int common = 0;
 103.271          /* check if conflict_set_i and ssidref have common types */
 103.272 -        for (j = 0; j < chwall_bin_pol.max_types; j++)
 103.273 -            if (chwall_bin_pol.
 103.274 -                conflict_sets[i * chwall_bin_pol.max_types + j]
 103.275 -                && chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.276 -                                          chwall_bin_pol.max_types + j])
 103.277 +        for ( j = 0; j < chwall_bin_pol.max_types; j++ )
 103.278 +            if ( chwall_bin_pol.
 103.279 +                 conflict_sets[i * chwall_bin_pol.max_types + j]
 103.280 +                 && chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.281 +                                            chwall_bin_pol.max_types + j] )
 103.282              {
 103.283                  common = 1;
 103.284                  break;
 103.285 @@ -519,12 +524,12 @@ static int _chwall_pre_domain_create(voi
 103.286          if (common == 0)
 103.287              continue;           /* try next conflict set */
 103.288          /* now add types of the conflict set to conflict_aggregate_set (except types in chwall_ssidref) */
 103.289 -        for (j = 0; j < chwall_bin_pol.max_types; j++)
 103.290 -            if (chwall_bin_pol.
 103.291 -                conflict_sets[i * chwall_bin_pol.max_types + j]
 103.292 -                && !chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.293 -                                           chwall_bin_pol.max_types + j])
 103.294 -                chwall_bin_pol.conflict_aggregate_set[j]++;
 103.295 +        for ( j = 0; j < chwall_bin_pol.max_types; j++ )
 103.296 +            if ( chwall_bin_pol.
 103.297 +                 conflict_sets[i * chwall_bin_pol.max_types + j]
 103.298 +                 && !chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.299 +                                             chwall_bin_pol.max_types + j])
 103.300 +                 chwall_bin_pol.conflict_aggregate_set[j]++;
 103.301      }
 103.302      return ACM_ACCESS_PERMITTED;
 103.303  }
 103.304 @@ -534,18 +539,16 @@ static void _chwall_post_domain_create(d
 103.305  {
 103.306      int i, j;
 103.307      ssidref_t chwall_ssidref;
 103.308 -    traceprintk("%s.\n", __func__);
 103.309  
 103.310      chwall_ssidref = GET_SSIDREF(ACM_CHINESE_WALL_POLICY, ssidref);
 103.311      /* adjust types ref-count for running domains */
 103.312 -    for (i = 0; i < chwall_bin_pol.max_types; i++)
 103.313 +    for ( i = 0; i < chwall_bin_pol.max_types; i++ )
 103.314          chwall_bin_pol.running_types[i] +=
 103.315              chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.316                                     chwall_bin_pol.max_types + i];
 103.317 -    if (domid)
 103.318 -    {
 103.319 +    if ( domid )
 103.320          return;
 103.321 -    }
 103.322 +
 103.323      /* Xen does not call pre-create hook for DOM0;
 103.324       * to consider type conflicts of any domain with DOM0, we need
 103.325       * to adjust the conflict_aggregate for DOM0 here the same way it
 103.326 @@ -555,27 +558,27 @@ static void _chwall_post_domain_create(d
 103.327  
 103.328      /* chinese wall conflict set adjustment (so that other
 103.329       *      other domains simultaneously created are evaluated against this new set)*/
 103.330 -    for (i = 0; i < chwall_bin_pol.max_conflictsets; i++)
 103.331 +    for ( i = 0; i < chwall_bin_pol.max_conflictsets; i++ )
 103.332      {
 103.333          int common = 0;
 103.334          /* check if conflict_set_i and ssidref have common types */
 103.335 -        for (j = 0; j < chwall_bin_pol.max_types; j++)
 103.336 -            if (chwall_bin_pol.
 103.337 -                conflict_sets[i * chwall_bin_pol.max_types + j]
 103.338 -                && chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.339 -                                          chwall_bin_pol.max_types + j])
 103.340 +        for ( j = 0; j < chwall_bin_pol.max_types; j++ )
 103.341 +            if ( chwall_bin_pol.
 103.342 +                 conflict_sets[i * chwall_bin_pol.max_types + j]
 103.343 +                 && chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.344 +                                            chwall_bin_pol.max_types + j] )
 103.345              {
 103.346                  common = 1;
 103.347                  break;
 103.348              }
 103.349 -        if (common == 0)
 103.350 +        if ( common == 0 )
 103.351              continue;           /* try next conflict set */
 103.352          /* now add types of the conflict set to conflict_aggregate_set (except types in chwall_ssidref) */
 103.353 -        for (j = 0; j < chwall_bin_pol.max_types; j++)
 103.354 -            if (chwall_bin_pol.
 103.355 -                conflict_sets[i * chwall_bin_pol.max_types + j]
 103.356 -                && !chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.357 -                                           chwall_bin_pol.max_types + j])
 103.358 +        for ( j = 0; j < chwall_bin_pol.max_types; j++ )
 103.359 +            if ( chwall_bin_pol.
 103.360 +                 conflict_sets[i * chwall_bin_pol.max_types + j]
 103.361 +                 && !chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.362 +                                             chwall_bin_pol.max_types + j] )
 103.363                  chwall_bin_pol.conflict_aggregate_set[j]++;
 103.364      }
 103.365      return;
 103.366 @@ -593,10 +596,11 @@ static int chwall_domain_create(void *su
 103.367  {
 103.368      int rc;
 103.369      read_lock(&acm_bin_pol_rwlock);
 103.370 +
 103.371      rc = _chwall_pre_domain_create(subject_ssid, ssidref);
 103.372 -    if (rc == ACM_ACCESS_PERMITTED) {
 103.373 +    if ( rc == ACM_ACCESS_PERMITTED )
 103.374          _chwall_post_domain_create(domid, ssidref);
 103.375 -    }
 103.376 +
 103.377      read_unlock(&acm_bin_pol_rwlock);
 103.378      return rc;
 103.379  }
 103.380 @@ -613,25 +617,23 @@ static void chwall_domain_destroy(void *
 103.381                                                   object_ssid);
 103.382      ssidref_t chwall_ssidref = chwall_ssidp->chwall_ssidref;
 103.383  
 103.384 -    traceprintk("%s.\n", __func__);
 103.385 +    read_lock(&acm_bin_pol_rwlock);
 103.386  
 103.387 -    read_lock(&acm_bin_pol_rwlock);
 103.388      /* adjust running types set */
 103.389 -    for (i = 0; i < chwall_bin_pol.max_types; i++)
 103.390 +    for ( i = 0; i < chwall_bin_pol.max_types; i++ )
 103.391          chwall_bin_pol.running_types[i] -=
 103.392              chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.393                                     chwall_bin_pol.max_types + i];
 103.394  
 103.395      /* roll-back: re-adjust conflicting types aggregate */
 103.396 -    for (i = 0; i < chwall_bin_pol.max_conflictsets; i++)
 103.397 +    for ( i = 0; i < chwall_bin_pol.max_conflictsets; i++ )
 103.398      {
 103.399          int common = 0;
 103.400          /* check if conflict_set_i and ssidref have common types */
 103.401 -        for (j = 0; j < chwall_bin_pol.max_types; j++)
 103.402 -            if (chwall_bin_pol.
 103.403 -                conflict_sets[i * chwall_bin_pol.max_types + j]
 103.404 -                && chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.405 -                                          chwall_bin_pol.max_types + j])
 103.406 +        for ( j = 0; j < chwall_bin_pol.max_types; j++ )
 103.407 +            if ( chwall_bin_pol.conflict_sets[i * chwall_bin_pol.max_types + j]
 103.408 +                 && chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.409 +                                            chwall_bin_pol.max_types + j])
 103.410              {
 103.411                  common = 1;
 103.412                  break;
 103.413 @@ -639,17 +641,26 @@ static void chwall_domain_destroy(void *
 103.414          if (common == 0)
 103.415              continue;           /* try next conflict set, this one does not include any type of chwall_ssidref */
 103.416          /* now add types of the conflict set to conflict_aggregate_set (except types in chwall_ssidref) */
 103.417 -        for (j = 0; j < chwall_bin_pol.max_types; j++)
 103.418 -            if (chwall_bin_pol.
 103.419 -                conflict_sets[i * chwall_bin_pol.max_types + j]
 103.420 -                && !chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.421 -                                           chwall_bin_pol.max_types + j])
 103.422 +        for ( j = 0; j < chwall_bin_pol.max_types; j++ )
 103.423 +            if ( chwall_bin_pol.
 103.424 +                 conflict_sets[i * chwall_bin_pol.max_types + j]
 103.425 +                 && !chwall_bin_pol.ssidrefs[chwall_ssidref *
 103.426 +                                             chwall_bin_pol.max_types + j])
 103.427                  chwall_bin_pol.conflict_aggregate_set[j]--;
 103.428      }
 103.429 +
 103.430      read_unlock(&acm_bin_pol_rwlock);
 103.431 +
 103.432      return;
 103.433  }
 103.434  
 103.435 +
 103.436 +static int chwall_is_default_policy(void)
 103.437 +{
 103.438 +    return ( (chwall_bin_pol.max_types    == 1 ) &&
 103.439 +             (chwall_bin_pol.max_ssidrefs == 2 ) );
 103.440 +}
 103.441 +
 103.442  struct acm_operations acm_chinesewall_ops = {
 103.443      /* policy management services */
 103.444      .init_domain_ssid = chwall_init_domain_ssid,
 103.445 @@ -674,6 +685,9 @@ struct acm_operations acm_chinesewall_op
 103.446      .fail_grant_setup = NULL,
 103.447      /* generic domain-requested decision hooks */
 103.448      .sharing = NULL,
 103.449 +    .authorization = NULL,
 103.450 +
 103.451 +    .is_default_policy = chwall_is_default_policy,
 103.452  };
 103.453  
 103.454  /*
   104.1 --- a/xen/acm/acm_core.c	Thu Jul 26 14:35:01 2007 -0600
   104.2 +++ b/xen/acm/acm_core.c	Fri Jul 27 08:15:16 2007 -0600
   104.3 @@ -314,26 +314,7 @@ acm_init(char *policy_start,
   104.4      return ret;
   104.5  }
   104.6  
   104.7 -int
   104.8 -acm_init_domain_ssid(domid_t id, ssidref_t ssidref)
   104.9 -{
  104.10 -    struct domain *subj = rcu_lock_domain_by_id(id);
  104.11 -    int ret;
  104.12 - 
  104.13 -    if (subj == NULL)
  104.14 -    {
  104.15 -        printk("%s: ACM_NULL_POINTER ERROR (id=%x).\n", __func__, id);
  104.16 -        return ACM_NULL_POINTER_ERROR;
  104.17 -    }
  104.18 -
  104.19 -    ret = acm_init_domain_ssid_new(subj, ssidref);
  104.20 -
  104.21 -    rcu_unlock_domain(subj);
  104.22 -
  104.23 -    return ret;
  104.24 -}
  104.25 -
  104.26 -int acm_init_domain_ssid_new(struct domain *subj, ssidref_t ssidref)
  104.27 +int acm_init_domain_ssid(struct domain *subj, ssidref_t ssidref)
  104.28  {
  104.29      struct acm_ssid_domain *ssid;
  104.30      int ret1, ret2;
  104.31 @@ -374,10 +355,6 @@ int acm_init_domain_ssid_new(struct doma
  104.32          return ACM_INIT_SSID_ERROR;
  104.33      }
  104.34  
  104.35 -    write_lock(&ssid_list_rwlock);
  104.36 -    list_add(&ssid->node, &ssid_list);
  104.37 -    write_unlock(&ssid_list_rwlock);
  104.38 -
  104.39      printkd("%s: assigned domain %x the ssidref=%x.\n",
  104.40             __func__, subj->domain_id, ssid->ssidref);
  104.41      return ACM_OK;
  104.42 @@ -399,10 +376,6 @@ acm_free_domain_ssid(struct acm_ssid_dom
  104.43          acm_secondary_ops->free_domain_ssid(ssid->secondary_ssid);
  104.44      ssid->secondary_ssid = NULL;
  104.45  
  104.46 -    write_lock(&ssid_list_rwlock);
  104.47 -    list_del(&ssid->node);
  104.48 -    write_unlock(&ssid_list_rwlock);
  104.49 -
  104.50      xfree(ssid);
  104.51      printkd("%s: Freed individual domain ssid (domain=%02x).\n",
  104.52              __func__, id);
   105.1 --- a/xen/acm/acm_policy.c	Thu Jul 26 14:35:01 2007 -0600
   105.2 +++ b/xen/acm/acm_policy.c	Fri Jul 27 08:15:16 2007 -0600
   105.3 @@ -37,9 +37,9 @@
   105.4  static int acm_check_deleted_ssidrefs(struct acm_sized_buffer *dels,
   105.5                                        struct acm_sized_buffer *errors);
   105.6  static void acm_doms_change_ssidref(ssidref_t (*translator)
   105.7 -                                     (const struct acm_ssid_domain *,
   105.8 -                                      const struct acm_sized_buffer *),
   105.9 -                                      struct acm_sized_buffer *translation_map);
  105.10 +                                   (const struct acm_ssid_domain *,
  105.11 +                                    const struct acm_sized_buffer *),
  105.12 +                                    struct acm_sized_buffer *translation_map);
  105.13  static void acm_doms_restore_ssidref(void);
  105.14  static ssidref_t oldssid_to_newssid(const struct acm_ssid_domain *,
  105.15                                      const struct acm_sized_buffer *map);
  105.16 @@ -50,15 +50,15 @@ acm_set_policy(XEN_GUEST_HANDLE_64(void)
  105.17  {
  105.18      u8 *policy_buffer = NULL;
  105.19      int ret = -EFAULT;
  105.20 - 
  105.21 -    if (buf_size < sizeof(struct acm_policy_buffer))
  105.22 +
  105.23 +    if ( buf_size < sizeof(struct acm_policy_buffer) )
  105.24          return -EFAULT;
  105.25  
  105.26      /* copy buffer from guest domain */
  105.27 -    if ((policy_buffer = xmalloc_array(u8, buf_size)) == NULL)
  105.28 +    if ( (policy_buffer = xmalloc_array(u8, buf_size)) == NULL )
  105.29          return -ENOMEM;
  105.30  
  105.31 -    if (copy_from_guest(policy_buffer, buf, buf_size))
  105.32 +    if ( copy_from_guest(policy_buffer, buf, buf_size) )
  105.33      {
  105.34          printk("%s: Error copying!\n",__func__);
  105.35          goto error_free;
  105.36 @@ -87,24 +87,28 @@ static int
  105.37                     struct acm_sized_buffer *errors)
  105.38  {
  105.39      uint32_t offset, length;
  105.40 +    static int require_update = 0;
  105.41  
  105.42      write_lock(&acm_bin_pol_rwlock);
  105.43  
  105.44 +    if (  require_update != 0 &&
  105.45 +        ( deletions == NULL || ssidchanges == NULL ) )
  105.46 +        goto error_lock_free;
  105.47 +
  105.48 +    require_update = 1;
  105.49      /*
  105.50         first some tests to check compatibility of new policy with
  105.51         current state of system/domains
  105.52       */
  105.53  
  105.54      /* if ssidrefs are to be deleted, make sure no domain is using them */
  105.55 -    if (deletions != NULL) {
  105.56 -        if (acm_check_deleted_ssidrefs(deletions, errors))
  105.57 +    if ( deletions != NULL )
  105.58 +        if ( acm_check_deleted_ssidrefs(deletions, errors) )
  105.59              goto error_lock_free;
  105.60 -    }
  105.61  
  105.62 -    if ((ssidchanges != NULL) && (ssidchanges->num_items > 0)) {
  105.63 +    if ( (ssidchanges != NULL) && (ssidchanges->num_items > 0) )
  105.64          /* assign all running domains new ssidrefs as requested */
  105.65          acm_doms_change_ssidref(oldssid_to_newssid, ssidchanges);
  105.66 -    }
  105.67  
  105.68      /* test primary policy data with the new ssidrefs */
  105.69      offset = be32_to_cpu(pol->primary_buffer_offset);
  105.70 @@ -122,9 +126,8 @@ static int
  105.71      if ( (offset + length) > buf_size ||
  105.72           acm_secondary_ops->test_binary_policy(buf + offset, length,
  105.73                                                 is_bootpolicy,
  105.74 -                                               errors)) {
  105.75 +                                               errors))
  105.76          goto error_lock_free;
  105.77 -    }
  105.78  
  105.79      /* end of testing --- now real updates */
  105.80  
  105.81 @@ -133,7 +136,7 @@ static int
  105.82  
  105.83      /* set label reference name */
  105.84      if ( (offset + length) > buf_size ||
  105.85 -        acm_set_policy_reference(buf + offset, length) )
  105.86 +         acm_set_policy_reference(buf + offset, length) )
  105.87          goto error_lock_free;
  105.88  
  105.89      /* set primary policy data */
  105.90 @@ -153,11 +156,17 @@ static int
  105.91             &pol->xml_pol_version,
  105.92             sizeof(acm_bin_pol.xml_pol_version));
  105.93