示例#1
0
 private unsafe void GenerateStatus()
 {
     if (!this.statusGenerated)
     {
         if (!this.browseGranted)
         {
             new ServiceControllerPermission(ServiceControllerPermissionAccess.Browse, this.machineName, this.ServiceName).Demand();
             this.browseGranted = true;
         }
         IntPtr serviceHandle = this.GetServiceHandle(4);
         try
         {
             System.ServiceProcess.NativeMethods.SERVICE_STATUS pStatus = new System.ServiceProcess.NativeMethods.SERVICE_STATUS();
             if (!System.ServiceProcess.UnsafeNativeMethods.QueryServiceStatus(serviceHandle, &pStatus))
             {
                 throw CreateSafeWin32Exception();
             }
             this.commandsAccepted = pStatus.controlsAccepted;
             this.status           = (ServiceControllerStatus)pStatus.currentState;
             this.type             = pStatus.serviceType;
             this.statusGenerated  = true;
         }
         finally
         {
             SafeNativeMethods.CloseServiceHandle(serviceHandle);
         }
     }
 }
示例#2
0
        private static System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS_PROCESS[] GetServicesInGroup(string machineName, string group)
        {
            System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS_PROCESS[] enum_service_status_processArray;
            IntPtr zero         = IntPtr.Zero;
            IntPtr status       = IntPtr.Zero;
            int    resumeHandle = 0;

            try
            {
                int num;
                int num2;
                zero = GetDataBaseHandleWithEnumerateAccess(machineName);
                System.ServiceProcess.UnsafeNativeMethods.EnumServicesStatusEx(zero, 0, 0x30, 3, IntPtr.Zero, 0, out num, out num2, ref resumeHandle, group);
                status = Marshal.AllocHGlobal((IntPtr)num);
                System.ServiceProcess.UnsafeNativeMethods.EnumServicesStatusEx(zero, 0, 0x30, 3, status, num, out num, out num2, ref resumeHandle, group);
                int num4 = num2;
                enum_service_status_processArray = new System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS_PROCESS[num4];
                for (int i = 0; i < num4; i++)
                {
                    IntPtr ptr = (IntPtr)(((long)status) + (i * Marshal.SizeOf(typeof(System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS_PROCESS))));
                    System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS_PROCESS structure = new System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS_PROCESS();
                    Marshal.PtrToStructure(ptr, structure);
                    enum_service_status_processArray[i] = structure;
                }
            }
            finally
            {
                Marshal.FreeHGlobal(status);
                if (zero != IntPtr.Zero)
                {
                    SafeNativeMethods.CloseServiceHandle(zero);
                }
            }
            return(enum_service_status_processArray);
        }
示例#3
0
        public unsafe void Stop()
        {
            if (!this.controlGranted)
            {
                new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, this.machineName, this.ServiceName).Demand();
                this.controlGranted = true;
            }
            IntPtr serviceHandle = this.GetServiceHandle(0x20);

            try
            {
                for (int i = 0; i < this.DependentServices.Length; i++)
                {
                    ServiceController controller = this.DependentServices[i];
                    controller.Refresh();
                    if (controller.Status != ServiceControllerStatus.Stopped)
                    {
                        controller.Stop();
                        controller.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30));
                    }
                }
                System.ServiceProcess.NativeMethods.SERVICE_STATUS pStatus = new System.ServiceProcess.NativeMethods.SERVICE_STATUS();
                if (!System.ServiceProcess.UnsafeNativeMethods.ControlService(serviceHandle, 1, &pStatus))
                {
                    Exception innerException = CreateSafeWin32Exception();
                    throw new InvalidOperationException(Res.GetString("StopService", new object[] { this.ServiceName, this.MachineName }), innerException);
                }
            }
            finally
            {
                SafeNativeMethods.CloseServiceHandle(serviceHandle);
            }
        }
        /// <include file='doc\ServiceInstaller.uex' path='docs/doc[@for="ServiceInstaller.RemoveService"]/*' />
        /// <devdoc>
        /// Called by Rollback and Uninstall to remove the service.
        /// </devdoc>
        private void RemoveService()
        {
            // try to stop the service before uninstalling it.
            try {
                using (ServiceController svc = new ServiceController(ServiceName)) {
                    if (svc.Status != ServiceControllerStatus.Stopped)
                    {
                        Context.LogMessage(Res.GetString(Res.TryToStop, ServiceName));
                        svc.Stop();
                        int timeout = 10;
                        svc.Refresh();
                        while (svc.Status != ServiceControllerStatus.Stopped && timeout > 0)
                        {
                            Thread.Sleep(1000);
                            svc.Refresh();
                            timeout--;
                        }
                    }
                }
            }
            catch {
            }

            Context.LogMessage(Res.GetString(Res.ServiceRemoving, ServiceName));
            IntPtr serviceManagerHandle = SafeNativeMethods.OpenSCManager(null, null, NativeMethods.SC_MANAGER_ALL);

            if (serviceManagerHandle == IntPtr.Zero)
            {
                throw new Win32Exception();
            }

            IntPtr serviceHandle = IntPtr.Zero;

            try {
                serviceHandle = NativeMethods.OpenService(serviceManagerHandle,
                                                          ServiceName, NativeMethods.STANDARD_RIGHTS_DELETE);

                if (serviceHandle == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                NativeMethods.DeleteService(serviceHandle);
            }
            finally {
                if (serviceHandle != IntPtr.Zero)
                {
                    SafeNativeMethods.CloseServiceHandle(serviceHandle);
                }

                SafeNativeMethods.CloseServiceHandle(serviceManagerHandle);
            }
            Context.LogMessage(Res.GetString(Res.ServiceRemoved, ServiceName));
        }
示例#5
0
 public void Close()
 {
     if (this.serviceManagerHandle != IntPtr.Zero)
     {
         SafeNativeMethods.CloseServiceHandle(this.serviceManagerHandle);
     }
     this.serviceManagerHandle = IntPtr.Zero;
     this.statusGenerated      = false;
     this.type           = 0x13f;
     this.browseGranted  = false;
     this.controlGranted = false;
 }
示例#6
0
        private void RemoveService()
        {
            base.Context.LogMessage(Res.GetString("ServiceRemoving", this.ServiceName));
            IntPtr intPtr = SafeNativeMethods.OpenSCManager(null, null, 983103);

            if (intPtr == IntPtr.Zero)
            {
                throw new Win32Exception();
            }
            IntPtr intPtr2 = IntPtr.Zero;

            try
            {
                intPtr2 = NativeMethods.OpenService(intPtr, this.ServiceName, 65536);
                if (intPtr2 == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }
                NativeMethods.DeleteService(intPtr2);
            }
            finally
            {
                if (intPtr2 != IntPtr.Zero)
                {
                    SafeNativeMethods.CloseServiceHandle(intPtr2);
                }
                SafeNativeMethods.CloseServiceHandle(intPtr);
            }
            base.Context.LogMessage(Res.GetString("ServiceRemoved", this.ServiceName));
            try
            {
                using (ServiceController serviceController = new ServiceController(this.ServiceName))
                {
                    if (serviceController.Status != ServiceControllerStatus.Stopped)
                    {
                        base.Context.LogMessage(Res.GetString("TryToStop", this.ServiceName));
                        serviceController.Stop();
                        int num = 10;
                        serviceController.Refresh();
                        while (serviceController.Status != ServiceControllerStatus.Stopped && num > 0)
                        {
                            Thread.Sleep(1000);
                            serviceController.Refresh();
                            num--;
                        }
                    }
                }
            }
            catch
            {
            }
            Thread.Sleep(5000);
        }
        private void RemoveService()
        {
            base.Context.LogMessage(System.ServiceProcess.Res.GetString("ServiceRemoving", new object[] { this.ServiceName }));
            IntPtr databaseHandle = SafeNativeMethods.OpenSCManager(null, null, 0xf003f);

            if (databaseHandle == IntPtr.Zero)
            {
                throw new Win32Exception();
            }
            IntPtr zero = IntPtr.Zero;

            try
            {
                zero = System.ServiceProcess.NativeMethods.OpenService(databaseHandle, this.ServiceName, 0x10000);
                if (zero == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }
                System.ServiceProcess.NativeMethods.DeleteService(zero);
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    SafeNativeMethods.CloseServiceHandle(zero);
                }
                SafeNativeMethods.CloseServiceHandle(databaseHandle);
            }
            base.Context.LogMessage(System.ServiceProcess.Res.GetString("ServiceRemoved", new object[] { this.ServiceName }));
            try
            {
                using (ServiceController controller = new ServiceController(this.ServiceName))
                {
                    if (controller.Status != ServiceControllerStatus.Stopped)
                    {
                        base.Context.LogMessage(System.ServiceProcess.Res.GetString("TryToStop", new object[] { this.ServiceName }));
                        controller.Stop();
                        int num = 10;
                        controller.Refresh();
                        while ((controller.Status != ServiceControllerStatus.Stopped) && (num > 0))
                        {
                            Thread.Sleep(0x3e8);
                            controller.Refresh();
                            num--;
                        }
                    }
                }
            }
            catch
            {
            }
            Thread.Sleep(0x1388);
        }
