File: wmi.cpp

package info (click to toggle)
mysql-workbench 6.3.8%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 113,932 kB
  • ctags: 87,814
  • sloc: ansic: 955,521; cpp: 427,465; python: 59,728; yacc: 59,129; xml: 54,204; sql: 7,091; objc: 965; makefile: 638; sh: 613; java: 237; perl: 30; ruby: 6; php: 1
file content (832 lines) | stat: -rw-r--r-- 27,112 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
/* 
 * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the
 * License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#include <iostream>
#include <sstream>

#include "base/string_utilities.h"
#include "base/threading.h"
#include "base/log.h"

#include "wmi.h"

#pragma comment(lib, "comsuppw.lib")

using namespace wmi;
using namespace grt;

DEFAULT_LOG_DOMAIN("wmi")

//--------------------------------------------------------------------------------------------------

/**
 * Converts the given variant to an UTF-8 encoded standard string. The variant content is converted to
 * a string if it is not already one.
 */
std::string variant2string(VARIANT& value) 
{
  if (value.vt == VT_NULL)
    return "NULL";

  VariantChangeType(&value, &value, VARIANT_ALPHABOOL, VT_BSTR);
  CW2A valueString(V_BSTR(&value), CP_UTF8);
  return (LPSTR) valueString;
}

//--------------------------------------------------------------------------------------------------

/**
 * Converts the given string (which must be UTF-8 encoded) to a BSTR, encapsulated by CComBSTR
 * which frees us from taking care to deallocate the result.
 */
CComBSTR string2Bstr(const std::string& value)
{
  CComBSTR result = CA2W(value.c_str(), CP_UTF8);
  return result;
}

//--------------------------------------------------------------------------------------------------

#ifdef _DEBUG

void dumpObject(IWbemClassObject* object)
{
  if (object != NULL)
  {
    BSTR objectText;
    object->GetObjectText(0, &objectText);
    std::wcout << objectText << std::endl;
    SysFreeString(objectText);
  }
  else
    std::wcout << L"Object is NULL" << std::endl;
}

//--------------------------------------------------------------------------------------------------

#endif

std::string wmiResultToString(HRESULT wmiResult)
{
  std::string result;
  IWbemStatusCodeText* status = NULL;

  HRESULT hres = CoCreateInstance(CLSID_WbemStatusCodeText, 0, CLSCTX_INPROC_SERVER,
    IID_IWbemStatusCodeText, (LPVOID*)&status);

  if (SUCCEEDED(hres))
  {
    CComBSTR errorString;
    hres = status->GetErrorCodeText(wmiResult, 0, 0, &errorString);

    if (FAILED(hres))
    {
      log_error("Converting result code to string failed with error: %d\n", hres);
      result = "Internal error: WMI error description retrieval failed.";
    }

    CW2A converted_text(errorString, CP_UTF8);
    result = converted_text;
    status->Release();
  }
  else
  {
    log_error("Could not instatiate a status code text converter. Error code: %d\n", hres);
    result = "Internal error: WMI status code text creation failed.";
  }

  return result;
}

//--------------------------------------------------------------------------------------------------

std::string serviceResultToString(unsigned int result)
{
  // Error codes according to http://msdn.microsoft.com/en-us/library/aa393660%28VS.85%29.aspx.
  static std::string code2String[] = {
    "Success",
    "Not Supported",
    "Access Denied",
    "Dependent Services Running",
    "Invalid Service Control",
    "Service Cannot Accept Control",
    "Service Not Active",
    "Service Request Timeout",
    "Unknown Failure",
    "Path Not Found",
    "Service Already Running",
    "Service Database Locked",
    "Service Dependency Deleted",
    "Service Dependency Failure",
    "Service Disabled",
    "Service Logon Failure",
    "Service Marked For Deletion",
    "Service No Thread",
    "Status Circular Dependency",
    "Status Duplicate Name",
    "Status Invalid Name",
    "Status Invalid Parameter",
    "Status Invalid Service Account",
    "Status Service Exists",
    "Service Already Paused"
  };


  if (result < 25)
    return code2String[result];

  return "Unknown error";
}

//----------------- WmiMonitor ---------------------------------------------------------------------

