summaryrefslogtreecommitdiff
path: root/lib/wmi.c
blob: 44c1d75e9ab8f8e06277df613e63d99ff8126234 (plain)
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
/*
 * Copyright (c) 2016 Cloudbase Solutions Srl
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <config.h>
#include "wmi.h"
#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>
#include "openvswitch/vlog.h"
#include "util.h"

VLOG_DEFINE_THIS_MODULE(wmi);

/* WMI Job values. */
enum job_status
{
    job_starting = 3,
    job_running = 4,
    job_completed = 7,
    job_wait = 4096
};

static char *
sanitize_port_name(char *name)
{
    char *p1, *p2;
    p1 = p2 = name;

    while (*p1) {
        if ((*p1) == '\'' || (*p1) == '\"') {
            p1++;
        } else {
            *p2 = *p1;
            p2++;
            p1++;
        }
    }
    *p2 = '\0';
    return name;
}

/* This function will output the appropriate message for a given HRESULT.*/
static void
get_hres_error(HRESULT hres)
{
    char *error_msg = NULL;

    if (FACILITY_WINDOWS == HRESULT_FACILITY(hres)) {
        hres = HRESULT_CODE(hres);
    }

    VLOG_ERR("%s", ovs_format_message(hres));
}

static boolean
check_return_value(HRESULT hres)
{
    if (FAILED(hres)) {
        get_hres_error(hres);
        return false;
    }

    return true;
}

static HRESULT
get_variant_value(IWbemClassObject *pcls_obj, wchar_t *field_name,
                  VARIANT *value)
{
    HRESULT hres;

    VariantInit(value);

    hres = pcls_obj->lpVtbl->Get(pcls_obj, field_name, 0, value, 0, 0);

    if (FAILED(hres)) {
        VariantClear(value);
    }

    return hres;
}

/* This function retrieves the uint16_t value from a given class object with
 * the field name field_name. */
static HRESULT
get_uint16_t_value(IWbemClassObject *pcls_obj, wchar_t *field_name,
                   uint16_t *value)
{
    VARIANT vt_prop;
    HRESULT hres = get_variant_value(pcls_obj, field_name, &vt_prop);
    *value = V_UI2(&vt_prop);

    return hres;
}

/* This function retrieves the unsigned int values from a given class object
 * with the field name field_name. */
static HRESULT
get_uint_value(IWbemClassObject *pcls_obj, wchar_t *field_name,
               unsigned int *value)
{
    VARIANT vt_prop;
    HRESULT hres = get_variant_value(pcls_obj, field_name, &vt_prop);
    *value = V_UI4(&vt_prop);

    return hres;
}

/* This function retrieves the unsigned short value from a given class object
 * with the field name field_name. */
static HRESULT
get_ushort_value(IWbemClassObject *pcls_obj, wchar_t *field_name,
                 unsigned short *value)
{
    VARIANT vt_prop;
    HRESULT hres = get_variant_value(pcls_obj, field_name, &vt_prop);
    *value = V_UI2(&vt_prop);

    return hres;
}

/* This function retrieves the BSTR value from a given class object with
 * the field name field_name, to a preallocated destination dest and with the
 * maximum length max_dest_lgth. */
static HRESULT
get_str_value(IWbemClassObject *pcls_obj, wchar_t *field_name, wchar_t *dest,
              int max_dest_lgth)
{
    VARIANT vt_prop;
    HRESULT hres = get_variant_value(pcls_obj, field_name, &vt_prop);

    if (wcscpy_s(dest, max_dest_lgth, vt_prop.bstrVal)) {
        VariantClear(&vt_prop);
        VLOG_WARN("get_str_value, wcscpy_s failed :%s", ovs_strerror(errno));
        return WBEM_E_FAILED;
    }

    VariantClear(&vt_prop);
    return S_OK;
}

/* This function waits for a WMI job to finish and retrieves the error code
 * if the job failed */
