public ImportImageAction(IXenConnection connection, EnvelopeType ovfEnv, string directory, Dictionary<string, VmMapping> vmMappings, bool runfixups, SR selectedIsoSr,
									string networkUuid, bool isTvmIpStatic, string tvmIpAddress, string tvmSubnetMask, string tvmGateway)
			: base(connection, Messages.IMPORT_DISK_IMAGE, networkUuid, isTvmIpStatic, tvmIpAddress, tvmSubnetMask, tvmGateway)
		{
			m_ovfEnvelope = ovfEnv;
			m_directory = directory;
			m_vmMappings = vmMappings;
			m_runfixups = runfixups;
			m_selectedIsoSr = selectedIsoSr;
		}
		public ImportApplianceAction(IXenConnection connection, EnvelopeType ovfEnv, Package package, Dictionary<string, VmMapping> vmMappings,
										bool verifyManifest, bool verifySignature, string password, bool runfixups, SR selectedIsoSr,
										string networkUuid, bool isTvmIpStatic, string tvmIpAddress, string tvmSubnetMask, string tvmGateway)
			: base(connection, Messages.IMPORT_APPLIANCE, networkUuid, isTvmIpStatic, tvmIpAddress, tvmSubnetMask, tvmGateway)
		{
			m_ovfEnvelope = ovfEnv;
			m_package = package;
			m_vmMappings = vmMappings;
			m_verifyManifest = verifyManifest;
			m_verifySignature = verifySignature;
			m_password = password;
			m_runfixups = runfixups;
			m_selectedIsoSr = selectedIsoSr;
		}
Exemple #3
0
 /// <summary>
 /// Decrypt the files associated with the provided OVF package.
 /// </summary>
 /// <param name="env">EnvelopeType ovf object</param>
 /// <param name="ovfFileName">fullpath/filename</param>
 /// <param name="password">password to use during decryption.</param>
 public void Decrypt(EnvelopeType env, string ovfFileName, string password)
 {
     _cancelEncrypt = false;
     CryptoFileWrapper(env, ovfFileName, password, false);
     if (_cancelEncrypt)
     {
         Log.Info("Encrypt: CANCELLED successfully.");
     }
     else
     {
         SaveAs(env, ovfFileName);
     }
 }
Exemple #4
0
        private void TransformXvaOvf_Network(EnvelopeType env, string vsId, string lang, string refId, XenStruct vmstruct)
        {
            string networkName = null;

            foreach (XenMember n in vmstruct.xenmember)
            {
                //
                // Currently these are the only values we care about.
                //
                if (n.xenname.ToLower().Equals("name_label") &&
                         n.xenvalue != null &&
                         n.xenvalue is string &&
                         ((string)n.xenvalue).Length > 0)
                {
                    networkName = ((string)n.xenvalue);
                    break;
                }
            }

            foreach (Section_Type section in env.Sections)
            {
                if (section is NetworkSection_Type)
                {
                    NetworkSection_Type ns = (NetworkSection_Type)section;
                    foreach (NetworkSection_TypeNetwork net in ns.Network)
                    {
                        if (net.Description != null &&
                            net.Description.msgid != null &&
                            net.Description.msgid.Equals(mappings[refId]))
                        {
                            net.Description.Value = networkName;
                            break;
                        }
                    }
                    break;
                }
            }
            log.DebugFormat("OVF.TransformXvaOvf_Network completed {0}", vsId);
        }
Exemple #5
0
        /// <summary>
        /// Validate password prior do decrypting, depends on sample encrypted section in The SecuritySection.
        /// </summary>
        /// <param name="ovfObj">EnvelopeType OVF Object</param>
        /// <param name="password">password to check</param>
        /// <returns>true = valid password, false = password failed</returns>
        public bool CheckPassword(EnvelopeType ovfObj, string password)
        {
            bool isValid = false;

            SecuritySection_Type[] security = FindSections<SecuritySection_Type>(ovfObj.Sections);

            if (security != null && security.Length == 1)
            {
                foreach (Security_Type sec in security[0].Security)
                {
                    EncryptedDataType edt = null;

                    if (sec.EncryptedData != null && sec.EncryptedData.CipherData != null && sec.EncryptedData.CipherData.Item != null)
                    {
                        edt = sec.EncryptedData;
                    }
                    if (edt == null && sec.Any != null)
                    {
                        foreach (XmlElement xe in sec.Any)
                        {
                            if (xe.Name.Contains(":EncryptedData") || xe.Name.Contains(":EncrypteData"))
                            {
                                CipherDataType cdt = (CipherDataType)Tools.Deserialize(xe.InnerXml, typeof(CipherDataType));
                                edt = new EncryptedDataType();
                                edt.CipherData = cdt;
                            }
                        }
                    }

                    if (edt != null)
                    {
                        if (sec.version != null &&
                            CheckSecurityVersion(sec.version, Properties.Settings.Default.securityVersion) >= 0)
                        {
                            isValid = InternalCheckPassword((byte[])edt.CipherData.Item, password, sec.version);
                        }
                        else
                        {
                            isValid = DeprecatedCheckPassword((byte[])edt.CipherData.Item, password, sec.version);
                        }
                    }
                    else
                    {
                        throw new Exception(Messages.SECURITY_SECTION_INVALID);
                    }
                }

            }
            if (isValid)
            {
                Log.Audit(Messages.PASSWORD_SUCCESS);
            }
            else
            {
                Log.Audit(Messages.PASSWORD_FAILED);
            }
            return isValid;
        }