WmiMonitor::WmiMonitor(IWbemServices* services, const std::string& parameter)
  : _services(services), _propertyHandle(0), _namePropertyHandle(0), _findTotal(false)
{
  log_debug("Creating new wmi monitor for parameter: %s\n", parameter.c_str());
  
  const std::vector<std::string> args = base::split(parameter, ".");

  if (args.size() < 2)
  {
    log_error("Invalid parameter format - cannot continue\n");
    throw std::runtime_error(_("Wrong monitor format. Got '") + parameter + _("', expected '<WMIClass.Name>'"));
  }

  CComBSTR instancePath;

  HRESULT hr = CoCreateInstance(CLSID_WbemRefresher, NULL, CLSCTX_INPROC_SERVER, IID_IWbemRefresher, 
    (void**) &_refresher);
  if (FAILED(hr))
  {
    log_error("Could not create a wbem refresher instance. Error: %d\n", hr);
    throw std::runtime_error(_("WMI - Could not create monitor object.\n\n") + wmiResultToString(hr));
  }

  CComPtr<IWbemConfigureRefresher> config;
  hr = _refresher->QueryInterface(IID_IWbemConfigureRefresher, (void**) &config);
  if (FAILED(hr))
  {
    log_error("QueryInterface for wbem configure refresher failed with error: %d\n", hr);

    // _refersher is a smart pointer and is automatically freed.
    throw std::runtime_error(_("WMI - Could not create monitor object.\n\n") + wmiResultToString(hr));
  }

  CComBSTR path = args[0].c_str();
  _propertyName = args[1].c_str();

  if (path.Length() == 0)
    throw std::runtime_error(_("WMI - Invalid monitoring parameter specified."));

  // Add an enumerator to the refresher. This is what actually gets the value to monitor.
  hr = config->AddEnum(_services, path, 0, NULL, &_enumerator, &_enumeratorId);
  if (FAILED(hr))
  {
    std::string result = wmiResultToString(hr);
    log_error("Could not register monitoring enumerator. Error: %s\n", result.c_str());
    throw std::runtime_error(_("WMI - Could not register monitoring enumerator.\n"));
  }
}

//--------------------------------------------------------------------------------------------------

WmiMonitor::~WmiMonitor()
{
  log_debug("Destroying monitor\n");
  
  CComPtr<IWbemConfigureRefresher> config;
  HRESULT hr = _refresher->QueryInterface(IID_IWbemConfigureRefresher, (void**) &config);
  if (SUCCEEDED(hr))
    config->Remove(_enumeratorId, WBEM_FLAG_REFRESH_NO_AUTO_RECONNECT);
  else
  {
    std::string result = wmiResultToString(hr);
    log_error("Could not remove enumerator from wbem config refresher. Error: %s\n", result.c_str());
  }
}

//--------------------------------------------------------------------------------------------------

std::string WmiMonitor::readValue()
{
  log_debug("Reading next monitoring value\n");

  // Refresh the enumerator so we actually get values.
  _refresher->Refresh(0L);

  // Read the results.
  ULONG returnCount = 0;
  IWbemObjectAccess** accessors = NULL; // List of accessors.

  // Determine required space. We have to provide it to the getter.
  HRESULT hr = _enumerator->GetObjects(0L, 0, accessors, &returnCount); 
  if (hr == WBEM_E_BUFFER_TOO_SMALL && returnCount > 0)
  {
    accessors = new IWbemObjectAccess*[returnCount];
    SecureZeroMemory(accessors, returnCount * sizeof(IWbemObjectAccess*));

    hr = _enumerator->GetObjects(0L, returnCount, accessors,  &returnCount);
    if (FAILED(hr))
    {
      std::string result = wmiResultToString(hr);
      log_error("Cannot get value object from enumerator. Error: %s\n", result.c_str());

      delete [] accessors;
      return "0";
    }
  }

  std::string result = "0";

  // First time we access the property we have to get a handle for it, which
  // can be reused for any subsequent query.
  CIMTYPE propertyType;
  if (_propertyHandle == 0)
    hr = accessors[0]->GetPropertyHandle(_propertyName, &propertyType, &_propertyHandle);

  if (FAILED(hr))
  {
    std::string result = wmiResultToString(hr);
    log_error("Cannot get property handle from wbem accessor. Error: %s\n", result.c_str());
  }

  CIMTYPE namePropType;
  if (_findTotal && _namePropertyHandle == 0)
    hr = accessors[0]->GetPropertyHandle(L"Name", &namePropType, &_namePropertyHandle);

  if (FAILED(hr))
  {
    std::string result = wmiResultToString(hr);
    log_error("Cannot get name property handle from wbem accessor. Error: %s\n", result.c_str());
  }

  if (_propertyHandle != 0)
  {
    DWORD value = 0;
    if (_namePropertyHandle != 0)
    {
      // For processor time queries a value is returned for every processor and a total entry
      // that comprises all processors.
      for (ULONG i = 0; i < returnCount; i++)
      {
        long byteCount = 0;
        byte buffer[20];
        hr = accessors[i]->ReadPropertyValue(_namePropertyHandle, 20, &byteCount, buffer);

        if (StrCmpW((LPCWSTR) buffer, L"_Total") == 0)
        {
          hr = accessors[i]->ReadDWORD(_propertyHandle, &value);
          if (FAILED(hr))
          {
            std::string result = wmiResultToString(hr);
            log_error("Cannot read DWORD value from wbem accessor. Error: %s\n", result.c_str());
          }

          break;
        }
      }
    }
    else
    {
      // No need to search for a specific value. Simply return the first (and mostly only) property value
      // we got.
      hr = accessors[0]->ReadDWORD(_propertyHandle, &value);

      if (FAILED(hr))
      {
        std::string result = wmiResultToString(hr);
        log_error("Cannot read DWORD value from wbem accessor. Error: %s\n", result.c_str());
      }
    }

    std::stringstream ss;
    ss << value;
    result = ss.str();
  }

  for (ULONG i = 0; i < returnCount; i++)
    accessors[i]->Release();
  delete [] accessors;

  return result;
}