示例#8
0
        private static ServiceController[] GetServicesOfType(string machineName, int serviceType)
        {
            ServiceController[] controllerArray;
            if (!SyntaxCheck.CheckMachineName(machineName))
            {
                throw new ArgumentException(Res.GetString("BadMachineName", new object[] { machineName }));
            }
            new ServiceControllerPermission(ServiceControllerPermissionAccess.Browse, machineName, "*").Demand();
            CheckEnvironment();
            IntPtr zero         = IntPtr.Zero;
            IntPtr status       = IntPtr.Zero;
            int    resumeHandle = 0;

            try
            {
                int num;
                int num2;
                zero = GetDataBaseHandleWithEnumerateAccess(machineName);
                System.ServiceProcess.UnsafeNativeMethods.EnumServicesStatus(zero, serviceType, 3, IntPtr.Zero, 0, out num, out num2, ref resumeHandle);
                status = Marshal.AllocHGlobal((IntPtr)num);
                System.ServiceProcess.UnsafeNativeMethods.EnumServicesStatus(zero, serviceType, 3, status, num, out num, out num2, ref resumeHandle);
                int num4 = num2;
                controllerArray = new ServiceController[num4];
                for (int i = 0; i < num4; i++)
                {
                    IntPtr ptr = (IntPtr)(((long)status) + (i * Marshal.SizeOf(typeof(System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS))));
                    System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS structure = new System.ServiceProcess.NativeMethods.ENUM_SERVICE_STATUS();
                    Marshal.PtrToStructure(ptr, structure);
                    controllerArray[i] = new ServiceController(machineName, structure);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(status);
                if (zero != IntPtr.Zero)
                {
                    SafeNativeMethods.CloseServiceHandle(zero);
                }
            }
            return(controllerArray);
        }
示例#9
0
        public unsafe void Pause()
        {
            if (!this.controlGranted)
            {
                new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, this.machineName, this.ServiceName).Demand();
                this.controlGranted = true;
            }
            IntPtr serviceHandle = this.GetServiceHandle(0x40);

            try
            {
                System.ServiceProcess.NativeMethods.SERVICE_STATUS pStatus = new System.ServiceProcess.NativeMethods.SERVICE_STATUS();
                if (!System.ServiceProcess.UnsafeNativeMethods.ControlService(serviceHandle, 2, &pStatus))
                {
                    Exception innerException = CreateSafeWin32Exception();
                    throw new InvalidOperationException(Res.GetString("PauseService", new object[] { this.ServiceName, this.MachineName }), innerException);
                }
            }
            finally
            {
                SafeNativeMethods.CloseServiceHandle(serviceHandle);
            }
        }
