<commit_before>﻿/* Copyright (c) Citrix Systems Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, 
 * with or without modification, are permitted provided 
 * that the following conditions are met:
 *
 * *   Redistributions of source code must retain the above 
 *     copyright notice, this list of conditions and the 
 *     following disclaimer.
 * *   Redistributions in binary form must reproduce the above 
 *     copyright notice, this list of conditions and the 
 *     following disclaimer in the documentation and/or other 
 *     materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Management;
using System.Windows.Forms;
using Microsoft.Win32;
using Microsoft.VisualBasic;
using System.Configuration.Install;
using System.Reflection;
using XenGuestLib;

[assembly:AssemblyVersion(XenVersions.Version)]
[assembly:AssemblyFileVersion(XenVersions.Version)]
[assembly:AssemblyCompanyAttribute(XenVersions.BRANDING_manufacturerLong)]
[assembly:AssemblyProductAttribute(XenVersions.BRANDING_toolsForVMs)]
[assembly:AssemblyDescriptionAttribute(XenVersions.BRANDING_guestAgentLong)]
[assembly:AssemblyTitleAttribute(XenVersions.BRANDING_guestAgentLong)]
[assembly:AssemblyCopyrightAttribute(XenVersions.BRANDING_copyrightGuestAgent)]


namespace xenwinsvc
{
    class TimeDateTraceListener : Microsoft.VisualBasic.Logging.FileLogTraceListener
    {
        public TimeDateTraceListener(String name)
            : base(name)
        {
            Debug.Print("TD Trace");
            base.Append = true;
            base.AutoFlush = true;
            base.MaxFileSize = 1024 * 1024;
            base.LogFileCreationSchedule = Microsoft.VisualBasic.Logging.LogFileCreationScheduleOption.Daily;
            base.Location = Microsoft.VisualBasic.Logging.LogFileLocation.Custom;
            System.IO.Directory.CreateDirectory(Application.CommonAppDataPath);
            base.CustomLocation = Application.CommonAppDataPath;
            Debug.Print("Log location " + base.CustomLocation);

        }

        public override void WriteLine(object o)
        {
            base.WriteLine(DateTime.Now.ToString() +" : " + o.ToString());
        }
        public override void WriteLine(string message)
        {
            base.WriteLine(DateTime.Now.ToString() +" : " + message);
        }
    }
        
       /* protected override void OnStart(string[] args)
        {
            // Start thread - so we can do everything in the background
            TextWriterTraceListener tlog = new TimeDateTraceListener(Application.CommonAppDataPath + "\\GuestData.log", "GuestData");
            Trace.Listeners.Add(tlog);
            Trace.AutoFlush = true;
            Trace.WriteLine("OnStart");  
            InstallState = new InstallerState();
            installthread = new Thread(InstallThreadHandler);
            installthread.Start();
            
        }*/

    class XenService : System.ServiceProcess.ServiceBase, IExceptionHandler
    {

        TimeDateTraceListener tlog;
        public XenService()
        {
     
            Debug.Print("GuestAgent Init");
            tlog = new TimeDateTraceListener("guest");
            Trace.Listeners.Add(tlog); Trace.WriteLine("This is all");
            this.ServiceName = Branding.Instance.getString("BRANDING_guestAgent");
            this.CanStop = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanHandlePowerEvent = true;
            this.AutoLog = true;
            servicestatelock = new object();
            Debug.Print("GuestAgent Init Done");
        }


        ManualResetEvent needsShutdown;
        Thread ServiceThread = null;
        WmiSession wmisession;


        uint cntr = 0;
        bool timeToRefresh()
        {
            if ((cntr % 26) == 0)
            {
                return true;
            }
            else
            {
                cntr++;
                return false;
            }
        }
        void resetTimeToRefresh()
        {
            cntr = 1;
        }

        void handleUnsuspended(object nothing, EventArrivedEventArgs args)
        {
            try
            {
                Refresher.RefreshAll(true);
            }
            catch (Exception e)
            {
                HandleException("Resume from suspend", e);
            }
        }        

        void ServiceThreadHandler()
        {
            try {
                Debug.Print("ServiceThreadHandler");
                needsShutdown.Reset();

                NetInfo.StoreChangedNetworkSettings();

                WmiBase.Reset();
                Debug.Print("WMI Check");
                if (WmiBase.Check())
                {
                    starting = true;
                    WmiCapableServiceThreadHandler();
                    starting = false;
                    running = true;
                }
                else
                {
                    running = false;
                    WaitHandle[] waitHandles = new WaitHandle[] 
                    {
                         (new WmiIncapableThread()).Incapable,
                         needsShutdown
                    };
                   
                    Debug.Print("Waiting for WMI capability to begin");
                    try
                    {
                        EventLog.WriteEntry(Branding.Instance.getString("BRANDING_errNoWMI"));
                    }
                    catch { };

                    int activehandle =WaitHandle.WaitAny(waitHandles);
                    Debug.Print("Received event");
       
                    if (activehandle == 0 ) {
                        try
                        {
                            EventLog.WriteEntry(Branding.Instance.getString("BRANDING_errNoWMI"));
                        }
                        catch { };
                        starting = true;
                        WmiCapableServiceThreadHandler();
                        starting = false;
                        running = true;
                    }
                }
            }
            catch (Exception e) {
                HandleException("Main Service Thread", e);
            }
        }

        class WmiIncapableThread {
            System.Threading.Timer timer;
            public WmiIncapableThread() {
                Incapable = new ManualResetEvent(false);
                timer = new System.Threading.Timer(WmiIncapableServiceThreadHandler, null, 4500, 4500);
            }
            public ManualResetEvent Incapable; 
            void WmiIncapableServiceThreadHandler(object nothing)
            {
                try {
                    WmiBase.Reset();
                    if (WmiBase.Check())
                    {
                        timer.Dispose();
                        Incapable.Set();
                    }
                }
                catch {
                     timer.Dispose();
                     Incapable.Set();
                }
            }

        }

        void RunProcess(string name, string arg, string comment)
        {
            try
            {

                Process myProcess = new Process();
                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.FileName = name;
                myProcess.StartInfo.Arguments = arg;
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.Start();
                myProcess.WaitForExit(5000);
            }
            catch (Exception e)
            {
                wmisession.Log("Process: unable to "+comment+"\n" + e.ToString());
            }
        }

        void WmiCapableServiceThreadHandler() 
        {
            try
            {
                wmisession = WmiBase.Singleton.GetXenStoreSession("Features");

                wmisession.Log("Guest Agent Starting");
                Refresher.Add(new PVInstallation(this));
               
                wmisession.Log("About to run apps");

                RunProcess("wmiadap","/f","refresh WMI ADAP");
                RunProcess("diskperf", "-y","enable disk perf counters");

                
                wmisession.Log("About to run features");
                new FeatureLicensed(this);
                new FeatureVSSLicensed(this);
                new FeatureDumpLog(this);
                new FeatureGC(this);
                new FeaturePing(this);
                new FeatureDomainJoin(this);
                new FeatureSetComputerName(this);
                new FeatureXSBatchCommand(this);
                new FeatureAutoUpdate(this);

                wmisession.Log("About to try snapshot");
                if (FeatureSnapshot.IsSnapshotSupported())
                {
                    Refresher.Add(new FeatureSnapshot(this));
                }
                else
                {
                    wmisession.Log("Snapshot not supported on this platform");
                    FeatureSnapshot.removeSnapshot(wmisession);
                }
                new FeatureTerminalServicesReset(this);
                new FeatureTerminalServices(this);
                //new FeatureStaticIpSetting(this);
                wmisession.Log("About to add refreshers");
                
                Refresher.Add(new NetInfo(this));
                Refresher.Add(new VolumeInfo());
                Refresher.Add(new MemoryInfo());<commit_msg>Revert "Revert "Revert "CA-205586 : Turn off FeatureStaticIpSetting"""<commit_after>﻿/* Copyright (c) Citrix Systems Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, 
 * with or without modification, are permitted provided 
 * that the following conditions are met:
 *
 * *   Redistributions of source code must retain the above 
 *     copyright notice, this list of conditions and the 
 *     following disclaimer.
 * *   Redistributions in binary form must reproduce the above 
 *     copyright notice, this list of conditions and the 
 *     following disclaimer in the documentation and/or other 
 *     materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Management;
using System.Windows.Forms;
using Microsoft.Win32;
using Microsoft.VisualBasic;
using System.Configuration.Install;
using System.Reflection;
using XenGuestLib;

[assembly:AssemblyVersion(XenVersions.Version)]
[assembly:AssemblyFileVersion(XenVersions.Version)]
[assembly:AssemblyCompanyAttribute(XenVersions.BRANDING_manufacturerLong)]
[assembly:AssemblyProductAttribute(XenVersions.BRANDING_toolsForVMs)]
[assembly:AssemblyDescriptionAttribute(XenVersions.BRANDING_guestAgentLong)]
[assembly:AssemblyTitleAttribute(XenVersions.BRANDING_guestAgentLong)]
[assembly:AssemblyCopyrightAttribute(XenVersions.BRANDING_copyrightGuestAgent)]


namespace xenwinsvc
{
    class TimeDateTraceListener : Microsoft.VisualBasic.Logging.FileLogTraceListener
    {
        public TimeDateTraceListener(String name)
            : base(name)
        {
            Debug.Print("TD Trace");
            base.Append = true;
            base.AutoFlush = true;
            base.MaxFileSize = 1024 * 1024;
            base.LogFileCreationSchedule = Microsoft.VisualBasic.Logging.LogFileCreationScheduleOption.Daily;
            base.Location = Microsoft.VisualBasic.Logging.LogFileLocation.Custom;
            System.IO.Directory.CreateDirectory(Application.CommonAppDataPath);
            base.CustomLocation = Application.CommonAppDataPath;
            Debug.Print("Log location " + base.CustomLocation);

        }

        public override void WriteLine(object o)
        {
            base.WriteLine(DateTime.Now.ToString() +" : " + o.ToString());
        }
        public override void WriteLine(string message)
        {
            base.WriteLine(DateTime.Now.ToString() +" : " + message);
        }
    }
        
       /* protected override void OnStart(string[] args)
        {
            // Start thread - so we can do everything in the background
            TextWriterTraceListener tlog = new TimeDateTraceListener(Application.CommonAppDataPath + "\\GuestData.log", "GuestData");
            Trace.Listeners.Add(tlog);
            Trace.AutoFlush = true;
            Trace.WriteLine("OnStart");  
            InstallState = new InstallerState();
            installthread = new Thread(InstallThreadHandler);
            installthread.Start();
            
        }*/

    class XenService : System.ServiceProcess.ServiceBase, IExceptionHandler
    {

        TimeDateTraceListener tlog;
        public XenService()
        {
     
            Debug.Print("GuestAgent Init");
            tlog = new TimeDateTraceListener("guest");
            Trace.Listeners.Add(tlog); Trace.WriteLine("This is all");
            this.ServiceName = Branding.Instance.getString("BRANDING_guestAgent");
            this.CanStop = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanHandlePowerEvent = true;
            this.AutoLog = true;
            servicestatelock = new object();
            Debug.Print("GuestAgent Init Done");
        }


        ManualResetEvent needsShutdown;
        Thread ServiceThread = null;
        WmiSession wmisession;


        uint cntr = 0;
        bool timeToRefresh()
        {
            if ((cntr % 26) == 0)
            {
                return true;
            }
            else
            {
                cntr++;
                return false;
            }
        }
        void resetTimeToRefresh()
        {
            cntr = 1;
        }

        void handleUnsuspended(object nothing, EventArrivedEventArgs args)
        {
            try
            {
                Refresher.RefreshAll(true);
            }
            catch (Exception e)
            {
                HandleException("Resume from suspend", e);
            }
        }        

        void ServiceThreadHandler()
        {
            try {
                Debug.Print("ServiceThreadHandler");
                needsShutdown.Reset();

                NetInfo.StoreChangedNetworkSettings();

                WmiBase.Reset();
                Debug.Print("WMI Check");
                if (WmiBase.Check())
                {
                    starting = true;
                    WmiCapableServiceThreadHandler();
                    starting = false;
                    running = true;
                }
                else
                {
                    running = false;
                    WaitHandle[] waitHandles = new WaitHandle[] 
                    {
                         (new WmiIncapableThread()).Incapable,
                         needsShutdown
                    };
                   
                    Debug.Print("Waiting for WMI capability to begin");
                    try
                    {
                        EventLog.WriteEntry(Branding.Instance.getString("BRANDING_errNoWMI"));
                    }
                    catch { };

                    int activehandle =WaitHandle.WaitAny(waitHandles);
                    Debug.Print("Received event");
       
                    if (activehandle == 0 ) {
                        try
                        {
                            EventLog.WriteEntry(Branding.Instance.getString("BRANDING_errNoWMI"));
                        }
                        catch { };
                        starting = true;
                        WmiCapableServiceThreadHandler();
                        starting = false;
                        running = true;
                    }
                }
            }
            catch (Exception e) {
                HandleException("Main Service Thread", e);
            }
        }

        class WmiIncapableThread {
            System.Threading.Timer timer;
            public WmiIncapableThread() {
                Incapable = new ManualResetEvent(false);
                timer = new System.Threading.Timer(WmiIncapableServiceThreadHandler, null, 4500, 4500);
            }
            public ManualResetEvent Incapable; 
            void WmiIncapableServiceThreadHandler(object nothing)
            {
                try {
                    WmiBase.Reset();
                    if (WmiBase.Check())
                    {
                        timer.Dispose();
                        Incapable.Set();
                    }
                }
                catch {
                     timer.Dispose();
                     Incapable.Set();
                }
            }

        }

        void RunProcess(string name, string arg, string comment)
        {
            try
            {

                Process myProcess = new Process();
                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.FileName = name;
                myProcess.StartInfo.Arguments = arg;
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.Start();
                myProcess.WaitForExit(5000);
            }
            catch (Exception e)
            {
                wmisession.Log("Process: unable to "+comment+"\n" + e.ToString());
            }
        }

        void WmiCapableServiceThreadHandler() 
        {
            try
            {
                wmisession = WmiBase.Singleton.GetXenStoreSession("Features");

                wmisession.Log("Guest Agent Starting");
                Refresher.Add(new PVInstallation(this));
               
                wmisession.Log("About to run apps");

                RunProcess("wmiadap","/f","refresh WMI ADAP");
                RunProcess("diskperf", "-y","enable disk perf counters");

                
                wmisession.Log("About to run features");
                new FeatureLicensed(this);
                new FeatureVSSLicensed(this);
                new FeatureDumpLog(this);
                new FeatureGC(this);
                new FeaturePing(this);
                new FeatureDomainJoin(this);
                new FeatureSetComputerName(this);
                new FeatureXSBatchCommand(this);
                new FeatureAutoUpdate(this);

                wmisession.Log("About to try snapshot");
                if (FeatureSnapshot.IsSnapshotSupported())
                {
                    Refresher.Add(new FeatureSnapshot(this));
                }
                else
                {
                    wmisession.Log("Snapshot not supported on this platform");
                    FeatureSnapshot.removeSnapshot(wmisession);
                }
                new FeatureTerminalServicesReset(this);
                new FeatureTerminalServices(this);
                new FeatureStaticIpSetting(this);
                wmisession.Log("About to add refreshers");
                
                Refresher.Add(new NetInfo(this));
                Refresher.Add(new VolumeInfo());
                Refresher.Add(new MemoryInfo());
{'fraction_non_alphanumeric': 0.07896390083603151, 'fraction_numerical': 0.0029961822838641084, 'mean_word_length': 1.5793344135610121, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2207884', 'n_tokens_mistral': 5217, 'n_tokens_neox': 4709, 'n_words': 1137}