//----------------- WmiServices --------------------------------------------------------------------

static base::Mutex _locator_mutex;
static IWbemLocator* _locator = NULL;
static int _locator_refcount = 0;

WmiServices::WmiServices(const std::string& server, const std::string& user, const std::string& password)
{
  if (server.empty())
    log_debug("Creating WmiServices for local server (user: %s)\n", user.c_str());
  else
    log_debug("Creating WmiServices for remote server: %s (user: %s)\n", server.c_str(), user.c_str());

  allocate_locator();

  // Connect to the given target node using the provided credentials.
  HRESULT hr;

  // If node is empty then we are connecting to the local box. In this case don't use the given credentials.
  if (server.size() > 0)
  {
    std::string unc = "\\\\" + server + "\\root\\cimv2";

    CComBSTR nodeString = string2Bstr(unc);
    CComBSTR userString = string2Bstr(user);
    CComBSTR passwordString = string2Bstr(password);
    hr = _locator->ConnectServer(nodeString, userString, passwordString, NULL,
      WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &_services);
  }
  else
    hr = _locator->ConnectServer(L"root\\cimv2", NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT,
      NULL, NULL, &_services);

  if (SUCCEEDED(hr))
  {
    /*
    // Set security levels on a WMI connection
    COAUTHIDENTITY cID;

    cID.User           = (USHORT*) CA2W(user.c_str(), CP_UTF8).m_psz;
    cID.UserLength     = user.size();
    cID.Password       = (USHORT*) CA2W(password.c_str(), CP_UTF8).m_psz;
    cID.PasswordLength = password.size();
    cID.Domain         = NULL;
    cID.DomainLength   = 0;
    cID.Flags          = SEC_WINNT_AUTH_IDENTITY_UNICODE;
*/
    // Set a blanket to our service proxy to establish a security context.
    // Values as recommended (http://msdn.microsoft.com/en-us/library/windows/desktop/aa393620%28v=vs.85%29.aspx).
    hr = CoSetProxyBlanket(
      _services,                   // Indicates the proxy to set
      RPC_C_AUTHN_DEFAULT,         // Authentication service
      RPC_C_AUTHZ_DEFAULT,         // Authorization service
      COLE_DEFAULT_PRINCIPAL,      // Server principal name
      RPC_C_AUTHN_LEVEL_DEFAULT,   // Authentication level
      RPC_C_IMP_LEVEL_IMPERSONATE, // Impersonation level
      COLE_DEFAULT_AUTHINFO,       // client identity
      EOAC_DEFAULT                 // proxy capabilities
    );

    if (FAILED(hr))
    {
      std::string result = wmiResultToString(hr);
      log_error("Could not set proxy blanket for our wmi services. Error: %s\n", result.c_str());
      throw std::runtime_error(_("WMI setting security blanket failed.\n"));
    }
  }
  else
  {
    std::string result = wmiResultToString(hr);
    log_error("Could not connect to target machine. Error: %s\n", result.c_str());
    throw std::runtime_error(_("Could not connect to target machine.\n"));
  }
}