static HRESULT
wait_for_job(IWbemServices *psvc, wchar_t *job_path)
{
    IWbemClassObject *pcls_obj = NULL;
    HRESULT retval = 0;
    uint16_t job_state = 0;
    uint16_t error = 0;

    do {
        if(!check_return_value(psvc->lpVtbl->GetObject(psvc, job_path, 0, NULL,
                                                       &pcls_obj, NULL))) {
            retval = WBEM_E_FAILED;
            break;
        }

        retval = get_uint16_t_value(pcls_obj, L"JobState", &job_state);
        if (FAILED(retval)) {
            break;
        }

        if (job_state == job_starting || job_state == job_running) {
            Sleep(200);
        } else if (job_state == job_completed) {
            break;
        } else {
            /* Error occurred. */
            retval = get_uint16_t_value(pcls_obj, L"ErrorCode", &error);
            if (FAILED(retval)) {
                break;
            }
            VLOG_WARN("Job failed with error: %d", error);
            retval = WBEM_E_FAILED;;
            break;
        }

        if (pcls_obj != NULL) {
            pcls_obj->lpVtbl->Release(pcls_obj);
            pcls_obj = NULL;
        }
    } while(TRUE);

    if (pcls_obj != NULL) {
        pcls_obj->lpVtbl->Release(pcls_obj);
        pcls_obj = NULL;
    }

    return retval;
}

/* This function will initialize DCOM retrieving the WMI locator's ploc and
 * the context associated to it. */
static boolean
initialize_wmi(IWbemLocator **ploc, IWbemContext **pcontext)
{
    HRESULT hres = 0;

    /* Initialize COM. */
    hres = CoInitialize(NULL);

    if (FAILED(hres)) {
        return false;
    }

    /* Initialize COM security. */
    hres = CoInitializeSecurity(NULL,
                                -1,
                                NULL,
                                NULL,
                                RPC_C_AUTHN_LEVEL_DEFAULT,
                                RPC_C_IMP_LEVEL_IMPERSONATE,
                                NULL,
                                EOAC_NONE,
                                NULL);

    if (FAILED(hres)) {
        return false;
    }

    /* Fill context. */
    hres = CoCreateInstance(&CLSID_WbemContext,
                            NULL,
                            CLSCTX_INPROC_SERVER,
                            &IID_IWbemContext,
                            (void**)pcontext);

    if (FAILED(hres)) {
        return false;
    }

    fill_context(*pcontext);

    /* Initialize locator's (ploc) to WMI. */
    hres = CoCreateInstance(&CLSID_WbemLocator,
                            NULL,
                            CLSCTX_INPROC_SERVER,
                            &IID_IWbemLocator,
                            (LPVOID *)ploc);

    if (FAILED(hres)) {
        return false;
    }

    return true;
}

/* This function connects the WMI locator's ploc to a given WMI provider
 * defined in server and also sets the required security levels for a local
 * connection to it. */
static boolean
connect_set_security(IWbemLocator *ploc, IWbemContext *pcontext,
                     wchar_t *server, IWbemServices **psvc)
{
    HRESULT hres = 0;

   /* Connect to server. */
    hres = ploc->lpVtbl->ConnectServer(ploc,
                                       server,
                                       NULL,
                                       NULL,
                                       0,
                                       0,
                                       0,
                                       pcontext,
                                       psvc);

    if (FAILED(hres)) {
        return false;
    }

    /* Set security levels. */
    hres = CoSetProxyBlanket((IUnknown *) *psvc,
                             RPC_C_AUTHN_WINNT,
                             RPC_C_AUTHZ_NONE,
                             NULL,
                             RPC_C_AUTHN_LEVEL_CALL,
                             RPC_C_IMP_LEVEL_IMPERSONATE,
                             NULL,
                             EOAC_NONE);

    if (FAILED(hres)) {
        return false;
    }

    return true;
}

/* This function retrieves the first class object of a given enumeration
 * outputted by a query and fails if it could not retrieve the object or there
 * was no object to retrieve */
static boolean
get_first_element(IEnumWbemClassObject *penumerate,
                  IWbemClassObject **pcls_obj)
{
    unsigned long retval = 0;

    if (penumerate == NULL) {
        VLOG_WARN("Enumeration Class Object is NULL. Cannot get the first"
                  "object");
        return false;
    }

    HRESULT hres = penumerate->lpVtbl->Next(penumerate, WBEM_INFINITE, 1,
                                            pcls_obj, &retval);


    if (!check_return_value(hres) || retval == 0) {
        return false;
    }

    return true;
}

