Example #1
0
		internal static int CreateClassEnumWmi(string strSuperclass, int lFlags, IWbemContext pCtx, out IEnumWbemClassObject ppEnum, int impLevel, int authnLevel, IWbemServices pCurrentNamespace, string strUser, IntPtr strPassword, string strAuthority)
		{
			var svc = pCurrentNamespace as UnixWbemServices;
			var items = WMIDatabaseFactory.Get (svc.CurrentNamespace, "SELECT * FROM " + strSuperclass);
			ppEnum = new UnixEnumWbemClassObject(items);
			return 0;
		}
Example #2
0
        /// <summary>
        /// Closes the connection and allows reuse of the connection.
        /// </summary>
        /// <exception cref="System.ObjectDisposedException">Object already disposed.</exception>
        #endregion
        public void Close()
        {
            if (this.isDisposed)
            {
                throw new ObjectDisposedException(typeof(WmiConnection).FullName);
            }

            if (this.isConnected)
            {
                lock (this.connectLockObject)
                {
                    if (this.isConnected)
                    {
                        if (this.wbemServices != null)
                        {
                            Marshal.ReleaseComObject(this.wbemServices);

                            this.wbemServices = null;
                        }

                        this.isConnected = false;
                    }
                }
            }
        }
Example #3
0
        internal IWbemServices GetIWbemServices()
        {
            // Lets start by assuming that we'll return the RCW that we already have
            IWbemServices localCopy = wbemServices;

            // Get an IUnknown for this apartment
            IntPtr pUnk = Marshal.GetIUnknownForObject(wbemServices);

            // Get an 'IUnknown RCW' for this apartment
            Object unknown = Marshal.GetObjectForIUnknown(pUnk);

            // Release the ref count on the IUnknwon
            Marshal.Release(pUnk);

            // See if we are in the same apartment as where the original IWbemServices lived
            // If we are in a different apartment, give the caller an RCW generated just for their
            // apartment, and set the proxy blanket appropriately
            if (!object.ReferenceEquals(unknown, wbemServices))
            {
                // We need to set the proxy blanket on 'unknown' or else the QI for IWbemServices may
                // fail if we are running under a local user account.  The QI has to be done by
                // someone who is a member of the 'Everyone' group on the target machine, or DCOM
                // won't let the call through.
                SecurityHandler securityHandler = GetSecurityHandler();
                securityHandler.SecureIUnknown(unknown);

                // Now, we can QI and secure the IWbemServices
                localCopy = (IWbemServices)unknown;

                // We still need to bless the IWbemServices in this apartment
                securityHandler.Secure(localCopy);
            }

            return(localCopy); // STRANGE: Why does it still work if I return 'wbemServices'?
        }
        private IWbemObjectSink stub;                           // The secured IWbemObjectSink

        public SinkForEventQuery(ManagementEventWatcher eventWatcher,
                                 object context,
                                 IWbemServices services)
        {
            this.services     = services;
            this.context      = context;
            this.eventWatcher = eventWatcher;
            if (MTAHelper.IsNoContextMTA())  // Bug#110141 - Checking for MTA is not enough.  We need to make sure we are not in a COM+ Context
            {
                HackToCreateStubInMTA(this);
            }
            else
            {
                //
                // [marioh, RAID: 111108]
                // Ensure we are able to trap exceptions from worker thread.
                //
                ThreadDispatch disp = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(HackToCreateStubInMTA));
                disp.Parameter = this;
                disp.Start( );
//				Thread thread = new Thread(new ThreadStart(HackToCreateStubInMTA));
//                thread.ApartmentState = ApartmentState.MTA;
//                thread.Start();
//                thread.Join();
            }
        }
 internal void Secure(IWbemServices services)
 {
     if (null != scope)
     {
         scope.Secure(services);
     }
 }