//--------------------------------------------------------------------------------------------------

WmiServices::~WmiServices()
{
  log_debug("Destroying services\n");
  deallocate_locator();
}

//--------------------------------------------------------------------------------------------------

void WmiServices::allocate_locator()
{
  log_debug("Allocating wbem locator\n");

  base::MutexLock lock(_locator_mutex);
  if (_locator_refcount == 0)
  {
    HRESULT hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator,
      reinterpret_cast<void**>(&_locator));

    if (FAILED(hr))
    {
      std::string result = wmiResultToString(hr);
      log_error("Could not create wbem locator. Error: %s\n", result.c_str());
      throw std::runtime_error("Internal error: Instantiation of IWbemLocator failed.\n");
    }
  }

  _locator_refcount++;
}

//--------------------------------------------------------------------------------------------------

void WmiServices::deallocate_locator()
{
  log_debug("Deallocating wbem locator\n");

  base::MutexLock lock(_locator_mutex);
  if (_locator_refcount > 0)
  {
    _locator_refcount--;
    if (_locator_refcount == 0)
    {
      _locator->Release();
      _locator = NULL;
    }
  }
}

//--------------------------------------------------------------------------------------------------

/**
 * Executes a wmi query and returns the queried objects as grt dicts.
 *
 * @param query The query to send. It must be of type WQL.
 * @param node The target machine where to execute the query on. Leave blank for localhost.
 * @param user The user name for authentication on a remote box. Ignored for localhost (the current 
 *             user is used in this case).
 * @param password The password for the given user. Also ignore for localhost.
 * @return A list of dictionaries containing an entry for each object returned by the query, with
 *         name/value pairs of object properties.
 */