/* This function is a wrapper that transforms a char * into a wchar_t * */
static boolean
tranform_wide(char *name, wchar_t *wide_name)
{
    unsigned long size = strlen(name) + 1;
    long long ret = 0;

    if (wide_name == NULL) {
        VLOG_WARN("Provided wide string is NULL");
        return false;
    }

    ret = mbstowcs(wide_name, name, size);

    if (ret == -1) {
        VLOG_WARN("Invalid multibyte character is encountered");
        return false;
    } else if (ret == size) {
        VLOG_WARN("Returned wide string not NULL terminated");
        return false;
    }

    return true;
}

#define WMI_QUERY_COUNT 2048

/* This function will delete a switch internal port with a given name as input
 * executing "RemoveResourceSettings" as per documentation:
 * https://msdn.microsoft.com/en-us/library/hh850277%28v=vs.85%29.aspx
 * allocating the data and populating the needed fields to execute the
 * method */
boolean
delete_wmi_port(char *name)
{
    HRESULT hres = 0;
    boolean retval = true;

    IWbemLocator *ploc = NULL;
    IWbemServices *psvc = NULL;
    IWbemContext *pcontext = NULL;
    IWbemClassObject *pclass_instance = NULL;
    IWbemClassObject *pinput_params = NULL;
    IWbemClassObject *pcls_obj = NULL;
    IWbemClassObject *pout_params = NULL;
    IEnumWbemClassObject *penumerate = NULL;

    sanitize_port_name(name);
    VARIANT vt_prop;
    VARIANT variant_array;
    wchar_t *wide_name = NULL;
    VariantInit(&vt_prop);
    VariantInit(&variant_array);

    LONG count[1];
    SAFEARRAY* psa = SafeArrayCreateVector(VT_BSTR, 0, 1);
    if (psa == NULL) {
        VLOG_WARN("Could not allocate memory for a SAFEARRAY");
        retval = false;
        goto error;
    }

    if (!initialize_wmi(&ploc, &pcontext)) {
        VLOG_WARN("Could not initialize DCOM");
        retval = false;
        goto error;
    }

    if (!connect_set_security(ploc, pcontext, L"Root\\Virtualization\\v2",
                              &psvc)) {
        VLOG_WARN("Could not connect and set security for virtualization");
        retval = false;
        goto error;
    }


    /* Get the port with the element name equal to the name input. */
    wchar_t internal_port_query[WMI_QUERY_COUNT] = L"SELECT * from "
        L"Msvm_EthernetPortAllocationSettingData  WHERE ElementName = \"" ;

    wide_name = xmalloc((strlen(name) + 1) * sizeof(wchar_t));

    if (!tranform_wide(name, wide_name)) {
        retval = false;
        goto error;
    }
    wcscat_s(internal_port_query, WMI_QUERY_COUNT, wide_name);

    wcscat_s(internal_port_query, WMI_QUERY_COUNT, L"\"");

    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   internal_port_query,
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    /* Get the element path on the switch which will be deleted. */
    if (!get_first_element(penumerate, &pcls_obj)) {
        retval = false;
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;

    hres = pcls_obj->lpVtbl->Get(pcls_obj, L"__PATH", 0, &vt_prop, 0, 0);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    pcls_obj->lpVtbl->Release(pcls_obj);
    pcls_obj = NULL;

    /* Get the class object and the parameters it can have. */
    hres = psvc->lpVtbl->GetObject(psvc,
        L"Msvm_VirtualEthernetSwitchManagementService", 0, NULL, &pcls_obj,
        NULL);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    hres = pcls_obj->lpVtbl->GetMethod(pcls_obj, L"RemoveResourceSettings", 0,
                                       &pinput_params, NULL);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    pcls_obj->lpVtbl->Release(pcls_obj);
    pcls_obj = NULL;

    hres = pinput_params->lpVtbl->SpawnInstance(pinput_params, 0,
                                                &pclass_instance);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    count[0] = 0;

    hres = SafeArrayPutElement(psa, count, vt_prop.bstrVal);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    VariantClear(&vt_prop);
    VariantInit(&vt_prop);
    variant_array.vt = VT_ARRAY | VT_BSTR;
    variant_array.parray = psa;

    hres = pclass_instance->lpVtbl->Put(pclass_instance, L"ResourceSettings", 0,
                                        &variant_array, 0);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    /* Get the object of the Msvm_VirtualEthernetSwitchManagementService which
     * we need to invoke the port deletion. */
    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   L"SELECT * FROM "
                                   L"Msvm_VirtualEthernetSwitchManagementService",
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (!get_first_element(penumerate, &pcls_obj)) {
        retval = false;
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;

    hres = pcls_obj->lpVtbl->Get(pcls_obj, L"__PATH", 0, &vt_prop, 0, 0);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    pcls_obj->lpVtbl->Release(pcls_obj);
    pcls_obj = NULL;

    /* Invoke the delete port method. */
    hres = psvc->lpVtbl->ExecMethod(psvc, vt_prop.bstrVal,
                                    L"RemoveResourceSettings", 0,
                                    pcontext, pclass_instance, &pout_params,
                                    NULL);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    VariantClear(&vt_prop);
    VariantInit(&vt_prop);

    hres = pout_params->lpVtbl->Get(pout_params, L"ReturnValue", 0,
                                    &vt_prop, NULL, 0);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    unsigned int retvalue = 0;
    hres = get_uint_value(pout_params, L"ReturnValue", &retvalue);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (retvalue != 0 && retvalue != job_wait) {
        retval = false;
        goto error;
    }

    if (retvalue == job_wait) {
        WCHAR job_path[2048];
        hres = get_str_value(pout_params, L"Job", job_path,
                             sizeof(job_path) / sizeof(WCHAR));
        if (FAILED(hres)) {
            retval = false;
            goto error;
    }
        hres = wait_for_job(psvc, job_path);
        if (FAILED(hres)) {
            retval = false;
        }
    }

error:
    VariantClear(&vt_prop);

    if (pcontext != NULL) {
        pcontext->lpVtbl->Release(pcontext);
        pcontext = NULL;
    }
    if (psa != NULL) {
        SafeArrayDestroy(psa);
        psa = NULL;
    }
    if (pcls_obj != NULL) {
        pcls_obj->lpVtbl->Release(pcls_obj);
        pcls_obj = NULL;
    }
    if (wide_name != NULL) {
        free(wide_name);
        wide_name = NULL;
    }
    if (!retval) {
        get_hres_error(hres);
    }
    if (pinput_params != NULL) {
        pinput_params->lpVtbl->Release(pinput_params);
        pinput_params = NULL;
    }
    if (pout_params != NULL) {
        pout_params->lpVtbl->Release(pout_params);
        pout_params = NULL;
    }
    if (psvc != NULL) {
        psvc->lpVtbl->Release(psvc);
        psvc = NULL;
    }
    if (ploc != NULL) {
        ploc->lpVtbl->Release(ploc);
        ploc = NULL;
    }
    if (pclass_instance != NULL) {
        pclass_instance->lpVtbl->Release(pclass_instance);
        pclass_instance = NULL;
    }
    if (penumerate != NULL) {
        penumerate->lpVtbl->Release(penumerate);
        penumerate = NULL;
    }

    CoUninitialize();
    return retval;
}


/* This function will create an internal port on the switch given a given name
 * executing the method AddResourceSettings as per documentation:
 * https://msdn.microsoft.com/en-us/library/hh850019%28v=vs.85%29.aspx.
 * It will verify if the port is already defined, in which case it will use
 * the specific port, and if the forwarding extension "Open vSwitch Extension"
 * is enabled and running only on a single switch.
 * After the port is created and bound to the switch we will disable the
 * created net adapter and rename it to match the OVS bridge name .*/
boolean
create_wmi_port(char *name) {
    HRESULT hres = 0;
    boolean retval = true;

    BSTR text_object_string = NULL;

    IWbemLocator *ploc = NULL;
    IWbemContext *pcontext = NULL;
    IWbemServices *psvc = NULL;
    IEnumWbemClassObject *penumerate = NULL;
    IWbemClassObject *default_settings_data = NULL;
    IWbemClassObject *default_system = NULL;
    IWbemClassObject *pcls_obj = NULL;
    IWbemClassObject *pclass = NULL;
    IWbemClassObject *pinput_params = NULL;
    IWbemClassObject *pclass_instance = NULL;
    IWbemObjectTextSrc *text_object = NULL;
    IWbemClassObject *pout_params = NULL;

    wchar_t *wide_name = NULL;
    VARIANT vt_prop;
    VARIANT switch_setting_path;
    VARIANT new_name;
    SAFEARRAY *psa = SafeArrayCreateVector(VT_BSTR, 0, 1);
    VARIANT variant_array;
    LONG count[1];

    VariantInit(&vt_prop);
    VariantInit(&switch_setting_path);
    sanitize_port_name(name);

    if (psa == NULL) {
        VLOG_WARN("Could not allocate memory for a SAFEARRAY");
        retval = false;
        goto error;
    }

    if (!initialize_wmi(&ploc, &pcontext)) {
        VLOG_WARN("Could not initialize DCOM");
        retval = false;
        goto error;
    }

    if (!connect_set_security(ploc, pcontext, L"Root\\Virtualization\\v2",
                              &psvc)) {
        VLOG_WARN("Could not connect and set security for virtualization");
        retval = false;
        goto error;
    }

    /* Check if the element already exists on the switch. */
    wchar_t internal_port_query[WMI_QUERY_COUNT] = L"SELECT * FROM "
    L"CIM_EthernetPort WHERE ElementName = \"";

    wide_name = xmalloc((strlen(name) + 1) * sizeof(wchar_t));

    if (!tranform_wide(name, wide_name)) {
        retval = false;
        goto error;
    }

    wcscat_s(internal_port_query, WMI_QUERY_COUNT, wide_name);

    wcscat_s(internal_port_query, WMI_QUERY_COUNT, L"\"");
    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   internal_port_query,
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (get_first_element(penumerate, &pcls_obj)) {
        VLOG_WARN("Port with name: %s already defined on the switch", name);
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;

    /* Check if the extension is enabled and running.  Also check if the
     * the extension is enabled on more than one switch. */
    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   L"SELECT * "
                                   L"FROM Msvm_EthernetSwitchExtension "
                                   L"WHERE "
                                   L"ElementName=\"Open vSwitch Extension\" "
                                   L"AND EnabledState=2 "
                                   L"AND HealthState=5",
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (!get_first_element(penumerate, &pcls_obj)) {
        VLOG_WARN("Open vSwitch Extension is not enabled on any switch");
        retval = false;
        goto error;
    }
    wcscpy_s(internal_port_query, WMI_QUERY_COUNT,
             L"SELECT * FROM Msvm_VirtualEthernetSwitch WHERE Name = \"");

    hres = pcls_obj->lpVtbl->Get(pcls_obj, L"SystemName", 0,
                                 &vt_prop, 0, 0);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    wcscat_s(internal_port_query, WMI_QUERY_COUNT,
             vt_prop.bstrVal);

    VariantClear(&vt_prop);
    pcls_obj->lpVtbl->Release(pcls_obj);
    pcls_obj = NULL;

    if (get_first_element(penumerate, &pcls_obj)) {
        VLOG_WARN("The extension is activated on more than one switch, "
                  "aborting operation. Please activate the extension on a "
                  "single switch");
        retval = false;
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;
    if (pcls_obj != NULL) {
        pcls_obj->lpVtbl->Release(pcls_obj);
        pcls_obj = NULL;
    }

    /* Get the switch object on which the extension is activated. */
    wcscat_s(internal_port_query, WMI_QUERY_COUNT, L"\"");
    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   internal_port_query,
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (!get_first_element(penumerate, &pcls_obj)) {
        VLOG_WARN("Could not get the switch object on which the extension is"
                  "activated");
        retval = false;
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;

    hres = pcls_obj->lpVtbl->Get(pcls_obj, L"ElementName", 0, &vt_prop, 0, 0);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    wcscpy_s(internal_port_query, WMI_QUERY_COUNT,
             L"SELECT * FROM Msvm_VirtualEthernetSwitchSettingData WHERE "
             L"ElementName = \"");

    wcscat_s(internal_port_query, WMI_QUERY_COUNT,
             vt_prop.bstrVal);
    VariantClear(&vt_prop);

    hres = pcls_obj->lpVtbl->Get(pcls_obj, L"Name", 0, &vt_prop, 0, 0);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    pcls_obj->lpVtbl->Release(pcls_obj);
    pcls_obj = NULL;

    /* Should be enough to give the InstanceID, from msdn documentation:
     * Uniquely identifies an instance of this class. This property is
     * inherited from CIM_SettingData and is always
     * set to "Microsoft:GUID\DeviceSpecificData". */
    wcscat_s(internal_port_query, WMI_QUERY_COUNT,
             L"\" AND InstanceID  = \"Microsoft:");
    wcscat_s(internal_port_query, WMI_QUERY_COUNT,
             vt_prop.bstrVal);
    wcscat_s(internal_port_query, WMI_QUERY_COUNT,
             L"\"");

    VariantClear(&vt_prop);

    /* Retrieve the Msvm_VirtualEthernetSwitchSettingData pinned to the switch
     * object on which the extension is activated. */
    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   internal_port_query,
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (!get_first_element(penumerate, &pcls_obj)) {
        VLOG_WARN("Could not get the first "
                  "Msvm_VirtualEthernetSwitchSettingData object");
        retval = false;
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;

    hres = pcls_obj->lpVtbl->Get(pcls_obj, L"__PATH", 0, &switch_setting_path,
                                 0, 0);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    pcls_obj->lpVtbl->Release(pcls_obj);
    pcls_obj = NULL;

    /* Retrieve a default allocation port.  This object will be later filled
     * with optional data to create an switch internal port. */
    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   L"SELECT * FROM "
                                   L"Msvm_EthernetPortAllocationSettingData "
                                   L"WHERE InstanceID LIKE '%%%%\\\\Default' "
                                   L"AND ResourceSubType = "
                                   L"'Microsoft:Hyper-V:Ethernet Connection'",
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (!get_first_element(penumerate, &default_settings_data)) {
        VLOG_WARN("Could not retrieve default allocation port object");
        retval = false;
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;

    /* Retrieve the default computer system on which the port allocation will
     * be hosted.
     * Instead of querying using Description, we can query using InstallDate.
     * From MSDN documentation regarding InstallDate:
     * The date and time the virtual machine configuration was created for
     * a virtual machine, or Null, for a management operating system. */
    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   L"SELECT * FROM Msvm_ComputerSystem WHERE "
                                   L"InstallDate is NULL",
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (!get_first_element(penumerate, &default_system)) {
        VLOG_WARN("Could not retrieve default computer system object");
        retval = false;
        goto error;
    }

    hres = default_system->lpVtbl->Get(default_system, L"__PATH",
                                       0, &vt_prop, 0, 0);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;

    count[0] = 0;
    hres = SafeArrayPutElement(psa, count, vt_prop.bstrVal);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    VariantClear(&vt_prop);
    variant_array.vt = VT_ARRAY | VT_BSTR;
    variant_array.parray = psa;
    hres = default_settings_data->lpVtbl->Put(default_settings_data,
                                              L"HostResource", 0,
                                              &variant_array, 0);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    hres = psvc->lpVtbl->GetObject(psvc,
                                   L"Msvm_VirtualEthernetSwitchManagementService",
                                   0, NULL, &pclass, NULL);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    hres = pclass->lpVtbl->GetMethod(pclass, L"AddResourceSettings", 0,
                                     &pinput_params, NULL);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    hres = pinput_params->lpVtbl->SpawnInstance(pinput_params, 0,
                                                &pclass_instance);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    /* Store the switch setting path retrieved above in the affected
     * configuration field of the class instance. */
    hres = pclass_instance->lpVtbl->Put(pclass_instance,
                                        L"AffectedConfiguration", 0,
                                        &switch_setting_path, 0);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    /* Store the port name in the ElementName field of the default allocation
     * data. */
    vt_prop.vt = VT_BSTR;
    vt_prop.bstrVal = SysAllocString(wide_name);
    hres = default_settings_data->lpVtbl->Put(default_settings_data,
                                              L"ElementName", 0,
                                              &vt_prop, 0);
    VariantClear(&vt_prop);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    /* Retrieve and store the serialized data of the modified default switch
     * settings data. */
    hres = CoCreateInstance(&CLSID_WbemObjectTextSrc,
                            NULL,
                            CLSCTX_INPROC_SERVER,
                            &IID_IWbemObjectTextSrc,
                            (void**)&text_object);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    hres = text_object->lpVtbl->GetText(text_object, 0,
                                        default_settings_data,
                                        WMI_OBJ_TEXT_WMI_DTD_2_0,
                                        pcontext,
                                        &text_object_string);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    hres = SafeArrayDestroy(psa);
    if (FAILED(hres)) {
        VLOG_WARN("Could not clear the data of the array");
        retval = false;
        goto error;
    }

    psa = SafeArrayCreateVector(VT_BSTR, 0, 1);

    if (psa == NULL) {
        VLOG_WARN("Could not allocate memory for a SAFEARRAY");
        retval = false;
        goto error;
    }

    count[0] = 0;
    variant_array.parray = psa;
    hres = SafeArrayPutElement(psa, count, text_object_string);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    hres = pclass_instance->lpVtbl->Put(pclass_instance, L"ResourceSettings",
                                        0, &variant_array, 0);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    /* Get the object of the switch service. */
    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   L"SELECT * FROM "
                                   L"Msvm_VirtualEthernetSwitchManagementService",
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (!get_first_element(penumerate, &pcls_obj)) {
        VLOG_WARN("Could not get the object of the switch service");
        retval = false;
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;

    hres = pcls_obj->lpVtbl->Get(pcls_obj, L"__PATH", 0, &vt_prop, 0, 0);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    pcls_obj->lpVtbl->Release(pcls_obj);
    pcls_obj = NULL;

    /* Try to add the port to the switch. */
    hres = psvc->lpVtbl->ExecMethod(psvc, vt_prop.bstrVal,
                                    L"AddResourceSettings", 0,
                                    pcontext, pclass_instance, &pout_params,
                                    NULL);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    unsigned int retvalue = 0;
    hres = get_uint_value(pout_params, L"ReturnValue", &retvalue);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    if (retvalue != 0 && retvalue != job_wait) {
        retval = false;
        goto error;
    }

    if (retvalue == job_wait) {
        WCHAR job_path[2048];
        hres = get_str_value(pout_params, L"Job", job_path,
                             sizeof(job_path) / sizeof(WCHAR));
        if (FAILED(hres)) {
            retval = false;
            goto error;
        }
        hres = wait_for_job(psvc, job_path);
        if (FAILED(hres)) {
            retval = false;
            goto error;
        }
    }

    pclass->lpVtbl->Release(pclass);
    pclass = NULL;
    pclass_instance->lpVtbl->Release(pclass_instance);
    pclass_instance = NULL;
    pinput_params->lpVtbl->Release(pinput_params);
    pinput_params = NULL;
    psvc->lpVtbl->Release(psvc);
    psvc = NULL;
    VariantClear(&vt_prop);

    if (!connect_set_security(ploc, pcontext, L"Root\\StandardCimv2",
                              &psvc)) {
        VLOG_WARN("Could not connect and set security for CIM");
        retval = false;
        goto error;
    }

    wcscpy_s(internal_port_query, WMI_QUERY_COUNT,
             L"SELECT * FROM MSFT_NetAdapter WHERE Name LIKE '%%");
    wcscat_s(internal_port_query, WMI_QUERY_COUNT, wide_name);
    wcscat_s(internal_port_query, WMI_QUERY_COUNT, L"%%'");

    /* Get the object with the port name equal to name on the CIM. */
    hres = psvc->lpVtbl->ExecQuery(psvc,
                                   L"WQL",
                                   internal_port_query,
                                   WBEM_FLAG_FORWARD_ONLY |
                                   WBEM_FLAG_RETURN_IMMEDIATELY,
                                   NULL,
                                   &penumerate);

    if (!get_first_element(penumerate, &pcls_obj)) {
        VLOG_WARN("Element name: %s not found in CIM", name);
        retval = false;
        goto error;
    }
    penumerate->lpVtbl->Release(penumerate);
    penumerate = NULL;
    pcls_obj->lpVtbl->Get(pcls_obj, L"__PATH", 0, &vt_prop, 0, 0);
    pcls_obj->lpVtbl->Release(pcls_obj);
    pcls_obj = NULL;

    /* Disable the adapter with port name equal with name. */
    hres = psvc->lpVtbl->ExecMethod(psvc, vt_prop.bstrVal, L"Disable", 0,
                                    pcontext, NULL, NULL, NULL);

    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    hres = psvc->lpVtbl->GetObject(psvc, L"MSFT_NetAdapter", 0, NULL, &pclass,
                                   NULL);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    hres = pclass->lpVtbl->GetMethod(pclass, L"Rename", 0, &pinput_params,
                                     NULL);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    hres = pinput_params->lpVtbl->SpawnInstance(pinput_params, 0,
                                                &pclass_instance);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }

    VariantInit(&new_name);
    new_name.vt = VT_BSTR;
    new_name.bstrVal = wide_name;
    hres = pclass_instance->lpVtbl->Put(pclass_instance, L"NewName", 0,
                                        &new_name, 0);
    if (FAILED(hres)) {
        retval = false;
        goto error;
    }
    hres = psvc->lpVtbl->ExecMethod(psvc, vt_prop.bstrVal, L"Rename", 0,
                                    pcontext, pclass_instance, NULL, NULL);
    if (FAILED(hres)) {
        retval = false;
    }

error:
    if (text_object_string != NULL) {
        SysFreeString(text_object_string);
        text_object_string = NULL;
    }
    if (psa != NULL) {
        SafeArrayDestroy(psa);
        psa = NULL;
    }
    if (ploc != NULL) {
        ploc->lpVtbl->Release(ploc);
        ploc = NULL;
    }
    if (pcontext != NULL) {
        pcontext->lpVtbl->Release(pcontext);
        pcontext = NULL;
    }
    if (psvc != NULL) {
        psvc->lpVtbl->Release(psvc);
        psvc = NULL;
    }
    if (penumerate != NULL) {
        penumerate->lpVtbl->Release(penumerate);
        penumerate = NULL;
    }
    if (default_settings_data != NULL) {
        default_settings_data->lpVtbl->Release(default_settings_data);
        default_settings_data = NULL;
    }
    if (default_system != NULL) {
        default_system->lpVtbl->Release(default_system);
        default_system = NULL;
    }
    if (pcls_obj != NULL) {
        pcls_obj->lpVtbl->Release(pcls_obj);
        pcls_obj = NULL;
    }
    if (pclass != NULL) {
        pclass->lpVtbl->Release(pclass);
        pclass = NULL;
    }
    if (pinput_params != NULL) {
        pinput_params->lpVtbl->Release(pinput_params);
        pinput_params = NULL;
    }
    if (pclass_instance != NULL) {
        pclass_instance->lpVtbl->Release(pclass_instance);
        pclass_instance = NULL;
    }
    if (text_object != NULL) {
        text_object->lpVtbl->Release(text_object);
        text_object = NULL;
    }
    if (pout_params != NULL) {
        pout_params->lpVtbl->Release(pout_params);
        pout_params = NULL;
    }
    if (wide_name != NULL) {
        free(wide_name);
        wide_name = NULL;
    }
    VariantClear(&vt_prop);
    VariantClear(&switch_setting_path);

    if (!retval) {
        get_hres_error(hres);
    }
    CoUninitialize();
    return retval;
}