示例#10
0
        /// <summary>Installs the service by writing service application information to the registry. This method is meant to be used by installation tools, which process the appropriate methods automatically.</summary>
        /// <param name="stateSaver">An <see cref="T:System.Collections.IDictionary" /> that contains the context information associated with the installation. </param>
        /// <exception cref="T:System.InvalidOperationException">The installation does not contain a <see cref="T:System.ServiceProcess.ServiceProcessInstaller" /> for the executable.-or- The file name for the assembly is null or an empty string.-or- The service name is invalid.-or- The Service Control Manager could not be opened. </exception>
        /// <exception cref="T:System.ArgumentException">The display name for the service is more than 255 characters in length.</exception>
        /// <exception cref="T:System.ComponentModel.Win32Exception">The system could not generate a handle to the service. -or-A service with that name is already installed.</exception>
        /// <PermissionSet>
        ///   <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
        ///   <IPermission class="System.Security.Permissions.UIPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        /// </PermissionSet>
        public override void Install(IDictionary stateSaver)
        {
            base.Context.LogMessage(Res.GetString("InstallingService", this.ServiceName));
            try
            {
                ServiceInstaller.CheckEnvironment();
                string servicesStartName = null;
                string password          = null;
                ServiceProcessInstaller serviceProcessInstaller = null;
                if (base.Parent is ServiceProcessInstaller)
                {
                    serviceProcessInstaller = (ServiceProcessInstaller)base.Parent;
                }
                else
                {
                    int num = 0;
                    while (num < base.Parent.Installers.Count)
                    {
                        if (!(base.Parent.Installers[num] is ServiceProcessInstaller))
                        {
                            num++;
                            continue;
                        }
                        serviceProcessInstaller = (ServiceProcessInstaller)base.Parent.Installers[num];
                        break;
                    }
                }
                if (serviceProcessInstaller == null)
                {
                    throw new InvalidOperationException(Res.GetString("NoInstaller"));
                }
                switch (serviceProcessInstaller.Account)
                {
                case ServiceAccount.LocalService:
                    servicesStartName = "NT AUTHORITY\\LocalService";
                    break;

                case ServiceAccount.NetworkService:
                    servicesStartName = "NT AUTHORITY\\NetworkService";
                    break;

                case ServiceAccount.User:
                    servicesStartName = serviceProcessInstaller.Username;
                    password          = serviceProcessInstaller.Password;
                    break;
                }
                string text = base.Context.Parameters["assemblypath"];
                if (string.IsNullOrEmpty(text))
                {
                    throw new InvalidOperationException(Res.GetString("FileName"));
                }
                if (text.IndexOf('"') == -1)
                {
                    text = "\"" + text + "\"";
                }
                if (!ServiceInstaller.ValidateServiceName(this.ServiceName))
                {
                    throw new InvalidOperationException(Res.GetString("ServiceName", this.ServiceName, 80.ToString(CultureInfo.CurrentCulture)));
                }
                if (this.DisplayName.Length > 255)
                {
                    throw new ArgumentException(Res.GetString("DisplayNameTooLong", this.DisplayName));
                }
                string dependencies = null;
                if (this.ServicesDependedOn.Length != 0)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < this.ServicesDependedOn.Length; i++)
                    {
                        string text2 = this.ServicesDependedOn[i];
                        try
                        {
                            text2 = new ServiceController(text2, ".").ServiceName;
                        }
                        catch
                        {
                        }
                        stringBuilder.Append(text2);
                        stringBuilder.Append('\0');
                    }
                    stringBuilder.Append('\0');
                    dependencies = stringBuilder.ToString();
                }
                IntPtr intPtr  = SafeNativeMethods.OpenSCManager(null, null, 983103);
                IntPtr intPtr2 = IntPtr.Zero;
                if (intPtr == IntPtr.Zero)
                {
                    throw new InvalidOperationException(Res.GetString("OpenSC", "."), new Win32Exception());
                }
                int serviceType = 16;
                int num2        = 0;
                for (int j = 0; j < base.Parent.Installers.Count; j++)
                {
                    if (base.Parent.Installers[j] is ServiceInstaller)
                    {
                        num2++;
                        if (num2 > 1)
                        {
                            break;
                        }
                    }
                }
                if (num2 > 1)
                {
                    serviceType = 32;
                }
                try
                {
                    intPtr2 = NativeMethods.CreateService(intPtr, this.ServiceName, this.DisplayName, 983551, serviceType, (int)this.StartType, 1, text, null, IntPtr.Zero, dependencies, servicesStartName, password);
                    if (intPtr2 == IntPtr.Zero)
                    {
                        throw new Win32Exception();
                    }
                    if (this.Description.Length != 0)
                    {
                        NativeMethods.SERVICE_DESCRIPTION sERVICE_DESCRIPTION = default(NativeMethods.SERVICE_DESCRIPTION);
                        sERVICE_DESCRIPTION.description = Marshal.StringToHGlobalUni(this.Description);
                        bool num3 = NativeMethods.ChangeServiceConfig2(intPtr2, 1u, ref sERVICE_DESCRIPTION);
                        Marshal.FreeHGlobal(sERVICE_DESCRIPTION.description);
                        if (!num3)
                        {
                            throw new Win32Exception();
                        }
                    }
                    if (Environment.OSVersion.Version.Major > 5 && this.StartType == ServiceStartMode.Automatic)
                    {
                        NativeMethods.SERVICE_DELAYED_AUTOSTART_INFO sERVICE_DELAYED_AUTOSTART_INFO = default(NativeMethods.SERVICE_DELAYED_AUTOSTART_INFO);
                        sERVICE_DELAYED_AUTOSTART_INFO.fDelayedAutostart = this.DelayedAutoStart;
                        if (!NativeMethods.ChangeServiceConfig2(intPtr2, 3u, ref sERVICE_DELAYED_AUTOSTART_INFO))
                        {
                            throw new Win32Exception();
                        }
                    }
                    stateSaver["installed"] = true;
                }
                finally
                {
                    if (intPtr2 != IntPtr.Zero)
                    {
                        SafeNativeMethods.CloseServiceHandle(intPtr2);
                    }
                    SafeNativeMethods.CloseServiceHandle(intPtr);
                }
                base.Context.LogMessage(Res.GetString("InstallOK", this.ServiceName));
            }
            finally
            {
                base.Install(stateSaver);
            }
        }
        public override void Install(IDictionary stateSaver)
        {
            this.Context.LogMessage(System.ServiceProcess.Res.GetString("InstallingService", new object[1]
            {
                (object)this.ServiceName
            }));
            try
            {
                ServiceInstaller.CheckEnvironment();
                string servicesStartName = (string)null;
                string password          = (string)null;
                ServiceProcessInstaller processInstaller = (ServiceProcessInstaller)null;
                if (this.Parent is ServiceProcessInstaller)
                {
                    processInstaller = (ServiceProcessInstaller)this.Parent;
                }
                else
                {
                    for (int index = 0; index < this.Parent.Installers.Count; ++index)
                    {
                        if (this.Parent.Installers[index] is ServiceProcessInstaller)
                        {
                            processInstaller = (ServiceProcessInstaller)this.Parent.Installers[index];
                            break;
                        }
                    }
                }
                if (processInstaller == null)
                {
                    throw new InvalidOperationException(System.ServiceProcess.Res.GetString("NoInstaller"));
                }
                switch (processInstaller.Account)
                {
                case ServiceAccount.LocalService:
                    servicesStartName = "NT AUTHORITY\\LocalService";
                    break;

                case ServiceAccount.NetworkService:
                    servicesStartName = "NT AUTHORITY\\NetworkService";
                    break;

                case ServiceAccount.User:
                    servicesStartName = processInstaller.Username;
                    password          = processInstaller.Password;
                    break;
                }
                string binaryPath = this.Context.Parameters["assemblypath"];
                if (string.IsNullOrEmpty(binaryPath))
                {
                    throw new InvalidOperationException(System.ServiceProcess.Res.GetString("FileName"));
                }
                if (binaryPath.IndexOf('"') == -1)
                {
                    binaryPath = "\"" + binaryPath + "\"";
                }
                if (!ServiceInstaller.ValidateServiceName(this.ServiceName))
                {
                    throw new InvalidOperationException(System.ServiceProcess.Res.GetString("ServiceName", (object)this.ServiceName, (object)80.ToString((IFormatProvider)CultureInfo.CurrentCulture)));
                }
                else if (this.DisplayName.Length > (int)byte.MaxValue)
                {
                    throw new ArgumentException(System.ServiceProcess.Res.GetString("DisplayNameTooLong", new object[1]
                    {
                        (object)this.DisplayName
                    }));
                }
                else
                {
                    string dependencies = (string)null;
                    if (this.ServicesDependedOn.Length > 0)
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int index = 0; index < this.ServicesDependedOn.Length; ++index)
                        {
                            string name = this.ServicesDependedOn[index];
                            try
                            {
                                name = new ServiceController(name, ".").ServiceName;
                            }
                            catch
                            {
                            }
                            stringBuilder.Append(name);
                            stringBuilder.Append(char.MinValue);
                        }
                        stringBuilder.Append(char.MinValue);
                        dependencies = ((object)stringBuilder).ToString();
                    }
                    IntPtr num1 = SafeNativeMethods.OpenSCManager((string)null, (string)null, 983103);
                    IntPtr num2 = IntPtr.Zero;
                    if (num1 == IntPtr.Zero)
                    {
                        throw new InvalidOperationException(System.ServiceProcess.Res.GetString("OpenSC", new object[1]
                        {
                            (object)"."
                        }), (Exception) new Win32Exception());
                    }
                    else
                    {
                        int serviceType = 16;
                        int num3        = 0;
                        for (int index = 0; index < this.Parent.Installers.Count; ++index)
                        {
                            if (this.Parent.Installers[index] is ServiceInstaller)
                            {
                                ++num3;
                                if (num3 > 1)
                                {
                                    break;
                                }
                            }
                        }
                        if (num3 > 1)
                        {
                            serviceType = 32;
                        }
                        try
                        {
                            num2 = System.ServiceProcess.NativeMethods.CreateService(num1, this.ServiceName, this.DisplayName, 983551, serviceType, (int)this.StartType, 1, binaryPath, (string)null, IntPtr.Zero, dependencies, servicesStartName, password);
                            if (num2 == IntPtr.Zero)
                            {
                                throw new Win32Exception();
                            }
                            if (this.Description.Length != 0)
                            {
                                System.ServiceProcess.NativeMethods.SERVICE_DESCRIPTION serviceDesc = new System.ServiceProcess.NativeMethods.SERVICE_DESCRIPTION();
                                serviceDesc.description = Marshal.StringToHGlobalUni(this.Description);
                                bool flag = System.ServiceProcess.NativeMethods.ChangeServiceConfig2(num2, 1U, ref serviceDesc);
                                Marshal.FreeHGlobal(serviceDesc.description);
                                if (!flag)
                                {
                                    throw new Win32Exception();
                                }
                            }
                            if (Environment.OSVersion.Version.Major > 5 && this.StartType == ServiceStartMode.Automatic)
                            {
                                if (!System.ServiceProcess.NativeMethods.ChangeServiceConfig2(num2, 3U, ref new System.ServiceProcess.NativeMethods.SERVICE_DELAYED_AUTOSTART_INFO()
                                {
                                    fDelayedAutostart = this.DelayedAutoStart
                                }))
                                {
                                    throw new Win32Exception();
                                }
                            }
                            stateSaver[(object)"installed"] = (object)true;
                        }
                        finally
                        {
                            if (num2 != IntPtr.Zero)
                            {
                                SafeNativeMethods.CloseServiceHandle(num2);
                            }
                            SafeNativeMethods.CloseServiceHandle(num1);
                        }
                        this.Context.LogMessage(System.ServiceProcess.Res.GetString("InstallOK", new object[1]
                        {
                            (object)this.ServiceName
                        }));
                    }
                }
            }
            finally
            {
                base.Install(stateSaver);
            }
        }