Example #6
0
        // IWbemProviderInit

        int IWbemProviderInit.Initialize_(
            [In][MarshalAs(UnmanagedType.LPWStr)]  string wszUser,
            [In] Int32 lFlags,
            [In][MarshalAs(UnmanagedType.LPWStr)]  string wszNamespace,
            [In][MarshalAs(UnmanagedType.LPWStr)]  string wszLocale,
            [In][MarshalAs(UnmanagedType.Interface)]  IWbemServices pNamespace,
            [In][MarshalAs(UnmanagedType.Interface)]  IWbemContext pCtx,
            [In][MarshalAs(UnmanagedType.Interface)]  IWbemProviderInitSink pInitSink)
        {
            this.pNamespaceNA = pNamespace;
            RelocateNamespaceRCWToMTA();

            this.pSinkNA  = null;
            this.pSinkMTA = null;

            lock (mapQueryIdToQuery)
            {
                mapQueryIdToQuery.Clear();
            }

            pInitSink.SetStatus_((int)tag_WBEM_EXTRA_RETURN_CODES.WBEM_S_INITIALIZED, 0);
            Marshal.ReleaseComObject(pInitSink);

            return(0);
        }
        public SinkForEventQuery(ManagementEventWatcher eventWatcher,
                                 object context,
                                 IWbemServices services)
        {
            this.services     = services;
            this.context      = context;
            this.eventWatcher = eventWatcher;
            this.status       = 0;
            this.isLocal      = false;

            // determine if the server is local, and if so don't create a real stub using unsecap
            if ((0 == String.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
                (0 == String.Compare(eventWatcher.Scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
            {
                this.isLocal = true;
            }

            if (MTAHelper.IsNoContextMTA())
            {
                HackToCreateStubInMTA(this);
            }
            else
            {
                //
                // Ensure we are able to trap exceptions from worker thread.
                //
                ThreadDispatch disp = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(HackToCreateStubInMTA));
                disp.Parameter = this;
                disp.Start( );
            }
        }
Example #8
0
 // IWbemServices
 int IWbemServices_Old.OpenNamespace_([In][MarshalAs(UnmanagedType.BStr)]  string strNamespace,
                                      [In] Int32 lFlags,
                                      [In][MarshalAs(UnmanagedType.Interface)]  IWbemContext pCtx,
                                      [In][Out][MarshalAs(UnmanagedType.Interface)]  ref IWbemServices ppWorkingNamespace,
                                      [In] IntPtr ppCallResult)
 {
     return((int)(tag_WBEMSTATUS.WBEM_E_NOT_SUPPORTED));
 }
Example #9
0
        public void Get(ManagementOperationObserver watcher)
        {
            if (watcher == null)
            {
                throw new ArgumentNullException("watcher");
            }
            this.Initialize();
            IWbemServices      iWbemServices = this.scope.GetIWbemServices();
            EnumerationOptions options       = (EnumerationOptions)this.options.Clone();

            options.ReturnImmediately = false;
            if (watcher.HaveListenersForProgress)
            {
                options.SendStatus = true;
            }
            WmiEventSink    newSink         = watcher.GetNewSink(this.scope, options.Context);
            SecurityHandler securityHandler = this.scope.GetSecurityHandler();
            int             errorCode       = 0;

            try
            {
                if (((this.query.GetType() == typeof(SelectQuery)) && (((SelectQuery)this.query).Condition == null)) && ((((SelectQuery)this.query).SelectedProperties == null) && this.options.EnumerateDeep))
                {
                    options.EnsureLocatable = false;
                    options.PrototypeOnly   = false;
                    if (!((SelectQuery)this.query).IsSchemaQuery)
                    {
                        errorCode = this.scope.GetSecuredIWbemServicesHandler(iWbemServices).CreateInstanceEnumAsync_(((SelectQuery)this.query).ClassName, options.Flags, options.GetContext(), newSink.Stub);
                    }
                    else
                    {
                        errorCode = this.scope.GetSecuredIWbemServicesHandler(iWbemServices).CreateClassEnumAsync_(((SelectQuery)this.query).ClassName, options.Flags, options.GetContext(), newSink.Stub);
                    }
                }
                else
                {
                    options.EnumerateDeep = true;
                    errorCode             = this.scope.GetSecuredIWbemServicesHandler(iWbemServices).ExecQueryAsync_(this.query.QueryLanguage, this.query.QueryString, options.Flags, options.GetContext(), newSink.Stub);
                }
            }
            catch (COMException exception)
            {
                watcher.RemoveSink(newSink);
                ManagementException.ThrowWithExtendedInfo(exception);
            }
            finally
            {
                securityHandler.Reset();
            }
            if ((errorCode & 0xfffff000L) == 0x80041000L)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
            }
            else if ((errorCode & 0x80000000L) != 0L)
            {
                Marshal.ThrowExceptionForHR(errorCode);
            }
        }
Example #10
0
        /// <summary>
        /// Sets the authentication information that will be used to make calls on the specified proxy.
        /// </summary>
        /// <param name="this">The <see cref="WmiLight.Wbem.IWbemServices"/> object which will by wrapped with a proxy.</param>
        /// <param name="userName">The name of the user.</param>
        /// <param name="password">The password of the user.</param>
        /// <param name="authority">
        /// The authority to be used to authenticate the specified user.
        /// <para />
        /// Example: "ntlmdomain:MYDOMAIN"
        /// </param>
        /// <param name="impersonationLevel">The impersonation level which will be used.</param>
        /// <param name="authenticationLevel">The authentication level which will be used.</param>
        #endregion
        internal static void SetProxy(this IWbemServices @this, string userName, string password, string authority, ImpersonationLevel impersonationLevel, AuthenticationLevel authenticationLevel)
        {
            HResult hr = NativeMethods.CoSetProxyBlanketForIWbemServices.Invoke(@this, userName, password, authority, impersonationLevel, authenticationLevel);

            if (hr.Failed)
            {
                throw (Exception)hr;
            }
        }
Example #11
0
        /// <summary>
        /// Sets the local authentication information that will be used to make calls on the specified proxy.
        /// </summary>
        /// <param name="this">The <see cref="WmiLight.Wbem.IWbemServices"/> object which will by wrapped with a proxy.</param>
        /// <param name="impersonationLevel">The impersonation level which will be used.</param>
        /// <param name="authenticationLevel">The authentication level which will be used.</param>
        #endregion
        internal static void SetProxy(this IWbemServices @this, ImpersonationLevel impersonationLevel, AuthenticationLevel authenticationLevel)
        {
            HResult hr = NativeMethods.CoSetProxyBlanketForIWbemServices.Invoke(@this, null, null, null, impersonationLevel, authenticationLevel);

            if (hr.Failed)
            {
                throw (Exception)hr;
            }
        }
Example #12
0
		internal int ConnectNSecureIWbemServices(string path, ref IWbemServices pServices)
		{
			int num = -2147217407;
			if (this.scope != null)
			{
				num = WmiNetUtilsHelper.ConnectServerWmi_f(path, this.scope.Options.Username, this.scope.Options.GetPassword(), this.scope.Options.Locale, this.scope.Options.Flags, this.scope.Options.Authority, this.scope.Options.GetContext(), out pServices, (int)this.scope.Options.Impersonation, (int)this.scope.Options.Authentication);
			}
			return num;
		}
Example #13
0
        internal int ConnectNSecureIWbemServices(string path, ref IWbemServices pServices)
        {
            int num = -2147217407;

            if (this.scope != null)
            {
                num = WmiNetUtilsHelper.ConnectServerWmi_f(path, this.scope.Options.Username, this.scope.Options.GetPassword(), this.scope.Options.Locale, this.scope.Options.Flags, this.scope.Options.Authority, this.scope.Options.GetContext(), out pServices, (int)this.scope.Options.Impersonation, (int)this.scope.Options.Authentication);
            }
            return(num);
        }
Example #14
0
        //Called when IdentifierChanged() event fires
        private void HandleIdentifierChange(object sender,
                                            IdentifierChangedEventArgs args)
        {
            // Since our object has changed we had better signal to ourself that
            // an connection needs to be established
            wbemServices = null;

            //Something inside ManagementScope changed, we need to fire an event
            //to the parent object
            FireIdentifierChanged();
        }
 internal ManagementScope(ManagementPath path, IWbemServices wbemServices, ConnectionOptions options)
 {
     if (path != null)
     {
         this.Path = path;
     }
     if (options != null)
     {
         this.Options = options;
     }
     this.wbemServices = wbemServices;
 }
Example #16
0
 internal ManagementScope(ManagementPath path, IWbemServices wbemServices, ConnectionOptions options)
 {
     if (path != null)
     {
         this.Path = path;
     }
     if (options != null)
     {
         this.Options = options;
     }
     this.wbemServices = wbemServices;
 }
        //********************************************
        //Start
        //********************************************
        /// <summary>
        ///    <para>Subscribes to events with the given query and delivers
        ///       them, asynchronously, through the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
        /// </summary>
        public void Start()
        {
            Initialize();

            // Cancel any current event query
            Stop();

            // Submit a new query
            SecurityHandler securityHandler = Scope.GetSecurityHandler();
            IWbemServices   wbemServices    = scope.GetIWbemServices();

            try
            {
                sink = new SinkForEventQuery(this, options.Context, wbemServices);
                if (sink.Status < 0)
                {
                    Marshal.ThrowExceptionForHR(sink.Status, WmiNetUtilsHelper.GetErrorInfo_f());
                }

                // For async event queries we should ensure 0 flags as this is
                // the only legal value
                int status = scope.GetSecuredIWbemServicesHandler(wbemServices).ExecNotificationQueryAsync_(
                    query.QueryLanguage,
                    query.QueryString,
                    0,
                    options.GetContext(),
                    sink.Stub);


                if (status < 0)
                {
                    if (sink != null)
                    {
                        sink.ReleaseStub();
                        sink = null;
                    }

                    if ((status & 0xfffff000) == 0x80041000)
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                    }
                    else
                    {
                        Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
                    }
                }
            }
            finally
            {
                securityHandler.Reset();
            }
        }
Example #18
0
        /// <summary>
        /// Sets the authentication information and executes a query to retrieve objects.
        /// </summary>
        /// <param name="this">The <see cref="WmiLight.Wbem.IWbemServices"/> object which will by wrapped with a proxy.</param>
        /// <param name="query">The query which will be executed.</param>
        /// <param name="enumeratorBehaviorOption">Flag for the behavior of the created enumerator.</param>
        /// <param name="ctx">
        /// Typically, this is NULL.
        /// Otherwise, this is an <see cref="WmiLight.Wbem.IWbemContext"/> object required by one or more dynamic class providers.
        /// </param>
        /// <param name="impersonationLevel">The impersonation level which will be used.</param>
        /// <param name="authenticationLevel">The authentication level which will be used.</param>
        /// <param name="userName">The name of the user.</param>
        /// <param name="password">The password of the user.</param>
        /// <param name="authority">
        /// The authority to be used to authenticate the specified user.
        /// <para />
        /// Example: "ntlmdomain:MYDOMAIN"
        /// </param>
        /// <returns>The enumerator for the results of the query.</returns>
        #endregion
        internal static IWbemClassObjectEnumerator ExecQuery(this IWbemServices @this, string query, WbemClassObjectEnumeratorBehaviorOption enumeratorBehaviorOption, IWbemContext ctx, AuthenticationLevel impersonationLevel, ImpersonationLevel authenticationLevel, string userName, string password, string authority)
        {
            IWbemClassObjectEnumerator enumerator;

            HResult hr = NativeMethods.ExecQueryWmi("WQL", query, enumeratorBehaviorOption, ctx, out enumerator, impersonationLevel, authenticationLevel, @this, userName, password, authority);

            if (hr.Failed)
            {
                throw (Exception)hr;
            }

            return(enumerator);
        }
Example #19
0
		internal void Secure(IWbemServices services)
		{
			if (this.scope != null)
			{
				IntPtr password = this.scope.Options.GetPassword();
				int num = WmiNetUtilsHelper.BlessIWbemServices_f(services, this.scope.Options.Username, password, this.scope.Options.Authority, (int)this.scope.Options.Impersonation, (int)this.scope.Options.Authentication);
				Marshal.ZeroFreeBSTR(password);
				if (num < 0)
				{
					Marshal.ThrowExceptionForHR(num);
				}
			}
		}
Example #20
0
 internal void Secure(IWbemServices services)
 {
     if (null != scope)
     {
         securityHelper.BlessIWbemServices(
             services,
             scope.Options.Username,
             scope.Options.GetPassword(),
             scope.Options.Authority,
             (int)scope.Options.Impersonation,
             (int)scope.Options.Authentication);
     }
 }
Example #21
0
        /// <summary>
        /// Executes a query to retrieve objects.
        /// </summary>
        /// <param name="this">The <see cref="IWbemServices"/> object which will be used.</param>
        /// <param name="query">The query which will be executed.</param>
        /// <param name="enumeratorBehaviorOption">Flag for the behavior of the created enumerator.</param>
        /// <param name="ctx">
        /// Typically, this is NULL.
        /// Otherwise, this is an <see cref="WmiLight.Wbem.IWbemContext"/> object required by one or more dynamic class providers.
        /// </param>
        /// <returns>The enumerator for the results of the query.</returns>
        #endregion
        internal static IWbemClassObjectEnumerator ExecQuery(this IWbemServices @this, string query, WbemClassObjectEnumeratorBehaviorOption enumeratorBehaviorOption, IWbemContext ctx)
        {
            IWbemClassObjectEnumerator enumerator;

            HResult hr = @this.ExecQuery("WQL", query, enumeratorBehaviorOption, ctx, out enumerator);

            if (hr.Failed)
            {
                throw (Exception)hr;
            }

            return(enumerator);
        }
 internal void Secure(IWbemServices services)
 {
     if (this.scope != null)
     {
         IntPtr password  = this.scope.Options.GetPassword();
         int    errorCode = WmiNetUtilsHelper.BlessIWbemServices_f(services, this.scope.Options.Username, password, this.scope.Options.Authority, (int)this.scope.Options.Impersonation, (int)this.scope.Options.Authentication);
         Marshal.ZeroFreeBSTR(password);
         if (errorCode < 0)
         {
             Marshal.ThrowExceptionForHR(errorCode);
         }
     }
 }
Example #23
0
 int IWbemProviderInit.Initialize_([In, MarshalAs(UnmanagedType.LPWStr)] string wszUser, [In] int lFlags, [In, MarshalAs(UnmanagedType.LPWStr)] string wszNamespace, [In, MarshalAs(UnmanagedType.LPWStr)] string wszLocale, [In, MarshalAs(UnmanagedType.Interface)] IWbemServices pNamespace, [In, MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In, MarshalAs(UnmanagedType.Interface)] IWbemProviderInitSink pInitSink)
 {
     this.pNamespaceNA = pNamespace;
     this.RelocateNamespaceRCWToMTA();
     this.pSinkNA  = null;
     this.pSinkMTA = null;
     lock (this.mapQueryIdToQuery)
     {
         this.mapQueryIdToQuery.Clear();
     }
     pInitSink.SetStatus_(0, 0);
     Marshal.ReleaseComObject(pInitSink);
     return(0);
 }
Example #24
0
 int System.Management.IWbemProviderInit.Initialize_(string wszUser, int lFlags, string wszNamespace, string wszLocale, IWbemServices pNamespace, IWbemContext pCtx, IWbemProviderInitSink pInitSink)
 {
     this.pNamespaceNA = pNamespace;
     this.RelocateNamespaceRCWToMTA();
     this.pSinkNA  = null;
     this.pSinkMTA = null;
     lock (this.mapQueryIdToQuery)
     {
         this.mapQueryIdToQuery.Clear();
     }
     pInitSink.SetStatus_(0, 0);
     Marshal.ReleaseComObject(pInitSink);
     return(0);
 }
        private IWbemObjectSink stub;                           // The secured IWbemObjectSink

        public SinkForEventQuery(ManagementEventWatcher eventWatcher,
                                 object context,
                                 IWbemServices services)
        {
            this.services     = services;
            this.context      = context;
            this.eventWatcher = eventWatcher;

            IWmiSinkDemultiplexor sinkDmux = (IWmiSinkDemultiplexor) new WmiSinkDemultiplexor();
            object dmuxStub = null;

            sinkDmux.GetDemultiplexedStub(this, out dmuxStub);
            stub = (IWbemObjectSink)dmuxStub;
        }
        internal void Secure(IWbemServices wbemServices)
        {
            if (null == securityHelper)
            {
                securityHelper = (IWmiSec) new WmiSec();
            }

            securityHelper.BlessIWbemServices(
                ref wbemServices,
                options.Username,
                options.GetPassword(),
                options.Authority,
                (int)options.Impersonation,
                (int)options.Authentication);
        }
Example #27
0
        internal IWbemServices GetIWbemServices()
        {
            IWbemServices wbemServices      = this.wbemServices;
            IntPtr        iUnknownForObject = Marshal.GetIUnknownForObject(this.wbemServices);
            object        objectForIUnknown = Marshal.GetObjectForIUnknown(iUnknownForObject);

            Marshal.Release(iUnknownForObject);
            if (!object.ReferenceEquals(objectForIUnknown, this.wbemServices))
            {
                SecurityHandler securityHandler = this.GetSecurityHandler();
                securityHandler.SecureIUnknown(objectForIUnknown);
                wbemServices = (IWbemServices)objectForIUnknown;
                securityHandler.Secure(wbemServices);
            }
            return(wbemServices);
        }
        //********************************************
        //Start
        //********************************************
        /// <summary>
        ///    <para>Subscribes for events with the given query and delivers them asynchronously, through the EventArrived event.</para>
        /// </summary>
        public void Start()
        {
            Initialize();

            // Cancel any current event query
            Stop();

            SecurityHandler securityHandler = Scope.GetSecurityHandler();

            int status = (int)ManagementStatus.NoError;

            // Submit a new query
            try
            {
                IWbemServices wbemServices = scope.GetIWbemServices();
                sink = new SinkForEventQuery(this, options.GetContext(), wbemServices);

                // For async event queries we should ensure 0 flags as this is
                // the only legal value
                status = wbemServices.ExecNotificationQueryAsync_(
                    query.QueryLanguage,
                    query.QueryString,
                    0,
                    options.GetContext(),
                    sink.Stub);
            } catch (Exception e) {
                // BUGBUG : securityHandler.Reset()?
                if (sink != null)                               // BUGBUG : This looks dangerous
                {
                    sink.ReleaseStub();
                    sink = null;
                }
                ManagementException.ThrowWithExtendedInfo(e);
            } finally {
                securityHandler.Reset();
            }

            if ((status & 0xfffff000) == 0x80041000)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
            }
            else if ((status & 0x80000000) != 0)
            {
                Marshal.ThrowExceptionForHR(status);
            }
        }