grt::DictListRef WmiServices::query(grt::GRT* grt, const std::string& query)
{
  log_debug3("Running wmi query: %s\n", query.c_str());

  // Making this function explicitly thread-safe might be unnecessary as we don't have
  // any data which is allocated/deallocated concurrently. But since we know we will be called
  // from different threads we play safe here, as it does not harm either.
  base::MutexLock lock(_locator_mutex);

  grt::DictListRef queryResult(grt);

  // Execute the given query.
  CComPtr<IEnumWbemClassObject> enumerator;
  CComBSTR converted_query = string2Bstr(query);
  HRESULT hr = _services->ExecQuery(L"WQL", converted_query, WBEM_FLAG_FORWARD_ONLY, NULL, &enumerator);

  if (SUCCEEDED(hr))
  {
    // We also need to set a security context for the enumerator or the next code will fail
    // with "access denied" on remote boxes.
    hr = CoSetProxyBlanket(enumerator, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
      RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

    // Read the returned results and create our own response.
    ULONG count = 0;
    while (true)
    {
      CComPtr<IWbemClassObject> wbemObject = NULL;
      hr = enumerator->Next(WBEM_INFINITE, 1L, &wbemObject, &count);
      if (FAILED(hr))
        throw std::runtime_error(_("WMI enumeration failed.\n\n") + wmiResultToString(hr));

      if (count == 0)
        break;

      SAFEARRAY* names;
      wbemObject->GetNames(NULL, WBEM_FLAG_NONSYSTEM_ONLY, NULL, &names);

      long lowBound, highBound;
      SafeArrayGetLBound(names, 1, &lowBound);
      SafeArrayGetUBound(names, 1, &highBound);

      DictRef resultNames(grt);
      for (long i = lowBound; i <= highBound; i++)
      {
        CComBSTR name;
        SafeArrayGetElement(names, &i, &name);
        CW2A nameString(name, CP_UTF8);

        // Read the actual value for the given property.
        VARIANT value;
        hr = wbemObject->Get(name, 0, &value, NULL, NULL);

        if (SUCCEEDED(hr))
        {
          // In order to ease the value transport everything is converted to a string.
          resultNames.gset((LPSTR)nameString, variant2string(value));

          VariantClear(&value);
        }
        else
        {
          char *name_ = _com_util::ConvertBSTRToString(name);

          std::string result = wmiResultToString(hr);
          log_error("Couldn't get the value for %s. Error: %s\n", name_, result.c_str());
          delete [] name_;
        }
      }
      SafeArrayDestroy(names);

      queryResult.insert(resultNames);
    }
  }
  else
  {
    std::string result = wmiResultToString(hr);
    log_error("Query execution failed. Error: %s\n", result.c_str());
    throw std::runtime_error("WMI query execution failed");
  }

  return queryResult;
}

//--------------------------------------------------------------------------------------------------

/**
 * Allows to work with a Windows service locally or remotely. The result depends on the action.
 *
 * @param service The display name of the service (as stored in the server instance) to act on.
 * @param action The action to execute. Supported are:
 *   - status: return the status of the service
 *   - start: start the service if it is not running.
 *   - stop: stop a running service.
 * @return A string describing the outcome of the action.
 *   - for status: either running, stopping, starting, stopped, unknown
 *   - for start: either completed, already-running, already-starting, stopping, error
 *   - for stop: either completed, already-stopped, already-stopping, starting, error
 */
std::string WmiServices::serviceControl(const std::string& service, const std::string& action)
{
  log_debug3("Running wmi service control query for service: %s (action: %s)\n", service.c_str(), action.c_str());

  base::MutexLock lock(_locator_mutex);

  CComBSTR instancePath = string2Bstr("Win32_Service.Name='" + service + "'");

  CComPtr<IWbemClassObject> serviceInstance;
  HRESULT hr = _services->GetObject(instancePath, 0, NULL, &serviceInstance, NULL);
  if (FAILED(hr))
  {
    std::string result = wmiResultToString(hr);
    log_error("Query execution failed. Error: %s\n", result.c_str());
    return "error, see log";
  }

  VARIANT value;
  hr = serviceInstance->Get(L"State", 0, &value, NULL, NULL);
  if (FAILED(hr))
  {
    std::string result = wmiResultToString(hr);
    log_error("Could not get state value for the service. Error: %s\n", result.c_str());
    return "unknown";
  }

  std::string state = base::tolower(variant2string(value));
  VariantClear(&value);

  if (action == "status")
    return state;
  else
  {
    CComBSTR methodName;
    std::string waitState;
    std::string expectedState;
    if (action == "start")
    {
      if (state == "running")
        return "already-running";
      if (state == "stop pending")
        return "stopping";
      if (state == "start pending")
        return "already-starting";
      if (state != "stopped")
        return "error";

      methodName = "StartService";
      waitState = "start pending";
      expectedState = "running";
    }
    else
      if (action == "stop")
      {
        if (state == "stopped")
          return "already-stopped";
        if (state == "stop pending")
          return "stopping";
        if (state == "start pending")
          return "starting";
        if (state != "running")
          return "error";

        methodName = "StopService";
        waitState = "stop pending";
        expectedState = "stopped";
      }

    if (methodName.Length() > 0)
    {
      CComBSTR serviceClassPath = "Win32_Service";
      CComPtr<IWbemClassObject> serviceClass;
      CComPtr<IWbemClassObject> outInstance;
      CComPtr<IWbemClassObject> inClass;
      CComPtr<IWbemClassObject> inInstance;
      CComPtr<IWbemClassObject> outClass;

      hr = _services->GetObject(serviceClassPath, 0, NULL, &serviceClass, NULL);
      if (SUCCEEDED(hr))
        hr = serviceClass->GetMethod(methodName, 0, &inClass, &outClass);
      else
      {
        char *serviceClassPath_ = _com_util::ConvertBSTRToString(serviceClassPath);
        std::string result = wmiResultToString(hr);
        log_error("Could not get object for service class path: %s. Error: %s\n", serviceClassPath_, result.c_str());
        delete [] serviceClassPath_;
      }

      if (SUCCEEDED(hr) && inClass)
        hr = inClass->SpawnInstance(0, &inInstance);
      else
      {
        char *methodName_ = _com_util::ConvertBSTRToString(methodName);
        std::string result = wmiResultToString(hr);
        log_error("Could not get in/out class for method: %s. Error: %s\n", methodName_, result.c_str());
        delete [] methodName_;
      }

      if (SUCCEEDED(hr))
        hr = _services->ExecMethod(instancePath, methodName, 0, NULL, inInstance, &outInstance, NULL);
      else
      {
        std::string result = wmiResultToString(hr);
        log_error("Could not spawn in-class instance. Error: %s\n", result.c_str());
      }

      if (FAILED(hr))
      {
        char *serviceClassPath_ = _com_util::ConvertBSTRToString(serviceClassPath);
        char *methodName_ = _com_util::ConvertBSTRToString(methodName);
        std::string result = wmiResultToString(hr);
        log_error("Could not execute method %d at path %s. Error: %s\n", methodName_,
          serviceClassPath_, result.c_str());
        delete [] methodName_;
        delete [] serviceClassPath_;

        return "error, see log";
      }

      // Try to figure out what happened if the call as such succeeded but returned an error code.
      // Service methods return uint32 error codes.
      VARIANT returnValue;
      hr = outInstance->Get(L"ReturnValue", 0, &returnValue, NULL, NULL);

      if (FAILED(hr))
      {
        std::string result = wmiResultToString(hr);
        log_error("Could not get the return value of the query. Error: %s\n", result.c_str());

        return "error, see log";
      }

      if (returnValue.vt != VT_EMPTY)
      {
        unsigned int result = V_UI4(&returnValue);
        VariantClear(&returnValue);
        if (result != 0)
        {
          std::string text =  serviceResultToString(result);
          log_error("Variant conversion for return value failed. Error: %s\n", text.c_str());
          
          return "error, see log";
        }
      }

      // So far everything worked fine. Now check the service if it changed as we intended.
      // Wait in a loop with increasing time steps for the result. If there was not the expected
      // change after at most 34 secs then assume an error and return.
      int i = 10;
      int sleepTime = 250; // Start with 1/4 sec steps, to return as quick as possible if things are fine.
      do
      {
        Sleep(sleepTime);

        VARIANT value;
        hr = serviceInstance->Get(L"State", 0, &value, NULL, NULL);
        if (FAILED(hr))
        {
          std::string result = wmiResultToString(hr);
          log_error("Could not get state value for the service. Error: %s\n", result.c_str());

          return "unknown";
        }

        state = base::tolower(variant2string(value));
        VariantClear(&value);

        if (state != waitState)
          break;

        if (--i == 0)
        {
          i = 10;
          sleepTime *= 2; // Double the time we wait for the next check of the service.
          if (sleepTime >= 4000)
            break;
        }
      } while (true);

      if (state != expectedState)
      {
        log_error("Timeout waiting for the service to change status. Returning error to caller.\n");
        return "error";
      }

      return "completed";
    }
  }

  return "unknown";
}

//--------------------------------------------------------------------------------------------------

/**
 * Retrieves operating system values like total available memory, OS description, boot device etc.
 *
 * @param what Specifies which value to query and return. Supported are all properties which belong
 * to the Win32_OperatingSystem class (see http://msdn.microsoft.com/en-us/library/aa394239%28VS.85%29.aspx).
 */
std::string WmiServices::systemStat(const std::string& what)
{
  log_debug3("Running wmi system stat call (what: %s)\n", what.c_str());

  base::MutexLock lock(_locator_mutex);

  CComBSTR instancePath = string2Bstr("Win32_OperatingSystem");

  CComPtr<IEnumWbemClassObject> enumerator;
  HRESULT hr = _services->ExecQuery(L"WQL", L"select * from Win32_OperatingSystem", WBEM_FLAG_FORWARD_ONLY, NULL, &enumerator);

  std::string result = "-1";
  if (SUCCEEDED(hr))
  {
    hr = CoSetProxyBlanket(enumerator, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
      RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

    CComPtr<IWbemClassObject> wbemObject = NULL;
    ULONG count = 0;
    hr = enumerator->Next(WBEM_INFINITE, 1L, &wbemObject, &count);
    if (FAILED(hr) || count == 0)
      return "-1";

    CComBSTR propertyName = string2Bstr(what);
    VARIANT value;
    hr = wbemObject->Get(propertyName, 0, &value, NULL, NULL);

    if (SUCCEEDED(hr))
    {
      result = base::tolower(variant2string(value));
      VariantClear(&value);
    }
    else
    {
      char *propertyName_ = _com_util::ConvertBSTRToString(propertyName);

      std::string result = wmiResultToString(hr);
      log_error("Could not get the value for property %s. Error: %s\n", propertyName_, result.c_str());
      delete [] propertyName_;
    }
  }
  else
  {
    std::string result = wmiResultToString(hr);
    log_error("Could not run the system stat query. Error: %s\n", result.c_str());
  }


  return result;
}

//--------------------------------------------------------------------------------------------------

WmiMonitor* WmiServices::startMonitoring(const std::string& parameter)
{
  return new WmiMonitor(_services, parameter);
}

//--------------------------------------------------------------------------------------------------

void wmi::WmiServices::stopMonitoring(WmiMonitor* monitor)
{
  delete monitor;
}

//--------------------------------------------------------------------------------------------------