Exemple #6
0
        private void ProcessCompression(EnvelopeType env, string path, string method, bool compress)
        {
            if (env.References != null && env.References.File != null && env.References.File.Length > 0)
            {
                foreach (File_Type file in env.References.File)
                {
                    if (compress)
                    {
                        if (method.ToLower() != "gzip" && method.ToLower() != "bzip2")
                            throw new InvalidDataException(string.Format(Messages.COMPRESS_INVALID_METHOD, method));
                    }
                    else
                    {
                        if (file.compression == null)
                        {
                            Log.Info("File {0} was not marked as compressed, skipped.", file.href);
                            continue;
                        }
                        if (file.compression.ToLower() != "gzip" && file.compression.ToLower() != "bzip2")
                        {
                            Log.Error("Invalid compression method File: {0} Method: {1}, must be Gzip or BZip2", file.href, file.compression);
                            continue;
                        }

                        method = file.compression;
                    }

                    int slash = file.href.LastIndexOf('/');
                    string filename =  slash >= 0 ? file.href.Substring(slash + 1) : file.href;

                    filename = Path.Combine(path, filename);

                    string tempfile = Path.Combine(path, Path.GetFileName(Path.GetTempFileName()));

                    try
                    {
                        if (method.ToLower() == "gzip")
                        {
                            using(var inputFile = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                            {
                                using (var outputFile = new FileStream(tempfile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
                                {
                                    if (compress)
                                        GZipCompress(inputFile, outputFile);
                                    else
                                        GZipDecompress(inputFile, outputFile);
                                }
                                inputFile.Flush();
                            }

                            //the original file should be overwritten only if the process has succeeded, so it should
                            //be done here and not in the finally block, because if compression/decompression fails
                            //for some reason, the original file is lost
                            File.Delete(filename);
                            File.Move(tempfile, filename);
                        }
                        else
                        {
                            throw new InvalidDataException(string.Format(Messages.COMPRESS_INVALID_METHOD, method));
                        }
                        file.compression = compress ? method : null;
                    }
                    catch (EndOfStreamException eose)
                    {
                        Log.Error("End of Stream: {0}", eose.Message);
                    }
                    catch (Exception ex)
                    {
                        if (ex is OperationCanceledException)
                            throw;
                        var message = string.Format(Messages.COMPRESS_FAILED, filename);
                        Log.Error("{0} {1}", message, ex.Message);
                        throw new Exception(message, ex);
                    }
                    finally
                    {
                        //in case of failure or cancellation delete the temp file;
                        //in case of success it won't be there, but no exception is thrown
                        File.Delete(tempfile);
                    }
                    FileInfo fi = new FileInfo(filename);
                    file.size = (ulong)fi.Length;
                }
            }
        }
Exemple #7
0
        private void TransformXvaOvf_VBD(EnvelopeType env, string vsId, string lang, XenStruct vmstruct)
        {
            string diskId = null;
            string vhdfilename = "";
            bool bootable = false;
            string caption = null;
            string description = null;
            ulong filesize = 0;
            ulong capacity = 0;
            string vdiuuid = null;

            bool isDisk = false;

            StringBuilder connection = new StringBuilder();
            foreach (XenMember n in vmstruct.xenmember)
            {
                //
                // Currently these are the only values we care about.
                //
                if (n.xenname.ToLower().Equals("uuid") &&
                    n.xenvalue != null &&
                    n.xenvalue is string &&
                    ((string)n.xenvalue).Length > 0)
                {
                    vdiuuid = (string)n.xenvalue;
                    if (!vdiuuid.ToLower().Contains("null"))
                    {
                        diskId = string.Format(@"Xen:{0}/{1}", vsId, vdiuuid);
                    }
                    else
                    {
                        vdiuuid = null;
                    }
                }
                else if (n.xenname.ToLower().Equals("vdi") &&
                         n.xenvalue != null &&
                         n.xenvalue is string &&
                         ((string)n.xenvalue).Length > 0)
                {
                    string vdiref = ((string)n.xenvalue);
                    if (!vdiref.ToLower().Contains("null"))
                    {
                        if (!mappings.ContainsKey(vdiref))
                        {
                            mappings.Add(vdiref, vdiuuid);
                        }
                    }
                }
                else if (n.xenname.ToLower().Equals("userdevice") &&
                         n.xenvalue != null &&
                         n.xenvalue is string &&
                         ((string)n.xenvalue).Length > 0)
                {
                    connection.AppendFormat("device={0},", ((string)n.xenvalue));
                }
                else if (n.xenname.ToLower().Equals("bootable") &&
                         n.xenvalue != null &&
                         n.xenvalue is string &&
                         ((string)n.xenvalue).Length > 0)
                {
                    connection.AppendFormat("bootable={0},", ((string)n.xenvalue));
                    bootable = Convert.ToBoolean(((string)n.xenvalue));
                }
                else if (n.xenname.ToLower().Equals("mode") &&
                         n.xenvalue != null &&
                         n.xenvalue is string &&
                         ((string)n.xenvalue).Length > 0)
                {
                    connection.AppendFormat("mode={0},", ((string)n.xenvalue));
                }
                else if (n.xenname.ToLower().Equals("type") &&
                         n.xenvalue != null &&
                         n.xenvalue is string &&
                         ((string)n.xenvalue).Length > 0)
                {
                    switch (((string)n.xenvalue).ToUpper())
                    {
                        case "CD":
                            {
                                isDisk = false;
                                caption = _ovfrm.GetString("RASD_16_CAPTION");
                                description = _ovfrm.GetString("RASD_16_DESCRIPTION");
                                break;
                            }
                        case "DISK":
                            {
                                caption = _ovfrm.GetString("RASD_19_CAPTION");
                                description = _ovfrm.GetString("RASD_19_DESCRIPTION");
                                isDisk = true;
                                break;
                            }
                    }
                }
            }
            if (vdiuuid != null)
                connection.AppendFormat("vdi={0}", vdiuuid);

            if (isDisk)
            {
                AddDisk(env, vsId, diskId, lang, vhdfilename, bootable, caption, description, filesize, capacity);
                UpdateResourceAllocationSettingData(env, vsId, diskId, "Connection", connection.ToString());
            }
            else
            {
                AddCDROM(env, vsId, diskId, caption, description);
            }
            log.DebugFormat("OVF.TransformXvaOvf_VBD completed {0}", vsId);
        }
Exemple #8
0
 public OvfStorageResource(RASD_Type type, EnvelopeType envelopeType)
 {
     rasd = type;
     envelope = envelopeType;
     file = OVF.FindFileReferenceByRASD(envelope, rasd);
 }
Exemple #9
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="env"></param>
 /// <param name="ovfilename"></param>
 /// <param name="method"></param>
 /// <param name="compress"></param>
 public void CompressOvfFiles(EnvelopeType env, string ovfilename, string method, bool compress)
 {
     ProcessCompression(env, Path.GetDirectoryName(ovfilename), method, compress);
     OVF.SaveAs(env, ovfilename);
 }
Exemple #10
0
 private void AddNetworks(EnvelopeType ovfEnv, string vsId)
 {
     AddNetworks(ovfEnv, vsId, Properties.Settings.Default.Language);
 }
Exemple #11
0
 private void AddNetworks(EnvelopeType ovfEnv, string vsId, string lang)
 {
     if (Win32_NetworkAdapter != null)
     {
         foreach (ManagementObject mo in Win32_NetworkAdapter)
         {
             // Only get the physical adapters, not logical (which there are numerous)
             //if ((bool)mo["PhysicalAdapter"])
             bool addThisNetwork = false;
             string macaddress = null;
             string description = null;
             //
             // setPriority is used to determine the description
             // 0 = unset
             // 1 highest priority
             // 2 next
             // 3 next
             // ...
             //
             int setPriority = 0;
             foreach (PropertyData pd in mo.Properties)
             {
                 if (pd.Name != null && pd.Name.Length > 0)
                 {
                     if (pd.Name.ToLower().Equals("macaddress") && pd.Value != null && ((string)pd.Value).Length > 0)
                     {
                         macaddress = (string)pd.Value;
                     }
                     else if (pd.Name.ToLower().Equals("netconnectionid") && pd.Value != null && ((string)pd.Value).Length > 0)
                     {
                         description = (string)pd.Value;
                         setPriority = 1;
                     }
                     else if (pd.Name.ToLower().Equals("name") && pd.Value != null && ((string)pd.Value).Length > 0)
                     {
                         if (setPriority == 0 || setPriority > 2)
                         {
                             description = (string)pd.Value;
                             setPriority = 2;
                         }
                     }
                     else if (pd.Name.ToLower().Equals("description") && pd.Value != null && ((string)pd.Value).Length > 0)
                     {
                         if (setPriority == 0 || setPriority > 3)
                         {
                             description = (string)pd.Value;
                             setPriority = 3;
                         }
                     }
                     // Below is trying to figure out if this is a Network Connection that
                     // is to be exported/defined.
                     // The issue is WMI has different value sets for different types of hardware
                     // such as hardware as we know it... pci ethernet
                     // or blade style, which WMI gives a different result.
                     // WAN/RAS connections.. etc.
                     // ANY one of the values can set this to true:
                     //      netconnectionstatus
                     //      pnpdeviceid
                     //      physicaladapter
                     //
                     else if (pd.Name.ToLower().Equals("netconnectionstatus") && pd.Value != null)
                     {
                         if ((UInt16)pd.Value == 0x2)
                         {
                             addThisNetwork = true;
                         }
                     }
                     else if (pd.Name.ToLower().Equals("pnpdeviceid") && pd.Value != null && ((string)pd.Value).Length > 0)
                     {
                         if ((((string)pd.Value).ToLower().StartsWith("pci") || ((string)pd.Value).ToLower().StartsWith("scsi")))
                         {
                             addThisNetwork = true;
                         }
                     }
                     else if (pd.Name.ToLower().Equals("physicaladapter") && pd.Value != null)
                     {
                         addThisNetwork = (bool)pd.Value;
                     }
                 }
             }
             if (addThisNetwork)
             {
                 AddNetwork(ovfEnv, vsId, lang, Guid.NewGuid().ToString(), description, macaddress);
             }
         }
     }
     else
     {
         log.Warn("No networks defined, If a network interface is required, the administrator will need to add it after import of OVF/OVA Package.");
     }
     log.DebugFormat("OVF.AddNetworks completed {0}", vsId);
 }
Exemple #12
0
        private void AddCPUs(EnvelopeType ovfEnv, string vsId, string lang)
        {
            UInt64 cpucount = 0;
            if (Win32_Processor != null && Win32_Processor.Count > 0)
            {
                foreach (ManagementObject mo in Win32_Processor)
                {
                    #region FIND BY PROPERTIES NOT EXPLICID
                    uint numberofcores = 1;

                    foreach (PropertyData pd in mo.Properties)
                    {
                        if (pd.Name.ToLower().Equals("numberofcores") && pd.Value != null)
                        {
                            numberofcores = (uint)pd.Value;
                        }
                    }
                    #endregion
                    cpucount += Convert.ToUInt64(numberofcores);
                }

                SetCPUs(ovfEnv, vsId, cpucount);
            }
            else
            {
                SetCPUs(ovfEnv, vsId, 1);
                log.Warn("OVF.AddCPUs, set using default (1) CPU");
            }
            log.DebugFormat("OVF.AddCPUs completed {0} cpus {1}", vsId, cpucount);
        }
Exemple #13
0
        private void AddMemory(EnvelopeType ovfEnv, string vsId, string lang)
        {
            ulong divisor = 1024 * 1024;
            ulong totalphysicalmemory = divisor * 512;  // 512MB Default Memory
            ulong memory = 0;

            if (Win32_ComputerSystem != null)
            {
                #region FIND BY PROPERTIES NOT EXPLICID

                foreach (PropertyData pd in Win32_ComputerSystem.Properties)
                {
                    if (pd.Name.ToLower().Equals("totalphysicalmemory") && pd.Value != null)
                    {
                        totalphysicalmemory = (ulong)pd.Value;
                        break;
                    }
                }
                #endregion
                memory = totalphysicalmemory / divisor;
            }
            else
            {
                log.Warn("OVF.AddMemory: could not determine system memory, defaulting to 512MB");
                memory = 512L;
            }
            SetMemory(ovfEnv, vsId, memory, "byte * 2^20");
            log.DebugFormat("OVF.AddMemory completed {0} memory {1} (byte * 2 ^ 20)", vsId, memory);
        }
Exemple #14
0
        private void TransformXvaOvf_VM(EnvelopeType env, string vsId, string lang, XenStruct vmstruct)
        {
            int PVvalue = 0;
            foreach (XenMember n in vmstruct.xenmember)
            {
                //
                // Currently these are the only values we care about.
                //
                if (n.xenname.ToLower().Equals("uuid"))
                {
                    UpdateVirtualSystemSettingData(env, vsId, "VirtualSystemIdentifier", (string)n.xenvalue);
                }
                if (n.xenname.ToLower().Equals("name_label"))
                {
                    if (n.xenvalue != null && n.xenvalue is string && ((string)n.xenvalue).Length > 0)
                    {
                        UpdateVirtualSystemName(env, vsId, lang, (string)n.xenvalue);
                        UpdateVirtualSystemSettingData(env, vsId, "ElementName", (string)n.xenvalue);
                        UpdateVirtualSystemSettingData(env, vsId, "Caption", _ovfrm.GetString("CONVERT_APP_NAME"));
                    }
                }
                else if (n.xenname.ToLower().Equals("memory_static_max"))
                {
                    if (n.xenvalue != null && n.xenvalue is string && ((string)n.xenvalue).Length > 0)
                    {
                        UInt64 memory = Convert.ToUInt64(n.xenvalue) / MB;
                        SetMemory(env, vsId, memory, "MB");
                    }
                }
                else if (n.xenname.ToLower().Equals("vcpus_max"))
                {
                    if (n.xenvalue != null && n.xenvalue is string && ((string)n.xenvalue).Length > 0)
                    {
                        UInt64 cpus = Convert.ToUInt64(n.xenvalue);
                        SetCPUs(env, vsId, cpus);
                    }
                }
                else if (
                         n.xenname.ToLower().Equals("pv_bootloader") ||
                         n.xenname.ToLower().Equals("pv_kernel") ||
                         n.xenname.ToLower().Equals("pv_ramdisk") ||
                         n.xenname.ToLower().Equals("pv_args") ||
                         n.xenname.ToLower().Equals("pv_bootloader_args") ||
                         n.xenname.ToLower().Equals("pv_legacy_args") ||
                         n.xenname.ToLower().Equals("hvm_boot_policy") ||
                         n.xenname.ToLower().Equals("hvm_shadow_multiplier")
                        )
                {
                    if (n.xenvalue != null && n.xenvalue is string && ((string)n.xenvalue).Length > 0)
                    {
                        if (n.xenname.ToLower().StartsWith("pv"))
                        {
                            PVvalue++;
                        }
                        if (n.xenname.ToLower().StartsWith("hvm_boot"))
                        {
                            PVvalue--;
                        }
                        AddOtherSystemSettingData(env, vsId, lang, n.xenname, (string)n.xenvalue, _ovfrm.GetString("XENSERVER_SPECIFIC_DESCRIPTION"));
                    }
                }
                else if (n.xenname.ToLower().Equals("hvm_boot_params"))
                {

                    if (n.xenvalue != null && n.xenvalue is XenStruct && ((XenStruct)n.xenvalue).xenmember != null)
                    {
                        string bootorder = "dc";
                        foreach (XenMember xm in ((XenStruct)n.xenvalue).xenmember)
                        {
                            PVvalue--;
                            if (xm.xenname.ToLower().Equals("order"))
                            {
                                if (xm.xenvalue != null && xm.xenvalue is string && ((string)xm.xenvalue).Length > 0)
                                {
                                    bootorder = (string)xm.xenvalue;
                                }
                            }
                        }
                        AddOtherSystemSettingData(env, vsId, lang, n.xenname, bootorder, _ovfrm.GetString("XENSERVER_SPECIFIC_DESCRIPTION"));
                    }
                }
                else if (n.xenname.ToLower().Equals("platform"))
                {
                    if (n.xenvalue != null && n.xenvalue is XenStruct && ((XenStruct)n.xenvalue).xenmember != null)
                    {
                        StringBuilder p = new StringBuilder();
                        foreach (XenMember xm in ((XenStruct)n.xenvalue).xenmember)
                        {
                            if (xm.xenvalue != null && xm.xenvalue is string && ((string)xm.xenvalue).Length > 0)
                            {
                                p.AppendFormat("{0}={1}; ", xm.xenname, (string)xm.xenvalue);
                            }
                        }
                        AddOtherSystemSettingData(env, vsId, lang, n.xenname, p.ToString().Trim(), _ovfrm.GetString("XENSERVER_PLATFORM_DESCRIPTION"));
                    }
                }
                else if (n.xenname.ToLower().Equals("other_config"))
                {
                    // Ignored, why you say? Because I haven't found one that is 'required' to reproduce the vm, yet.
                }
                else if (n.xenname.ToLower().Equals("domarch"))
                {
                    // Can't depend on a value here but we need to set it to work correctly.
                    if (n.xenvalue != null && n.xenvalue is string && ((string)n.xenvalue).Length > 0)
                    {
                        string svalue = (string)n.xenvalue;

                        if (svalue.Equals("hvm"))
                        {
                            PVvalue = -10;
                        }
                    }

                    if (PVvalue < 0)
                    {
                        UpdateVirtualSystemSettingData(env, vsId, "VirtualSystemType", "hvm-3.0-unknown");
                    }
                    else
                    {
                        UpdateVirtualSystemSettingData(env, vsId, "VirtualSystemType", "xen-3.0-unknown");
                    }
                }
            }
            log.DebugFormat("OVF.TransformXvaOvf_VM completed {0}", vsId);
        }
Exemple #15
0
        private void TransformXvaOvf_VIF(EnvelopeType env, string vsId, string lang, XenStruct vmstruct)
        {
            string vifuuid = null;
            string mac = null;

            foreach (XenMember n in vmstruct.xenmember)
            {
                //
                // Currently these are the only values we care about.
                //
                if (n.xenname.ToLower().Equals("uuid") &&
                    n.xenvalue != null &&
                    n.xenvalue is string &&
                    ((string)n.xenvalue).Length > 0)
                {
                    vifuuid = (string)n.xenvalue;
                    if (vifuuid.ToLower().Contains("null"))
                    {
                        vifuuid = null;
                    }
                }
                else if (n.xenname.ToLower().Equals("network") &&
                         n.xenvalue != null &&
                         n.xenvalue is string &&
                         ((string)n.xenvalue).Length > 0)
                {
                    string netref = ((string)n.xenvalue);
                    if (!netref.ToLower().Contains("null"))
                    {
                        if (!mappings.ContainsKey(netref))
                        {
                            mappings.Add(netref, vifuuid);
                        }
                    }
                }
                else if (n.xenname.ToLower().Equals("mac") &&
                         n.xenvalue != null &&
                         n.xenvalue is string &&
                         ((string)n.xenvalue).Length > 0)
                {
                    mac = ((string)n.xenvalue);
                }
            }
            AddNetwork(env, vsId, lang, vifuuid, null, mac);
            log.DebugFormat("OVF.TransformXvaOvf_VIF completed {0}", vsId);
        }
Exemple #16
0
 private void TransformXvaOvf_VDI(EnvelopeType env, string vsId, string lang, string refId, DiskInfo di, XenStruct vmstruct)
 {
     string instanceId = null;
     if (mappings.ContainsKey(refId))
     {
         instanceId = string.Format(@"Xen:{0}/{1}", vsId, mappings[refId]);
     }
     else
     {
         instanceId = string.Format(@"Xen:{0}/{1}", vsId, Guid.NewGuid().ToString());
     }
     string description = null;
     string vhdfilename = di.VhdFileName;
     ulong filesize = 0;
     ulong capacity = 0;
     ulong freespace = 0;
     foreach (XenMember n in vmstruct.xenmember)
     {
         if (n.xenname.ToLower().Equals("virtual_size"))
         {
             capacity = Convert.ToUInt64(n.xenvalue);
         }
         else if (n.xenname.ToLower().Equals("physical_utilisation"))
         {
             filesize = Convert.ToUInt64(n.xenvalue);
         }
     }
     freespace = capacity - filesize;
     UpdateDisk(env, vsId, instanceId, description, vhdfilename, filesize, capacity, freespace);
     log.DebugFormat("OVF.TransformXvaOvf_VDI completed {0}", vsId);
 }
Exemple #17
0
        private static void CryptoFileWrapper(EnvelopeType env, string ovffilename, string password, bool encrypt)
        {
            bool process = true;

            if ((env.References == null) ||
                (env.References.File == null) ||
                (env.References.File.Length == 0))
            {
                Log.Info("OVF.Security: No files to encrypt/decrypt.");
                return;
            }
            try
            {
                List<DataReference> dataReference = new List<DataReference>();
                string cryptoclassname = (string)AlgorithmMap((Properties.Settings.Default.encryptAlgorithmURI.Split(new char[] { '#' }))[1].ToLower().Replace('-', '_'));
                int keysize = Convert.ToInt32(Properties.Settings.Default.encryptKeyLength);
                string fileuuids = null;
                string version = null;
                //
                // Initial version really only works when there is ONLY ONE SecuritySection::Security
                //
                #region GET DECRYPT INFO
                if (!encrypt)
                {
                    SecuritySection_Type securitysection = null;
                    foreach (Section_Type section in env.Sections)
                    {
                        if (section is SecuritySection_Type)
                        {
                            securitysection = (SecuritySection_Type)section;
                            break;
                        }
                    }
                    foreach (Security_Type securitytype in securitysection.Security)
                    {
                        foreach (XenOvf.Definitions.XENC.ReferenceType dataref in securitytype.ReferenceList.Items)
                        {
                            if (dataref is DataReference)
                            {
                                fileuuids += ":" + ((DataReference)dataref).ValueType;
                            }
                        }
                        if (securitytype.EncryptionMethod != null &&
                            securitytype.EncryptionMethod.Algorithm != null)
                        {
                            string algoname = (securitytype.EncryptionMethod.Algorithm.Split(new char[] { '#' }))[1].ToLower().Replace('-', '_');
                            object x = Properties.Settings.Default[algoname];
                            if (x != null)
                            {
                                cryptoclassname = (string)x;
                                keysize = Convert.ToInt32(securitytype.EncryptionMethod.KeySize);
                            }
                        }
                        if (!string.IsNullOrEmpty(securitytype.version))
                        {
                            version = securitytype.version;
                        }
                    }
                }
                #endregion

                #region PROCESS FILES
                foreach (File_Type file in env.References.File)
                {
                    if (encrypt)
                    {
                        version = Properties.Settings.Default.securityVersion;
                        if (file.Id == null)
                        {
                            file.Id = "xen_" + Guid.NewGuid().ToString();
                            DataReference newDataReference = new DataReference();
                            newDataReference.ValueType = file.Id;
                            dataReference.Add(newDataReference);
                            process = true;
                        }
                        else
                        {
                            Log.Info("File already encrypted, skipping. [{0}]", file.href);
                            process = false;
                        }
                    }
                    else
                    {
                        if (file.Id != null &&
                            fileuuids != null &&
                            fileuuids.ToLower().Contains(file.Id.ToLower()))
                        {
                            process = true;
                            file.Id = null;
                        }
                        else
                        {
                            process = false;
                            Log.Info("File is not encrypted, skipping. [{0}]", file.href);
                        }
                    }

                    if (process)
                    {
                        string fullname = string.Format(@"{0}\{1}", Path.GetDirectoryName(ovffilename), file.href);
                        Log.Debug(@"{0} : {1}", encrypt ? "Encrypt" : "Decrypt", fullname);
                        ICryptoTransform trans = CryptoSetup(cryptoclassname, password, encrypt, version);
                        CryptoFile(trans, fullname, fullname + ".tmp", encrypt);
                        if (_cancelEncrypt)
                        {
                            File.Delete(fullname + ".tmp");
                        }
                        else
                        {
                            File.Delete(fullname);
                            File.Move(fullname + ".tmp", fullname);
                        }
                    }
                }
                #endregion

                #region BUILD SECURITY SECTION
                if (encrypt && process && !_cancelEncrypt)
                {
                    List<Section_Type> sections = new List<Section_Type>();
                    SecuritySection_Type securitySection = null;

                    foreach (Section_Type section in env.Sections)
                    {
                        if (section is SecuritySection_Type)
                        {
                            securitySection = (SecuritySection_Type)section;
                        }
                        else
                        {
                            sections.Add(section);
                        }
                    }

                    if (securitySection == null)
                    {
                        securitySection = new SecuritySection_Type();
                        securitySection.Info = new Msg_Type();
                        securitySection.Info.Value = "Encrypted Content Definition";
                    }

                    List<Security_Type> secType = new List<Security_Type>();
                    if (securitySection.Security != null && securitySection.Security.Length > 0)
                    {
                        secType.AddRange(securitySection.Security);
                    }

                    Security_Type securityType = new Security_Type();
                    securityType.version = Properties.Settings.Default.securityVersion;
                    securityType.Id = "xen_" + Guid.NewGuid().ToString();
                    ReferenceList referenceList = new ReferenceList();
                    referenceList.Items = dataReference.ToArray();
                    List<ItemsChoiceType3> ictList = new List<ItemsChoiceType3>();
                    for (int i = 0; i < dataReference.Count; i++)
                    {
                        ictList.Add(ItemsChoiceType3.DataReference);
                    }
                    referenceList.ItemsElementName = ictList.ToArray();
                    EncryptionMethodType encryptMethod = new EncryptionMethodType();
                    encryptMethod.KeySize = Convert.ToString(_KeySize);
                    encryptMethod.Algorithm = Properties.Settings.Default.encryptAlgorithmURI;

                    EncryptedDataType EncryptedData = new EncryptedDataType();
                    EncryptedData.CipherData = new CipherDataType();

                    CryptoElement(EncryptedData, KnownEncrypt, cryptoclassname, version, password);

                    securityType.ReferenceList = referenceList;
                    securityType.EncryptionMethod = encryptMethod;
                    securityType.EncryptedData = EncryptedData;

                    secType.Add(securityType);
                    securitySection.Security = secType.ToArray();
                    sections.Add(securitySection);
                    env.Sections = sections.ToArray();
                }
                #endregion
            }
            catch (Exception ex)
            {
                Log.Error("OVF.Security: Cryptography error: {0}", ex.Message);
                throw ex;
            }
        }
Exemple #18
0
 private void AddVssd(EnvelopeType ovfEnv, string vsId, string vhsId)
 {
     AddVssd(ovfEnv, vsId, vhsId, Properties.Settings.Default.Language);
 }
Exemple #19
0
 public OvfStorageResourceContainer( EnvelopeType selectedOvfEnvelope, string sysId)
 {
     rasdArray = OVF.FindDiskRasds(selectedOvfEnvelope, sysId);
     this.selectedOvfEnvelope = selectedOvfEnvelope;
 }
Exemple #20
0
        private void AddVssd(EnvelopeType ovfEnv, string vsId, string vhsId, string lang)
        {
            if (Win32_ComputerSystem != null)
            {
                #region FIND BY PROPERTIES NOT EXPLICID
                string name = "Generic Computer";
                string caption = "Generic Caption";
                string description = "Autogenerated OVF/OVA Package";

                foreach (PropertyData pd in Win32_ComputerSystem.Properties)
                {
                    if (pd.Name.ToLower().Equals("name") && pd.Value != null)
                    {
                        name = (string)pd.Value;
                    }
                    else if (pd.Name.ToLower().Equals("caption") && pd.Value != null)
                    {
                        caption = (string)pd.Value;
                    }
                    else if (pd.Name.ToLower().Equals("description") && pd.Value != null)
                    {
                        description = (string)pd.Value;
                    }
                }
                #endregion
                UpdateVirtualSystemName(ovfEnv, vsId, lang, name);
                AddVirtualSystemSettingData(ovfEnv,
                                            vsId,
                                            vhsId,
                                            name,
                                            caption,
                                            description,
                                            Guid.NewGuid().ToString(),
                                            "301"); // 301 == Microsoft (source), hvm-3.0-unknown == (xen source) Microsoft && Linux NOT PV'd, xen-3.0-unknown == PV'd

            }
            else
            {
                Random rand = new Random();
                string name = string.Format(Messages.AUTOGENERATED, rand.Next());
                string caption = string.Format(Messages.UNKNOWN);
                string description = string.Format(Messages.UNKNOWN);
                UpdateVirtualSystem(ovfEnv, vsId, lang, name);
                AddVirtualSystemSettingData(ovfEnv,
                                            vsId,
                                            vhsId,
                                            name,
                                            caption,
                                            description,
                                            Guid.NewGuid().ToString(),
                                            "301");
                log.Warn("System definition not available, created defaults");
            }
            log.Debug("OVF.AddVssd completed");
        }
 public OvfNetworkResourceContainer(string sysId, EnvelopeType envelopeType)
 {
     rasdArray = OVF.FindRasdByType(envelopeType, sysId, 10);
 }
Exemple #22
0
        private void SetDeviceConnections(EnvelopeType ovfEnv, VirtualHardwareSection_Type vhs)
        {
            int[] connections = new int[16];
            int deviceoffset = 0;
            List<RASD_Type> rasdList = new List<RASD_Type>();

            rasdList.AddRange(vhs.Item);
            rasdList.Sort(compareControllerRasd);  // sorts based on ResourceType.Value

            // For Xen really nothing to do here, does not support the different
            // controller types, therefore we must ensure
            // via positional on controllers.
            // IDE - #1
            // SCSI - #2
            // IDE 0 Disk 0  Goes to Xen: userdevice=0
            // IDE 0 Disk 1  Goes to Xen: userdevice=1
            // IDE 1 CD/DVD 0  Goes to Xen: userdevice=2
            // IDE 1 Disk 1  UnUsed
            // SCSI 0 Disk 0 Goes to Xen: userdevice=3
            // SCSI 0 Disk 1 Goes to Xen: userdevice=4
            // and so forth.

            foreach (RASD_Type rasd in rasdList)
            {
                switch (rasd.ResourceType.Value)
                {
                    case 5:  // IDE Controller #1
                    case 6:  // Parallel SCSI HBA #2
                    case 7:  // FC HBA #3
                    case 8:  // iSCSI HBA #4
                    case 9:  // IB HCA #5
                        {
                            List<RASD_Type> connectedrasds = FindConnectedItems(rasd.InstanceID.Value, vhs.Item, null);
                            foreach (RASD_Type _rasd in connectedrasds)
                            {
                                //if (_rasd.Connection != null &&
                                //    _rasd.Connection.Length > 0 &&
                                //    _rasd.Connection[0] != null &&
                                //    _rasd.Connection[0].Value != null &&
                                //    _rasd.Connection[0].Value.Length > 0)
                                if (_rasd.ResourceType.Value == 15 || _rasd.ResourceType.Value == 16)
                                {
                                    deviceoffset = 2;
                                }
                                else
                                {
                                    deviceoffset = 0;
                                }
                                if (Tools.ValidateProperty("Connection", _rasd))
                                {
                                    if (!_rasd.Connection[0].Value.ToLower().Contains("device="))
                                    {
                                       _rasd.Connection[0].Value = string.Format("{0},device={1}", _rasd.Connection[0].Value, FindNextAvailable(deviceoffset, connections, 0));
                                    }
                                }
                                else
                                {
                                    _rasd.Connection = new cimString[] { new cimString(string.Format("device={0}", FindNextAvailable(deviceoffset, connections, 0))) };
                                }
                            }
                            break;
                        }
                }
            }
        }
Exemple #23
0
 /// <summary>
 /// Check the Envelope to see if the files are compressed.
 /// </summary>
 /// <param name="env">EnvelopeType</param>
 /// <param name="method">out method used: Gzip | BZip2</param>
 /// <returns>True|False</returns>
 public bool IsCompressed(EnvelopeType env, out string method)
 {
     if (env.References != null && env.References.File != null && env.References.File.Length > 0)
     {
         foreach (File_Type file in env.References.File)
         {
             if (!string.IsNullOrEmpty(file.compression))
             {
                 method = file.compression;
                 return true;
             }
         }
     }
     method = "none";
     return false;
 }
Exemple #24
0
 public void Process(EnvelopeType ovfObj, string pathToOvf, string passcode)
 {
     Process(XenSession, ovfObj, pathToOvf, passcode);
 }
Exemple #25
0
        /// <summary>
        /// Checks to see if an OVF is encrypted.
        /// </summary>
        /// <param name="ovfFilename">EnvelopeType OVF object</param>
        /// <returns>true = is encrypted, false = not encrypted</returns>
        public static bool HasEncryption(EnvelopeType ovfObj)
        {
            SecuritySection_Type[] security = FindSections<SecuritySection_Type>(ovfObj.Sections);

            if (security != null && security.Length > 0)
            {
                return true;  // we now know that a security section is defined therefore something is encrypted.
            }
            return false;
        }
Exemple #26
0
 private void TransformXvaOvf_SR(EnvelopeType env, string vsId, string lang, XenStruct vmstruct)
 {
     //
     // Currently this is data for the Environment not necessarily part of the VM
     // even if the VM is in this SR it may not exist in the target server therefore
     // it is not required in the OVF.
     //
     log.DebugFormat("OVF.TransformXvaOvf_SR completed {0}", vsId);
 }
Exemple #27
0
        private void SetIfDeviceIsBootable(EnvelopeType ovfEnv, RASD_Type rasd)
        {
            // This is a best guess algorithm. without opening the VHD itself, there is no guarrenteed method
            // to delineate this, so we guess.
            // IF it's created by Kensho/XenConvert there will be a chance of having a clue.
            // Otherwise it'll be based upon 'order' and device 0 will win the bootable device.
            bool isBootable = true;
            VirtualDiskDesc_Type[] disks = null;

            foreach (Section_Type sect in ovfEnv.Sections)
            {
                if (sect is DiskSection_Type)
                {
                    disks = ((DiskSection_Type)sect).Disk;
                }
            }

            if (disks == null)
                return;

            bool useHostResource = false;
            if (Tools.ValidateProperty("HostResource", rasd))
            {
                log.Debug("Using HostResource to find Disk");
                useHostResource = true;
            }
            else
            {
                log.Debug("Using InstanceID to find Disk");
            }

            foreach(VirtualDiskDesc_Type disk in disks)
            {
                if (useHostResource)
                {
                    if (rasd.HostResource[0].Value.Contains(disk.diskId))
                    {
                        isBootable = disk.isBootable;
                    }
                }
                else
                {
                    if (rasd.InstanceID.Value.Contains(disk.diskId))
                    {
                        isBootable = disk.isBootable;
                    }
                }
            }

            if (Tools.ValidateProperty("Address", rasd))
            {
                if ((rasd.ResourceType.Value == 21 ||
                    rasd.ResourceType.Value == 5) &&
                    rasd.Address.Value == "0")
                {
                    isBootable = true;
                }
            }

            if (Tools.ValidateProperty("AddressOnParent", rasd))
            {
                if ((rasd.ResourceType.Value == 17 ||
                    rasd.ResourceType.Value == 19) &&
                    rasd.AddressOnParent.Value == "0")
                {
                    isBootable = true;
                }
            }

            if (Tools.ValidateProperty("Connection", rasd))
            {
                if (rasd.Connection[0].Value.Contains("device=0"))
                {
                    isBootable = true;
                }
                if (!rasd.Connection[0].Value.Contains("bootable"))
                {
                    rasd.Connection[0].Value = string.Format("{0},bootable={1}", rasd.Connection[0].Value, isBootable);
                }
            }
            else
            {
                rasd.Connection = new cimString[] { new cimString(string.Format("bootable={0}", isBootable)) };
            }
        }
Exemple #28
0
        /// <summary>
        /// An ovf can contain both encrypted and non-encrypted file mixed together.
        /// find if file name is encrypted.
        /// 1. check the References for the security ID
        /// 2. check the Security id section exists.
        /// </summary>
        /// <param name="ovfObj">OVF Envelope</param>
        /// <param name="filename">filename to check</param>
        /// <returns>true = encrypted; false = not encrypted</returns>
        public static bool IsThisEncrypted(EnvelopeType ovfObj, RASD_Type rasd)
        {
            bool _isEncrypted = false;
            // 15,16,17,19,20 are attached files.
            // rest is RASD specific

            switch (rasd.ResourceType.Value)
            {
                case 15:
                case 16:
                case 17:
                case 19:
                case 20:
                    {
                        File_Type file = FindFileReferenceByRASD(ovfObj, rasd);
                        if (file != null)
                        {
                            if (!string.IsNullOrEmpty(file.Id))
                            {
                                _isEncrypted = IsThisIdEncrypted(ovfObj, file.Id);
                            }
                        }
                        break;
                    }
                default:
                    {
                        // currently encrypted RASD or Elements, isn't being done, but this can check it.
                        if (rasd.AnyAttr != null && rasd.AnyAttr.Length > 0)
                        {
                            foreach (XmlAttribute xa in rasd.AnyAttr)
                            {
                                if (xa.Name.ToLower().Equals("xenc:id"))
                                {
                                    _isEncrypted = IsThisIdEncrypted(ovfObj, xa.Value);
                                    break;
                                }
                            }
                        }
                        break;
                    }
            }
            return _isEncrypted;
        }
Exemple #29
0
        public void Process(Session xenSession, EnvelopeType ovfObj, string pathToOvf, string passcode)
        {
            if (xenSession == null)
                throw new InvalidOperationException(Messages.ERROR_NOT_CONNECTED);

            string ovfname = Guid.NewGuid().ToString();

            vifDeviceIndex = 0;
            string encryptionVersion = null;

            #region CHECK ENCRYPTION
            if (OVF.HasEncryption(ovfObj))
            {
                if (passcode == null)
                {
                    throw new InvalidDataException(Messages.ERROR_NO_PASSWORD);
                }
                string fileuuids = null;
                SecuritySection_Type[] securitysection = OVF.FindSections<SecuritySection_Type>((ovfObj).Sections);
                if (securitysection != null && securitysection.Length >= 0)
                {
                    foreach (Security_Type securitytype in securitysection[0].Security)
                    {
                        if (securitytype.ReferenceList.Items != null && securitytype.ReferenceList.Items.Length > 0)
                        {
                            foreach (XenOvf.Definitions.XENC.ReferenceType dataref in securitytype.ReferenceList.Items)
                            {
                                if (dataref is DataReference)
                                {
                                    fileuuids += ":" + ((DataReference)dataref).ValueType;
                                }
                            }
                        }
                        if (securitytype.EncryptionMethod != null && securitytype.EncryptionMethod.Algorithm != null)
                        {
                            string algoname = (securitytype.EncryptionMethod.Algorithm.Split(new char[] { '#' }))[1].ToLower().Replace('-', '_');
                            object x = OVF.AlgorithmMap(algoname);
                            if (x != null)
                            {
                                EncryptionClass = (string)x;
                                EncryptionKeySize = Convert.ToInt32(securitytype.EncryptionMethod.KeySize);
                            }
                        }

                        if (!string.IsNullOrEmpty(securitytype.version))
                        {
                            encryptionVersion = securitytype.version;
                        }
                    }
                }
            }
            #endregion

            #region FIND DEFAULT SR
            Dictionary<XenRef<Pool>, Pool> pools = Pool.get_all_records(xenSession);
            foreach (XenRef<Pool> pool in pools.Keys)
            {
                DefaultSRUUID = pools[pool].default_SR;
                break;
            }
            #endregion

            //
            // So the process is the same below, change this
            //
            if (ovfObj.Item is VirtualSystem_Type)
            {
                VirtualSystem_Type vstemp = (VirtualSystem_Type)ovfObj.Item;
                ovfObj.Item = new VirtualSystemCollection_Type();
                ((VirtualSystemCollection_Type)ovfObj.Item).Content = new Content_Type[] { vstemp };
            }

            #region Create appliance

            XenRef<VM_appliance> applRef = null;
            if (ApplianceName != null)
            {
                var vmAppliance = new VM_appliance {name_label = ApplianceName, Connection = xenSession.Connection};
                applRef = VM_appliance.create(xenSession, vmAppliance);
            }

            #endregion

            foreach (VirtualSystem_Type vSystem in ((VirtualSystemCollection_Type)ovfObj.Item).Content)
            {
               //FIND/SET THE NAME OF THE VM
                ovfname = OVF.FindSystemName(ovfObj, vSystem.id);
                auditLog.DebugFormat("Import: {0}, {1}", ovfname, pathToOvf);

                VirtualHardwareSection_Type vhs = OVF.FindVirtualHardwareSectionByAffinity(ovfObj, vSystem.id, "xen");

                XenRef<VM> vmRef = DefineSystem(xenSession, vhs, ovfname);
                if (vmRef == null)
                {
                    log.Error(Messages.ERROR_CREATE_VM_FAILED);
                    throw new ImportException(Messages.ERROR_CREATE_VM_FAILED);
                }

                HideSystem(xenSession, vmRef);
                log.DebugFormat("OVF.Import.Process: DefineSystem completed ({0})", VM.get_name_label(xenSession, vmRef));

                #region Set appliance
                if (applRef != null)
                    VM.set_appliance(xenSession, vmRef.opaque_ref, applRef.opaque_ref);

                if (ovfObj.Sections != null)
                {
                    StartupSection_Type[] startUpArray = OVF.FindSections<StartupSection_Type>(ovfObj.Sections);
                    if (startUpArray != null && startUpArray.Length > 0)
                    {
                        var startupSection = startUpArray[0];
                        var itemList = startupSection.Item;

                        if (itemList != null)
                        {
                            var item = itemList.FirstOrDefault(it => it.id == vSystem.id);

                            if (item != null)
                            {
                                VM.set_start_delay(xenSession, vmRef.opaque_ref, item.startDelay);
                                VM.set_shutdown_delay(xenSession, vmRef.opaque_ref, item.stopDelay);
                                VM.set_order(xenSession, vmRef.opaque_ref, item.order);
                            }
                        }
                    }
                }

                #endregion

                #region set has_vendor_device

                if (Helpers.DundeeOrGreater(xenSession.Connection))
                {
                    var data = vhs.VirtualSystemOtherConfigurationData;
                    if (data != null)
                    {
                        var datum = data.FirstOrDefault(s => s.Name == "VM_has_vendor_device");
                        if (datum != null)
                        {
                            bool hasVendorDevice;
                            if (bool.TryParse(datum.Value.Value, out hasVendorDevice) && hasVendorDevice)
                                VM.set_has_vendor_device(xenSession, vmRef.opaque_ref, hasVendorDevice);
                        }
                    }
                }

                #endregion

                #region Set vgpu

                GPU_group gpuGroup;
                VGPU_type vgpuType;
                FindGpuGroupAndVgpuType(xenSession, vhs, out gpuGroup, out vgpuType);

                if (gpuGroup != null)
                {
                    var other_config = new Dictionary<string, string>();

                    if (Helpers.FeatureForbidden(xenSession, Host.RestrictVgpu))
                        VGPU.create(xenSession, vmRef.opaque_ref, gpuGroup.opaque_ref, "0", other_config);
                    else if (vgpuType != null)
                        VGPU.create(xenSession, vmRef.opaque_ref, gpuGroup.opaque_ref, "0", other_config, vgpuType.opaque_ref);
                }

                #endregion

                SetDeviceConnections(ovfObj, vhs);
                try
                {
                    foreach (RASD_Type rasd in vhs.Item)
                    {
                        string thisPassCode = null;
                        // Check to see if THIS rasd is encrypted, if so, set the passcode.
                        if (OVF.IsThisEncrypted(ovfObj, rasd))
                            thisPassCode = passcode;

                        string compression = "None";
                        if (rasd.ResourceType.Value == 17 || rasd.ResourceType.Value == 19 || rasd.ResourceType.Value == 21)
                        {
                            bool skip = Tools.ValidateProperty("Caption", rasd) &&
                                 (
                                  rasd.Caption.Value.ToUpper().Contains("COM") ||
                                  rasd.Caption.Value.ToUpper().Contains("FLOPPY") ||
                                  rasd.Caption.Value.ToUpper().Contains("ISO")
                                 );

                            if (!skip)
                            {
                                File_Type file = OVF.FindFileReferenceByRASD(ovfObj, rasd);
                                if (file == null)
                                    continue;

                                if (IsKnownURIType(file.href))
                                    _filedownloadsize = file.size;

                                VirtualDiskDesc_Type vdisk = OVF.FindDiskReference(ovfObj, rasd);
                                SetIfDeviceIsBootable(ovfObj, rasd);
                                AdditionalSpace = OVF.ComputeCapacity(Convert.ToInt64(vdisk.capacity), vdisk.capacityAllocationUnits);  // used in Wim file imports only.
                                AddResourceSettingData(xenSession, vmRef, rasd, pathToOvf, OVF.FindRasdFileName(ovfObj, rasd, out compression), compression, encryptionVersion, thisPassCode);
                            }
                        }
                        else
                        {
                            AddResourceSettingData(xenSession, vmRef, rasd, pathToOvf, OVF.FindRasdFileName(ovfObj, rasd, out compression), compression, encryptionVersion, thisPassCode);
                        }
                    }

                    InstallSection_Type[] installSection = OVF.FindSections<InstallSection_Type>(vSystem.Items);

                    if (installSection != null && installSection.Length == 1)
                    {
                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.MarqueeOn, "Import", Messages.START_POST_INSTALL_INSTRUCTIONS));
                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.ImportProgress, "Import", Messages.START_POST_INSTALL_INSTRUCTIONS));
                        HandleInstallSection(xenSession, vmRef, installSection[0]);
                    }
                    ShowSystem(xenSession, vmRef);
                }
                catch (Exception ex)
                {
                    if (ex is OperationCanceledException)
                        throw;
                    log.Error(Messages.ERROR_IMPORT_FAILED);
                    throw new Exception(Messages.ERROR_IMPORT_FAILED, ex);
                }
            }

            OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.MarqueeOff, "Import", ""));
            int _processId = System.Diagnostics.Process.GetCurrentProcess().Id;
            string _touchFile = Path.Combine(pathToOvf, "xen__" + _processId);
            //added check again as Delete needs write permissions and even if the file does not exist import will fail if the user has read only permissions
            if (File.Exists(_touchFile))
                File.Delete(_touchFile);

            OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.ImportThreadComplete, "Import", Messages.COMPLETED_IMPORT));
        }
Exemple #30
0
        public static bool IsThisIdEncrypted(EnvelopeType ovfObj, string id)
        {
            SecuritySection_Type[] security = FindSections<SecuritySection_Type>(ovfObj.Sections);

            if (security != null && security.Length > 0) // if no security section don't bother going any further.
            {
                foreach (SecuritySection_Type sst in security)
                {
                    foreach (Security_Type st in sst.Security)
                    {
                        foreach (XenOvf.Definitions.XENC.DataReference dataref in st.ReferenceList.Items)
                        {
                            if (dataref.ValueType != null && dataref.ValueType.Length > 0 &&
                                dataref.ValueType.Contains(id))
                            {
                                return true;  // no need to go anyfurther, nicer just to leave now.
                            }
                        }
                    }
                }
            }

            return false;  // get here... its not encrypted.
        }