Example #29
0
        //Internal constructor
        internal ManagementScope(ManagementPath path, IWbemServices wbemServices,
                                 IWmiSec securityHelper, ConnectionOptions options)
        {
            if (null != path)
            {
                this.Path = path;
            }

            if (null != options)
            {
                this.Options = options;
            }

            // We set this.wbemServices after setting Path and Options
            // because the latter operations can cause wbemServices to be NULLed.
            this.wbemServices = wbemServices;
//			this.securityHelper = securityHelper;
        }
Example #30
0
        /// <summary>
        /// Establishes a connection to the WMI server and namespace.
        /// </summary>
        #endregion
        public void Open()
        {
            if (this.isDisposed)
            {
                throw new ObjectDisposedException(typeof(WmiConnection).FullName);
            }

            if (!this.isConnected)
            {
                IWbemLocator locator = new WbemLocator();

                lock (this.connectLockObject)
                {
                    if (!this.isConnected)
                    {
                        AuthenticationLevel authLevel = this.options.EnablePackageEncryption ? AuthenticationLevel.PacketIntegrity : AuthenticationLevel.PacketPrivacy;

                        if (this.IsRemote)
                        {
                            try
                            {
                                this.wbemServices = locator.ConnectServer(this.path, this.credential.UserName, this.credential.Password, null, WbemConnectOption.None, this.Authority, this.context);
                                this.wbemServices.SetProxy(this.credential.UserName, this.credential.Password, this.Authority, ImpersonationLevel.Impersonate, authLevel);
                            }
                            catch (LocalCredentialsException)
                            {
                                // try again without credential
                                this.ignoreCredential = true;
                                this.Open();
                                return; // exit method
                            }
                        }
                        else
                        {
                            this.wbemServices = locator.ConnectServer(this.path, null, null, null, WbemConnectOption.None, null, this.context);
                            this.wbemServices.SetProxy(ImpersonationLevel.Impersonate, authLevel);
                        }

                        this.isConnected = true;
                    }
                }
            }
        }
 public SinkForEventQuery(ManagementEventWatcher eventWatcher, object context, IWbemServices services)
 {
     this.services = services;
     this.context = context;
     this.eventWatcher = eventWatcher;
     this.status = 0;
     this.isLocal = false;
     if ((string.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(eventWatcher.Scope.Path.Server, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0))
     {
         this.isLocal = true;
     }
     if (MTAHelper.IsNoContextMTA())
     {
         this.HackToCreateStubInMTA(this);
     }
     else
     {
         new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(this.HackToCreateStubInMTA)) { Parameter = this }.Start();
     }
 }