示例#12
0
        public void Start(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (!this.controlGranted)
            {
                new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, this.machineName, this.ServiceName).Demand();
                this.controlGranted = true;
            }
            IntPtr serviceHandle = this.GetServiceHandle(0x10);

            try
            {
                IntPtr[] ptrArray = new IntPtr[args.Length];
                int      index    = 0;
                try
                {
                    index = 0;
                    while (index < args.Length)
                    {
                        if (args[index] == null)
                        {
                            throw new ArgumentNullException(Res.GetString("ArgsCantBeNull"), "args");
                        }
                        ptrArray[index] = Marshal.StringToHGlobalUni(args[index]);
                        index++;
                    }
                }
                catch
                {
                    for (int i = 0; i < index; i++)
                    {
                        Marshal.FreeHGlobal(ptrArray[index]);
                    }
                    throw;
                }
                GCHandle handle = new GCHandle();
                try
                {
                    handle = GCHandle.Alloc(ptrArray, GCHandleType.Pinned);
                    if (!System.ServiceProcess.UnsafeNativeMethods.StartService(serviceHandle, args.Length, handle.AddrOfPinnedObject()))
                    {
                        Exception innerException = CreateSafeWin32Exception();
                        throw new InvalidOperationException(Res.GetString("CannotStart", new object[] { this.ServiceName, this.MachineName }), innerException);
                    }
                }
                finally
                {
                    for (index = 0; index < args.Length; index++)
                    {
                        Marshal.FreeHGlobal(ptrArray[index]);
                    }
                    if (handle.IsAllocated)
                    {
                        handle.Free();
                    }
                }
            }
            finally
            {
                SafeNativeMethods.CloseServiceHandle(serviceHandle);
            }
        }
        private void RemoveService()
        {
            this.Context.LogMessage(System.ServiceProcess.Res.GetString("ServiceRemoving", new object[1]
            {
                (object)this.ServiceName
            }));
            IntPtr num1 = SafeNativeMethods.OpenSCManager((string)null, (string)null, 983103);

            if (num1 == IntPtr.Zero)
            {
                throw new Win32Exception();
            }
            IntPtr num2 = IntPtr.Zero;

            try
            {
                num2 = System.ServiceProcess.NativeMethods.OpenService(num1, this.ServiceName, 65536);
                if (num2 == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }
                System.ServiceProcess.NativeMethods.DeleteService(num2);
            }
            finally
            {
                if (num2 != IntPtr.Zero)
                {
                    SafeNativeMethods.CloseServiceHandle(num2);
                }
                SafeNativeMethods.CloseServiceHandle(num1);
            }
            this.Context.LogMessage(System.ServiceProcess.Res.GetString("ServiceRemoved", new object[1]
            {
                (object)this.ServiceName
            }));
            try
            {
                using (ServiceController serviceController = new ServiceController(this.ServiceName))
                {
                    if (serviceController.Status != ServiceControllerStatus.Stopped)
                    {
                        this.Context.LogMessage(System.ServiceProcess.Res.GetString("TryToStop", new object[1]
                        {
                            (object)this.ServiceName
                        }));
                        serviceController.Stop();
                        int num3 = 10;
                        serviceController.Refresh();
                        while (serviceController.Status != ServiceControllerStatus.Stopped)
                        {
                            if (num3 > 0)
                            {
                                Thread.Sleep(1000);
                                serviceController.Refresh();
                                --num3;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {
            }
            Thread.Sleep(5000);
        }
        /// <include file='doc\ServiceInstaller.uex' path='docs/doc[@for="ServiceInstaller.Install"]/*' />
        /// <devdoc>
        ///    <para>Installs the service by writing service application
        ///       information to the registry. This method is meant to be used by installation
        ///       tools, which process the appropriate methods automatically.</para>
        /// </devdoc>
        public unsafe override void Install(IDictionary stateSaver)
        {
            Context.LogMessage(Res.GetString(Res.InstallingService, ServiceName));
            try
            {
                CheckEnvironment();
                string userName = null;
                string password = null;
                // find the ServiceProcessInstaller for our process. It's either the
                // parent or one of our peers in the parent's Installers collection.
                ServiceProcessInstaller processInstaller = null;
                if (Parent is ServiceProcessInstaller)
                {
                    processInstaller = (ServiceProcessInstaller)Parent;
                }
                else
                {
                    for (int i = 0; i < Parent.Installers.Count; i++)
                    {
                        if (Parent.Installers[i] is ServiceProcessInstaller)
                        {
                            processInstaller = (ServiceProcessInstaller)Parent.Installers[i];
                            break;
                        }
                    }
                }

                if (processInstaller == null)
                {
                    throw new InvalidOperationException(Res.GetString(Res.NoInstaller));
                }

                switch (processInstaller.Account)
                {
                case ServiceAccount.LocalService:
                    userName = LocalServiceName;
                    break;

                case ServiceAccount.NetworkService:
                    userName = NetworkServiceName;
                    break;

                case ServiceAccount.User:
                    userName = processInstaller.Username;
                    password = processInstaller.Password;
                    break;
                }

                // check all our parameters

                string moduleFileName = Context.Parameters["assemblypath"];
                if (String.IsNullOrEmpty(moduleFileName))
                {
                    throw new InvalidOperationException(Res.GetString(Res.FileName));
                }

                // Put quotas around module file name. Otherwise a service might fail to start if there is space in the path.
                // Note: Though CreateService accepts a binaryPath allowing
                // arguments for automatic services, in /assemblypath=foo,
                // foo is simply the path to the executable.
                // Therefore, it is best to quote if there are no quotes,
                // and best to not quote if there are quotes.
                if (moduleFileName.IndexOf('\"') == -1)
                {
                    moduleFileName = "\"" + moduleFileName + "\"";
                }

                //Check service name
                if (!ValidateServiceName(ServiceName))
                {
                    //Event Log cannot be used here, since the service doesn't exist yet.
                    throw new InvalidOperationException(Res.GetString(Res.ServiceName, ServiceName, ServiceBase.MaxNameLength.ToString(CultureInfo.CurrentCulture)));
                }

                // Check DisplayName length.
                if (DisplayName.Length > 255)
                {
                    // MSDN suggests that 256 is the max length, but in
                    // fact anything over 255 causes problems.
                    throw new ArgumentException(Res.GetString(Res.DisplayNameTooLong, DisplayName));
                }

                //Build servicesDependedOn string
                string servicesDependedOn = null;
                if (ServicesDependedOn.Length > 0)
                {
                    StringBuilder buff = new StringBuilder();
                    for (int i = 0; i < ServicesDependedOn.Length; ++i)
                    {
                        // we have to build a list of the services' short names. But the user
                        // might have used long names in the ServicesDependedOn property. Try
                        // to use ServiceController's logic to get the short name.
                        string tempServiceName = ServicesDependedOn[i];
                        try
                        {
                            ServiceController svc = new ServiceController(tempServiceName, ".");
                            tempServiceName = svc.ServiceName;
                        }
                        catch
                        {
                        }
                        //The servicesDependedOn need to be separated by a null
                        buff.Append(tempServiceName);
                        buff.Append('\0');
                    }
                    // an extra null at the end indicates end of list.
                    buff.Append('\0');

                    servicesDependedOn = buff.ToString();
                }

                // Open the service manager
                IntPtr serviceManagerHandle = SafeNativeMethods.OpenSCManager(null, null, NativeMethods.SC_MANAGER_ALL);
                IntPtr serviceHandle        = IntPtr.Zero;
                if (serviceManagerHandle == IntPtr.Zero)
                {
                    throw new InvalidOperationException(Res.GetString(Res.OpenSC, "."), new Win32Exception());
                }

                int serviceType = NativeMethods.SERVICE_TYPE_WIN32_OWN_PROCESS;
                // count the number of UserNTServiceInstallers. More than one means we set the SHARE_PROCESS flag.
                int serviceInstallerCount = 0;
                for (int i = 0; i < Parent.Installers.Count; i++)
                {
                    if (Parent.Installers[i] is ServiceInstaller)
                    {
                        serviceInstallerCount++;
                        if (serviceInstallerCount > 1)
                        {
                            break;
                        }
                    }
                }
                if (serviceInstallerCount > 1)
                {
                    serviceType = NativeMethods.SERVICE_TYPE_WIN32_SHARE_PROCESS;
                }

                try
                {
                    // Install the service
                    serviceHandle = NativeMethods.CreateService(serviceManagerHandle, ServiceName,
                                                                DisplayName, NativeMethods.ACCESS_TYPE_ALL, serviceType,
                                                                (int)StartType, NativeMethods.ERROR_CONTROL_NORMAL,
                                                                moduleFileName, null, IntPtr.Zero, servicesDependedOn, userName, password);

                    if (serviceHandle == IntPtr.Zero)
                    {
                        throw new Win32Exception();
                    }

                    // A local variable in an unsafe method is already fixed -- so we don't need a "fixed { }" blocks to protect
                    // across the p/invoke calls below.

                    if (Description.Length != 0)
                    {
                        NativeMethods.SERVICE_DESCRIPTION serviceDesc = new NativeMethods.SERVICE_DESCRIPTION();
                        serviceDesc.description = Marshal.StringToHGlobalUni(Description);
                        bool success = NativeMethods.ChangeServiceConfig2(serviceHandle, NativeMethods.SERVICE_CONFIG_DESCRIPTION, ref serviceDesc);
                        Marshal.FreeHGlobal(serviceDesc.description);
                        if (!success)
                        {
                            throw new Win32Exception();
                        }
                    }

                    if (Environment.OSVersion.Version.Major > 5)
                    {
                        if (StartType == ServiceStartMode.Automatic)
                        {
                            NativeMethods.SERVICE_DELAYED_AUTOSTART_INFO serviceDelayedInfo = new NativeMethods.SERVICE_DELAYED_AUTOSTART_INFO();
                            serviceDelayedInfo.fDelayedAutostart = DelayedAutoStart;
                            bool success = NativeMethods.ChangeServiceConfig2(serviceHandle, NativeMethods.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, ref serviceDelayedInfo);
                            if (!success)
                            {
                                throw new Win32Exception();
                            }
                        }
                    }

                    stateSaver["installed"] = true;
                }
                finally
                {
                    if (serviceHandle != IntPtr.Zero)
                    {
                        SafeNativeMethods.CloseServiceHandle(serviceHandle);
                    }

                    SafeNativeMethods.CloseServiceHandle(serviceManagerHandle);
                }
                Context.LogMessage(Res.GetString(Res.InstallOK, ServiceName));
            }
            finally
            {
                base.Install(stateSaver);
            }
        }
        public override void Install(IDictionary stateSaver)
        {
            base.Context.LogMessage(System.ServiceProcess.Res.GetString("InstallingService", new object[] { this.ServiceName }));
            try
            {
                CheckEnvironment();
                string servicesStartName       = null;
                string password                = null;
                ServiceProcessInstaller parent = null;
                if (base.Parent is ServiceProcessInstaller)
                {
                    parent = (ServiceProcessInstaller)base.Parent;
                }
                else
                {
                    for (int j = 0; j < base.Parent.Installers.Count; j++)
                    {
                        if (base.Parent.Installers[j] is ServiceProcessInstaller)
                        {
                            parent = (ServiceProcessInstaller)base.Parent.Installers[j];
                            break;
                        }
                    }
                }
                if (parent == null)
                {
                    throw new InvalidOperationException(System.ServiceProcess.Res.GetString("NoInstaller"));
                }
                switch (parent.Account)
                {
                case ServiceAccount.LocalService:
                    servicesStartName = @"NT AUTHORITY\LocalService";
                    break;

                case ServiceAccount.NetworkService:
                    servicesStartName = @"NT AUTHORITY\NetworkService";
                    break;

                case ServiceAccount.User:
                    servicesStartName = parent.Username;
                    password          = parent.Password;
                    break;
                }
                string str3 = base.Context.Parameters["assemblypath"];
                if (string.IsNullOrEmpty(str3))
                {
                    throw new InvalidOperationException(System.ServiceProcess.Res.GetString("FileName"));
                }
                if (str3.IndexOf('"') == -1)
                {
                    str3 = "\"" + str3 + "\"";
                }
                if (!ValidateServiceName(this.ServiceName))
                {
                    object[] args = new object[] { this.ServiceName, 80.ToString(CultureInfo.CurrentCulture) };
                    throw new InvalidOperationException(System.ServiceProcess.Res.GetString("ServiceName", args));
                }
                if (this.DisplayName.Length > 0xff)
                {
                    throw new ArgumentException(System.ServiceProcess.Res.GetString("DisplayNameTooLong", new object[] { this.DisplayName }));
                }
                string dependencies = null;
                if (this.ServicesDependedOn.Length > 0)
                {
                    StringBuilder builder = new StringBuilder();
                    for (int k = 0; k < this.ServicesDependedOn.Length; k++)
                    {
                        string name = this.ServicesDependedOn[k];
                        try
                        {
                            ServiceController controller = new ServiceController(name, ".");
                            name = controller.ServiceName;
                        }
                        catch
                        {
                        }
                        builder.Append(name);
                        builder.Append('\0');
                    }
                    builder.Append('\0');
                    dependencies = builder.ToString();
                }
                IntPtr databaseHandle = SafeNativeMethods.OpenSCManager(null, null, 0xf003f);
                IntPtr zero           = IntPtr.Zero;
                if (databaseHandle == IntPtr.Zero)
                {
                    throw new InvalidOperationException(System.ServiceProcess.Res.GetString("OpenSC", new object[] { "." }), new Win32Exception());
                }
                int serviceType = 0x10;
                int num4        = 0;
                for (int i = 0; i < base.Parent.Installers.Count; i++)
                {
                    if (base.Parent.Installers[i] is ServiceInstaller)
                    {
                        num4++;
                        if (num4 > 1)
                        {
                            break;
                        }
                    }
                }
                if (num4 > 1)
                {
                    serviceType = 0x20;
                }
                try
                {
                    zero = System.ServiceProcess.NativeMethods.CreateService(databaseHandle, this.ServiceName, this.DisplayName, 0xf01ff, serviceType, (int)this.StartType, 1, str3, null, IntPtr.Zero, dependencies, servicesStartName, password);
                    if (zero == IntPtr.Zero)
                    {
                        throw new Win32Exception();
                    }
                    if (this.Description.Length != 0)
                    {
                        System.ServiceProcess.NativeMethods.SERVICE_DESCRIPTION serviceDesc = new System.ServiceProcess.NativeMethods.SERVICE_DESCRIPTION {
                            description = Marshal.StringToHGlobalUni(this.Description)
                        };
                        bool flag = System.ServiceProcess.NativeMethods.ChangeServiceConfig2(zero, 1, ref serviceDesc);
                        Marshal.FreeHGlobal(serviceDesc.description);
                        if (!flag)
                        {
                            throw new Win32Exception();
                        }
                    }
                    if ((Environment.OSVersion.Version.Major > 5) && (this.StartType == ServiceStartMode.Automatic))
                    {
                        System.ServiceProcess.NativeMethods.SERVICE_DELAYED_AUTOSTART_INFO service_delayed_autostart_info = new System.ServiceProcess.NativeMethods.SERVICE_DELAYED_AUTOSTART_INFO {
                            fDelayedAutostart = this.DelayedAutoStart
                        };
                        if (!System.ServiceProcess.NativeMethods.ChangeServiceConfig2(zero, 3, ref service_delayed_autostart_info))
                        {
                            throw new Win32Exception();
                        }
                    }
                    stateSaver["installed"] = true;
                }
                finally
                {
                    if (zero != IntPtr.Zero)
                    {
                        SafeNativeMethods.CloseServiceHandle(zero);
                    }
                    SafeNativeMethods.CloseServiceHandle(databaseHandle);
                }
                base.Context.LogMessage(System.ServiceProcess.Res.GetString("InstallOK", new object[] { this.ServiceName }));
            }
            finally
            {
                base.Install(stateSaver);
            }
        }
        /// <include file='doc\ServiceInstaller.uex' path='docs/doc[@for="ServiceInstaller.RemoveService"]/*' />
        /// <devdoc>
        /// Called by Rollback and Uninstall to remove the service.
        /// </devdoc>
        private void RemoveService()
        {
            //
            // SCUM deletes a service when the Service is stopped and there is no open handle to the Service.
            // Service will be deleted asynchrously, so it takes a while for the deletion to be complete.
            // The recoommended way to delete a Service is:
            // (a)  DeleteService/closehandle,
            // (b) Stop service & wait until it is stopped & close handle
            // (c)  Wait for 5-10 secs for the async deletion to go through.
            //
            Context.LogMessage(Res.GetString(Res.ServiceRemoving, ServiceName));
            IntPtr serviceManagerHandle = SafeNativeMethods.OpenSCManager(null, null, NativeMethods.SC_MANAGER_ALL);

            if (serviceManagerHandle == IntPtr.Zero)
            {
                throw new Win32Exception();
            }

            IntPtr serviceHandle = IntPtr.Zero;

            try
            {
                serviceHandle = NativeMethods.OpenService(serviceManagerHandle,
                                                          ServiceName, NativeMethods.STANDARD_RIGHTS_DELETE);

                if (serviceHandle == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                NativeMethods.DeleteService(serviceHandle);
            }
            finally
            {
                if (serviceHandle != IntPtr.Zero)
                {
                    SafeNativeMethods.CloseServiceHandle(serviceHandle);
                }

                SafeNativeMethods.CloseServiceHandle(serviceManagerHandle);
            }
            Context.LogMessage(Res.GetString(Res.ServiceRemoved, ServiceName));

            // Stop the service
            try
            {
                using (ServiceController svc = new ServiceController(ServiceName))
                {
                    if (svc.Status != ServiceControllerStatus.Stopped)
                    {
                        Context.LogMessage(Res.GetString(Res.TryToStop, ServiceName));
                        svc.Stop();
                        int timeout = 10;
                        svc.Refresh();
                        while (svc.Status != ServiceControllerStatus.Stopped && timeout > 0)
                        {
                            Thread.Sleep(1000);
                            svc.Refresh();
                            timeout--;
                        }
                    }
                }
            }
            catch
            {
            }

            Thread.Sleep(5000);
        }
        /// <include file='doc\ServiceInstaller.uex' path='docs/doc[@for="ServiceInstaller.Install"]/*' />
        /// <devdoc>
        ///    <para>Installs the service by writing service application
        ///       information to the registry. This method is meant to be used by installation
        ///       tools, which process the appropriate methods automatically.</para>
        /// </devdoc>
        public override void Install(IDictionary stateSaver)
        {
            Context.LogMessage(Res.GetString(Res.InstallingService, ServiceName));
            try {
                CheckEnvironment();
                string userName = null;
                string password = null;
                // find the ServiceProcessInstaller for our process. It's either the
                // parent or one of our peers in the parent's Installers collection.
                ServiceProcessInstaller processInstaller = null;
                if (Parent is ServiceProcessInstaller)
                {
                    processInstaller = (ServiceProcessInstaller)Parent;
                }
                else
                {
                    for (int i = 0; i < Parent.Installers.Count; i++)
                    {
                        if (Parent.Installers[i] is ServiceProcessInstaller)
                        {
                            processInstaller = (ServiceProcessInstaller)Parent.Installers[i];
                            break;
                        }
                    }
                }

                if (processInstaller == null)
                {
                    throw new InvalidOperationException(Res.GetString(Res.NoInstaller));
                }

                switch (processInstaller.Account)
                {
                case ServiceAccount.LocalService:
                    userName = LocalServiceName;
                    break;

                case ServiceAccount.NetworkService:
                    userName = NetworkServiceName;
                    break;

                case ServiceAccount.User:
                    userName = processInstaller.Username;
                    password = processInstaller.Password;
                    break;
                }

                // check all our parameters

                string moduleFileName = Context.Parameters["assemblypath"];
                if (moduleFileName == null || moduleFileName.Length == 0)
                {
                    throw new InvalidOperationException(Res.GetString(Res.FileName));
                }

                //Check service name
                if (!ValidateServiceName(ServiceName))
                {
                    //Event Log cannot be used here, since the service doesn't exist yet.
                    throw new InvalidOperationException(Res.GetString(Res.ServiceName, ServiceName, ServiceBase.MaxNameLength.ToString()));
                }

                // Check DisplayName length.
                if (DisplayName.Length > 255)
                {
                    // MSDN suggests that 256 is the max length, but in
                    // fact anything over 255 causes problems.
                    throw new ArgumentException(Res.GetString(Res.DisplayNameTooLong, DisplayName));
                }

                //Build servicesDependedOn string
                string servicesDependedOn = null;
                if (ServicesDependedOn.Length > 0)
                {
                    StringBuilder buff = new StringBuilder();
                    for (int i = 0; i < ServicesDependedOn.Length; ++i)
                    {
                        // we have to build a list of the services' short names. But the user
                        // might have used long names in the ServicesDependedOn property. Try
                        // to use ServiceController's logic to get the short name.
                        string tempServiceName = ServicesDependedOn[i];
                        try {
                            ServiceController svc = new ServiceController(tempServiceName, ".");
                            tempServiceName = svc.ServiceName;
                        }
                        catch {
                        }
                        //The servicesDependedOn need to be separated by a null
                        buff.Append(tempServiceName);
                        buff.Append('\0');
                    }
                    // an extra null at the end indicates end of list.
                    buff.Append('\0');

                    servicesDependedOn = buff.ToString();
                }

                // Open the service manager
                IntPtr serviceManagerHandle = SafeNativeMethods.OpenSCManager(null, null, NativeMethods.SC_MANAGER_ALL);
                IntPtr serviceHandle        = IntPtr.Zero;
                if (serviceManagerHandle == IntPtr.Zero)
                {
                    throw new InvalidOperationException(Res.GetString(Res.OpenSC, "."), new Win32Exception());
                }

                int serviceType = NativeMethods.SERVICE_TYPE_WIN32_OWN_PROCESS;
                // count the number of UserNTServiceInstallers. More than one means we set the SHARE_PROCESS flag.
                int serviceInstallerCount = 0;
                for (int i = 0; i < Parent.Installers.Count; i++)
                {
                    if (Parent.Installers[i] is ServiceInstaller)
                    {
                        serviceInstallerCount++;
                        if (serviceInstallerCount > 1)
                        {
                            break;
                        }
                    }
                }
                if (serviceInstallerCount > 1)
                {
                    serviceType = NativeMethods.SERVICE_TYPE_WIN32_SHARE_PROCESS;
                }

                try {
                    // Install the service
                    serviceHandle = NativeMethods.CreateService(serviceManagerHandle, ServiceName,
                                                                DisplayName, NativeMethods.ACCESS_TYPE_ALL, serviceType,
                                                                (int)StartType, NativeMethods.ERROR_CONTROL_NORMAL,
                                                                moduleFileName, null, IntPtr.Zero, servicesDependedOn, userName, password);

                    if (serviceHandle == IntPtr.Zero)
                    {
                        throw new Win32Exception();
                    }

                    stateSaver["installed"] = true;
                }
                finally {
                    if (serviceHandle != IntPtr.Zero)
                    {
                        SafeNativeMethods.CloseServiceHandle(serviceHandle);
                    }

                    SafeNativeMethods.CloseServiceHandle(serviceManagerHandle);
                }
                Context.LogMessage(Res.GetString(Res.InstallOK, ServiceName));
            }
            finally {
                base.Install(stateSaver);
            }
        }