Example #32
0
 public SinkForEventQuery(ManagementEventWatcher eventWatcher, object context, IWbemServices services)
 {
     this.services     = services;
     this.context      = context;
     this.eventWatcher = eventWatcher;
     this.status       = 0;
     this.isLocal      = false;
     if ((string.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(eventWatcher.Scope.Path.Server, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0))
     {
         this.isLocal = true;
     }
     if (MTAHelper.IsNoContextMTA())
     {
         this.HackToCreateStubInMTA(this);
     }
     else
     {
         new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(this.HackToCreateStubInMTA))
         {
             Parameter = this
         }.Start();
     }
 }
Example #33
0
        public void Start()
        {
            this.Initialize();
            this.Stop();
            SecurityHandler securityHandler = this.Scope.GetSecurityHandler();
            IWbemServices   wbemServices    = this.scope.GetIWbemServices();

            try
            {
                this.sink = new SinkForEventQuery(this, this.options.Context, wbemServices);
                if (this.sink.Status < 0)
                {
                    Marshal.ThrowExceptionForHR(this.sink.Status);
                }
                int num = this.scope.GetSecuredIWbemServicesHandler(wbemServices).ExecNotificationQueryAsync_(this.query.QueryLanguage, this.query.QueryString, 0, this.options.GetContext(), this.sink.Stub);
                if (num < 0)
                {
                    if (this.sink != null)
                    {
                        this.sink.ReleaseStub();
                        this.sink = null;
                    }
                    if (((long)num & (long)-4096) != (long)-2147217408)
                    {
                        Marshal.ThrowExceptionForHR(num);
                    }
                    else
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
                    }
                }
            }
            finally
            {
                securityHandler.Reset();
            }
        }
Example #34
0
        public void Start()
        {
            this.Initialize();
            this.Stop();
            SecurityHandler securityHandler = this.Scope.GetSecurityHandler();
            IWbemServices   iWbemServices   = this.scope.GetIWbemServices();

            try
            {
                this.sink = new SinkForEventQuery(this, this.options.Context, iWbemServices);
                if (this.sink.Status < 0)
                {
                    Marshal.ThrowExceptionForHR(this.sink.Status);
                }
                int errorCode = this.scope.GetSecuredIWbemServicesHandler(iWbemServices).ExecNotificationQueryAsync_(this.query.QueryLanguage, this.query.QueryString, 0, this.options.GetContext(), this.sink.Stub);
                if (errorCode < 0)
                {
                    if (this.sink != null)
                    {
                        this.sink.ReleaseStub();
                        this.sink = null;
                    }
                    if ((errorCode & 0xfffff000L) == 0x80041000L)
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                    }
                    else
                    {
                        Marshal.ThrowExceptionForHR(errorCode);
                    }
                }
            }
            finally
            {
                securityHandler.Reset();
            }
        }
Example #35
0
        public SinkForEventQuery(ManagementEventWatcher eventWatcher,
                                 object context,
                                 IWbemServices services)
        {
            this.services     = services;
            this.context      = context;
            this.eventWatcher = eventWatcher;
            this.status       = 0;
            this.isLocal      = false;

            // determine if the server is local, and if so don't create a real stub using unsecap
            if ((0 == String.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
                (0 == String.Compare(eventWatcher.Scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
            {
                this.isLocal = true;
            }

            if (MTAHelper.IsNoContextMTA())  // Bug#110141 - Checking for MTA is not enough.  We need to make sure we are not in a COM+ Context
            {
                HackToCreateStubInMTA(this);
            }
            else
            {
                //
                // [marioh, RAID: 111108]
                // Ensure we are able to trap exceptions from worker thread.
                //
                ThreadDispatch disp = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(HackToCreateStubInMTA));
                disp.Parameter = this;
                disp.Start( );
                //            Thread thread = new Thread(new ThreadStart(HackToCreateStubInMTA));
                //            thread.ApartmentState = ApartmentState.MTA;
                //            thread.Start();
                //            thread.Join();
            }
        }
Example #36
0
		internal static int PutInstanceWmi(IntPtr pInst, int lFlags, IWbemContext pCtx, IntPtr ppCallResult, int impLevel, int authnLevel, IWbemServices pCurrentNamespace, string strUser, IntPtr strPassword, string strAuthority)
		{
			return pCurrentNamespace.PutInstance_ (pInst, lFlags, pCtx, ppCallResult);
		}
Example #37
0
		internal static int ConnectServerWmi(string strNetworkResource, string strUser, IntPtr strPassword, string strLocale, int lSecurityFlags, string strAuthority, IWbemContext pCtx, out IWbemServices ppNamespace, int impersonationLevel, int authenticationLevel)
		{
			WMIDatabaseFactory.EnsureOpen();
			ppNamespace = new UnixWbemServices();
			return 0;
		}
Example #38
0
		internal static int ExecQueryWmi(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, out IEnumWbemClassObject ppEnum, int impLevel, int authnLevel, IWbemServices pCurrentNamespace, string strUser, IntPtr strPassword, string strAuthority)
		{
			var svc = pCurrentNamespace as UnixWbemServices;
			IEnumerable<IWbemClassObject_DoNotMarshal> list = WMIDatabaseFactory.Get(svc.CurrentNamespace, strQuery);
			ppEnum = new UnixEnumWbemClassObject(list);
			return 0;
		}
Example #39
0
		internal static int BlessIWbemServices(IWbemServices pIUnknown, string strUser, IntPtr password, string strAuthority, int impersonationLevel, int authenticationLevel)
		{
			return 0;
		}
 internal SecuredIWbemServicesHandler(ManagementScope theScope, IWbemServices pWbemServiecs)
 {
     this.scope = theScope;
     this.pWbemServiecsSecurityHelper = pWbemServiecs;
 }
Example #41
0
		internal static int ExecNotificationQueryWmi(string strQueryLanguage, string strQuery, int lFlags, IWbemContext pCtx, out IEnumWbemClassObject ppEnum, int impLevel, int authnLevel, IWbemServices pCurrentNamespace, string strUser, IntPtr strPassword, string strAuthority)
		{
			ppEnum = null;
			return 0;
		}
Example #42
0
		public int OpenNamespace_ (string strNamespace, int lFlags, IWbemContext pCtx, out IWbemServices ppWorkingNamespace, IntPtr ppCallResult)
		{
			ppWorkingNamespace = new UnixWbemServices(strNamespace);
			return 0;
		}
Example #43
0
        //Called when IdentifierChanged() event fires
        private void HandleIdentifierChange(object sender,
            IdentifierChangedEventArgs args)
        {
            // Since our object has changed we had better signal to ourself that
            // an connection needs to be established
            wbemServices = null;

            //Something inside ManagementScope changed, we need to fire an event
            //to the parent object
            FireIdentifierChanged();
        }
Example #44
0
		internal SecuredIWbemServicesHandler GetSecuredIWbemServicesHandler(IWbemServices pWbemServiecs)
		{
			return new SecuredIWbemServicesHandler(this, pWbemServiecs);
		}
        public SinkForEventQuery (ManagementEventWatcher eventWatcher,
            object context, 
            IWbemServices services)
        {
            this.services = services;
            this.context = context;
            this.eventWatcher = eventWatcher;
            this.status = 0;
            this.isLocal = false;

            // determine if the server is local, and if so don't create a real stub using unsecap
            if((0==String.Compare(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
                (0==String.Compare(eventWatcher.Scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
            {
                this.isLocal = true;
            }
            
            if(MTAHelper.IsNoContextMTA())  // Bug#110141 - Checking for MTA is not enough.  We need to make sure we are not in a COM+ Context
                HackToCreateStubInMTA(this);
            else
            {
                //
                // [marioh, RAID: 111108]
                // Ensure we are able to trap exceptions from worker thread.
                //
                ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethodWithParam ( HackToCreateStubInMTA ) ) ;
                disp.Parameter = this ;
                disp.Start ( ) ;
                //            Thread thread = new Thread(new ThreadStart(HackToCreateStubInMTA));
                //            thread.ApartmentState = ApartmentState.MTA;
                //            thread.Start();
                //            thread.Join();
            }

        }
Example #46
0
 internal int ConnectNSecureIWbemServices(string path,  ref IWbemServices pServices)
 {
     int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED;
     if( null != scope )
     {
         IntPtr password = scope.Options.GetPassword();
         status = WmiNetUtilsHelper.ConnectServerWmi_f(
             path,
             scope.Options.Username,
             password, 
             scope.Options.Locale,
             scope.Options.Flags,
             scope.Options.Authority,
             scope.Options.GetContext(),
             out pServices,
             (int)scope.Options.Impersonation,
             (int)scope.Options.Authentication);
         System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password);
     }
     return status;
 }
Example #47
0
 internal int OpenNamespace_(string strNamespace, Int32 lFlags, ref IWbemServices ppWorkingNamespace, IntPtr ppCallResult)
 {
     int status = (int)tag_WBEMSTATUS.WBEM_E_NOT_SUPPORTED;
     //This should go through WMINET_utils layer and ppWorkingNamespace should be secured. See implementation of CreateInstanceEnum method.
     return status;
 }
Example #48
0
 internal void Secure (IWbemServices services)
  {
      if (null != scope)
      {
          IntPtr password = scope.Options.GetPassword();
          int status = WmiNetUtilsHelper.BlessIWbemServices_f
              (
              services,
              scope.Options.Username,
              password,
              scope.Options.Authority,
              (int)scope.Options.Impersonation,
              (int)scope.Options.Authentication
              );
          System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password);
          if (status < 0)
          {
              Marshal.ThrowExceptionForHR(status);
          }
      }
  }
        // IWbemProviderInit

        int IWbemProviderInit.Initialize_(
            [In][MarshalAs(UnmanagedType.LPWStr)]  string   wszUser,
            [In] Int32 lFlags,
            [In][MarshalAs(UnmanagedType.LPWStr)]  string   wszNamespace,
            [In][MarshalAs(UnmanagedType.LPWStr)]  string   wszLocale,
            [In][MarshalAs(UnmanagedType.Interface)]  IWbemServices   pNamespace,
            [In][MarshalAs(UnmanagedType.Interface)]  IWbemContext   pCtx,
            [In][MarshalAs(UnmanagedType.Interface)]  IWbemProviderInitSink   pInitSink)
        {
            this.pNamespaceNA = pNamespace;
            RelocateNamespaceRCWToMTA();

            this.pSinkNA = null;
            this.pSinkMTA = null;

            lock(mapQueryIdToQuery)
            {
                mapQueryIdToQuery.Clear();
            }

            pInitSink.SetStatus_((int)tag_WBEM_EXTRA_RETURN_CODES.WBEM_S_INITIALIZED, 0);
            Marshal.ReleaseComObject(pInitSink);

            return 0;
        }
 internal int OpenNamespace_(string strNamespace, int lFlags, ref IWbemServices ppWorkingNamespace, IntPtr ppCallResult)
 {
     return -2147217396;
 }
Example #51
0
		private void HandleIdentifierChange(object sender, IdentifierChangedEventArgs args)
		{
			this.wbemServices = null;
			this.FireIdentifierChanged();
		}
Example #52
0
        //Internal constructor
        internal ManagementScope (ManagementPath path, IWbemServices wbemServices, 
            ConnectionOptions options)
        {
            if (null != path)
                this.Path = path;

            if (null != options)
                this.Options = options;

            // We set this.wbemServices after setting Path and Options
            // because the latter operations can cause wbemServices to be NULLed.
            this.wbemServices = wbemServices;
        }
 int IWbemProviderInit.Initialize_([In, MarshalAs(UnmanagedType.LPWStr)] string wszUser, [In] int lFlags, [In, MarshalAs(UnmanagedType.LPWStr)] string wszNamespace, [In, MarshalAs(UnmanagedType.LPWStr)] string wszLocale, [In, MarshalAs(UnmanagedType.Interface)] IWbemServices pNamespace, [In, MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In, MarshalAs(UnmanagedType.Interface)] IWbemProviderInitSink pInitSink)
 {
     this.pNamespaceNA = pNamespace;
     this.RelocateNamespaceRCWToMTA();
     this.pSinkNA = null;
     this.pSinkMTA = null;
     lock (this.mapQueryIdToQuery)
     {
         this.mapQueryIdToQuery.Clear();
     }
     pInitSink.SetStatus_(0, 0);
     Marshal.ReleaseComObject(pInitSink);
     return 0;
 }
Example #54
0
		int System.Management.IWbemProviderInit.Initialize_(string wszUser, int lFlags, string wszNamespace, string wszLocale, IWbemServices pNamespace, IWbemContext pCtx, IWbemProviderInitSink pInitSink)
		{
			this.pNamespaceNA = pNamespace;
			this.RelocateNamespaceRCWToMTA();
			this.pSinkNA = null;
			this.pSinkMTA = null;
			lock (this.mapQueryIdToQuery)
			{
				this.mapQueryIdToQuery.Clear();
			}
			pInitSink.SetStatus_(0, 0);
			Marshal.ReleaseComObject(pInitSink);
			return 0;
		}
Example #55
0
		int System.Management.IWbemServices_Old.OpenNamespace_(string strNamespace, int lFlags, IWbemContext pCtx, out IWbemServices ppWorkingNamespace, IntPtr ppCallResult)
		{
			ppWorkingNamespace  = null;
			return -2147217396;
		}
 internal IWbemServices GetIWbemServices()
 {
     IWbemServices wbemServices = this.wbemServices;
     IntPtr iUnknownForObject = Marshal.GetIUnknownForObject(this.wbemServices);
     object objectForIUnknown = Marshal.GetObjectForIUnknown(iUnknownForObject);
     Marshal.Release(iUnknownForObject);
     if (!object.ReferenceEquals(objectForIUnknown, this.wbemServices))
     {
         SecurityHandler securityHandler = this.GetSecurityHandler();
         securityHandler.SecureIUnknown(objectForIUnknown);
         wbemServices = (IWbemServices) objectForIUnknown;
         securityHandler.Secure(wbemServices);
     }
     return wbemServices;
 }