aboutsummaryrefslogtreecommitdiffstats
path: root/api/devmgmt.c
blob: de834958f075fe7561d93ec37a2c49d55093b614 (plain) (blame)
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
/* SPDX-License-Identifier: GPL-2.0
 *
 * Copyright (C) 2018-2020 WireGuard LLC. All Rights Reserved.
 */

#include "pch.h"

#define WINTUN_HWID L"Wintun"
#define WAIT_FOR_REGISTRY_TIMEOUT 10000     /* ms */
#define MAX_POOL_DEVICE_TYPE (MAX_POOL + 8) /* Should accommodate a pool name with " Tunnel" appended */

const static GUID CLASS_NET_GUID = { 0x4d36e972L, 0xe325, 0x11ce, { 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 } };
const static GUID ADAPTER_NET_GUID = { 0xcac88484L,
                                       0x7515,
                                       0x4c03,
                                       { 0x82, 0xe6, 0x71, 0xa8, 0x7a, 0xba, 0xc3, 0x61 } };

/**
 * Retrieves a specified Plug and Play device property.
 *
 * @param DevInfo       A handle to the device information set that contains a device information element that
 *                      represents the device for which to open a registry key.
 *
 * @param DevInfoData   A pointer to a structure that specifies the device information element in DeviceInfoSet.
 *
 * @param Property      The property to be retrieved. One of the SPDRP_* constants.
 *
 * @param PropertyRegDataType  A pointer to a variable that receives the data type of the property that is being
 *                      retrieved. This is one of the standard registry data types. This parameter is optional
 *                      and can be NULL.
 *
 * @param PropertyBuffer  A pointer to a buffer that receives the property that is being retrieved. Must be
 *                      released with HeapFree(GetProcessHeap(), 0, Value) after use.
 *
 * @param PropertySize  A pointer to a variable of type DWORD that receives the property size, in bytes, of the
 *                      PropertyBuffer buffer. This parameter is optional and can be NULL.
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise
 */
static WINTUN_STATUS
GetDeviceRegistryProperty(
    _In_ HDEVINFO DevInfo,
    _In_ SP_DEVINFO_DATA *DevInfoData,
    _In_ DWORD Property,
    _Out_opt_ DWORD *ValueType,
    _Out_ void **Buf,
    _Inout_ DWORD *BufLen)
{
    HANDLE Heap = GetProcessHeap();
    for (;;)
    {
        *Buf = HeapAlloc(Heap, 0, *BufLen);
        if (!*Buf)
            return ERROR_OUTOFMEMORY;
        if (SetupDiGetDeviceRegistryPropertyW(DevInfo, DevInfoData, Property, ValueType, *Buf, *BufLen, BufLen))
            return ERROR_SUCCESS;
        DWORD Result = GetLastError();
        HeapFree(Heap, 0, *Buf);
        if (Result != ERROR_INSUFFICIENT_BUFFER)
            return Result;
    }
}

/**
 * Retrieves a specified Plug and Play device property string.
 *
 * @param DevInfo       A handle to the device information set that contains a device information element that
 *                      represents the device for which to open a registry key.
 *
 * @param DevInfoData   A pointer to a structure that specifies the device information element in DeviceInfoSet.
 *
 * @param Property      The property to be retrieved. One of the SPDRP_* constants.
 *
 * @param PropertyBuffer  A pointer to a string that receives the string that is being retrieved. Must be
 *                      released with HeapFree(GetProcessHeap(), 0, Value) after use.
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise
 */
static WINTUN_STATUS
GetDeviceRegistryString(
    _In_ HDEVINFO DevInfo,
    _In_ SP_DEVINFO_DATA *DevInfoData,
    _In_ DWORD Property,
    _Out_ WCHAR **Buf)
{
    DWORD Result, ValueType, Size = 256 * sizeof(WCHAR);
    Result = GetDeviceRegistryProperty(DevInfo, DevInfoData, Property, &ValueType, Buf, &Size);
    if (Result != ERROR_SUCCESS)
        return Result;
    switch (ValueType)
    {
    case REG_SZ:
    case REG_EXPAND_SZ:
    case REG_MULTI_SZ:
        Result = RegistryGetString(Buf, Size / sizeof(WCHAR), ValueType);
        if (Result != ERROR_SUCCESS)
            HeapFree(GetProcessHeap(), 0, *Buf);
        return Result;
    default:
        HeapFree(GetProcessHeap(), 0, *Buf);
        return ERROR_INVALID_DATATYPE;
    }
}

/**
 * Retrieves a specified Plug and Play device property multi-string.
 *
 * @param DevInfo       A handle to the device information set that contains a device information element that
 *                      represents the device for which to open a registry key.
 *
 * @param DevInfoData   A pointer to a structure that specifies the device information element in DeviceInfoSet.
 *
 * @param Property      The property to be retrieved. One of the SPDRP_* constants.
 *
 * @param PropertyBuffer  A pointer to a multi-string that receives the string that is being retrieved. Must be
 *                      released with HeapFree(GetProcessHeap(), 0, Value) after use.
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise
 */
static WINTUN_STATUS
GetDeviceRegistryMultiString(
    _In_ HDEVINFO DevInfo,
    _In_ SP_DEVINFO_DATA *DevInfoData,
    _In_ DWORD Property,
    _Out_ WCHAR **Buf)
{
    DWORD Result, ValueType, Size = 256 * sizeof(WCHAR);
    Result = GetDeviceRegistryProperty(DevInfo, DevInfoData, Property, &ValueType, Buf, &Size);
    if (Result != ERROR_SUCCESS)
        return Result;
    switch (ValueType)
    {
    case REG_SZ:
    case REG_EXPAND_SZ:
    case REG_MULTI_SZ:
        Result = RegistryGetMultiString(Buf, Size / sizeof(WCHAR), ValueType);
        if (Result != ERROR_SUCCESS)
            HeapFree(GetProcessHeap(), 0, *Buf);
        return Result;
    default:
        HeapFree(GetProcessHeap(), 0, *Buf);
        return ERROR_INVALID_DATATYPE;
    }
}

/**
 * Retrieves driver information detail for a device information set or a particular device information element in the
 * device information set.
 *
 * @param DevInfo       A handle to the device information set that contains a device information element that
 *                      represents the device for which to open a registry key.
 *
 * @param DevInfoData   A pointer to a structure that specifies the device information element in DeviceInfoSet.
 *
 * @param DriverData    A pointer to a structure that specifies the driver information element that represents the
 *                      driver for which to retrieve details.
 *
 * @param DriverDetailData  A pointer to a structure that receives detailed information about the specified driver.
 *                      Must be released with HeapFree(GetProcessHeap(), 0, Value) after use.
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise
 */
static WINTUN_STATUS
GetDriverInfoDetail(
    _In_ HDEVINFO DevInfo,
    _In_ SP_DEVINFO_DATA *DevInfoData,
    _In_ SP_DRVINFO_DATA_W *DriverData,
    _Out_ SP_DRVINFO_DETAIL_DATA_W **DriverDetailData)
{
    HANDLE Heap = GetProcessHeap();
    DWORD Size = sizeof(SP_DRVINFO_DETAIL_DATA_W) + 0x100;
    for (;;)
    {
        *DriverDetailData = HeapAlloc(Heap, 0, Size);
        if (!*DriverDetailData)
            return ERROR_OUTOFMEMORY;
        (*DriverDetailData)->cbSize = sizeof(SP_DRVINFO_DETAIL_DATA_W);
        if (SetupDiGetDriverInfoDetailW(DevInfo, DevInfoData, DriverData, *DriverDetailData, Size, &Size))
            return ERROR_SUCCESS;
        DWORD Result = GetLastError();
        HeapFree(Heap, 0, *DriverDetailData);
        if (Result != ERROR_INSUFFICIENT_BUFFER)
            return Result;
    }
}

/**
 * Tests if any of the hardware IDs match ours.
 *
 * @param Hwids         Multi-string containing a list of hardware IDs
 *
 * @return TRUE on match; FALSE otherwise.
 */
static BOOL
IsOurHardwareID(_In_z_ WCHAR *Hwids)
{
    for (; Hwids[0]; Hwids += wcslen(Hwids) + 1)
        if (!_wcsicmp(Hwids, WINTUN_HWID))
            return TRUE;
    return FALSE;
}

/**
 * Check if the device is using Wintun driver.
 */
static WINTUN_STATUS
IsUsingOurDriver(_In_ HDEVINFO DevInfo, _In_ SP_DEVINFO_DATA *DevInfoData, _Out_ BOOL *IsOurDriver)
{
    if (!SetupDiBuildDriverInfoList(DevInfo, DevInfoData, SPDIT_COMPATDRIVER))
        return GetLastError();
    *IsOurDriver = FALSE;
    HANDLE Heap = GetProcessHeap();
    for (DWORD DriverIndex = 0;; ++DriverIndex)
    {
        SP_DRVINFO_DATA_W DriverData = { .cbSize = sizeof(SP_DRVINFO_DATA_W) };
        if (!SetupDiEnumDriverInfoW(DevInfo, DevInfoData, SPDIT_COMPATDRIVER, DriverIndex, &DriverData))
        {
            if (GetLastError() == ERROR_NO_MORE_ITEMS)
                break;
            continue;
        }
        SP_DRVINFO_DETAIL_DATA_W *DriverDetailData;
        if (GetDriverInfoDetail(DevInfo, DevInfoData, &DriverData, &DriverDetailData) != ERROR_SUCCESS)
            continue;
        if (DriverDetailData->CompatIDsOffset > 1 && !_wcsicmp(DriverDetailData->HardwareID, WINTUN_HWID) ||
            DriverDetailData->CompatIDsLength &&
                IsOurHardwareID(DriverDetailData->HardwareID + DriverDetailData->CompatIDsOffset))
        {
            HeapFree(Heap, 0, DriverDetailData);
            *IsOurDriver = TRUE;
            break;
        }
        HeapFree(Heap, 0, DriverDetailData);
    }
    SetupDiDestroyDriverInfoList(DevInfo, DevInfoData, SPDIT_COMPATDRIVER);
    return ERROR_SUCCESS;
}

/**
 * Checks device install parameters if a system reboot is required.
 */
static BOOL
CheckReboot(_In_ HDEVINFO DevInfo, _In_ SP_DEVINFO_DATA *DevInfoData)
{
    SP_DEVINSTALL_PARAMS_W DevInstallParams = { .cbSize = sizeof(SP_DEVINSTALL_PARAMS_W) };
    if (!SetupDiGetDeviceInstallParamsW(DevInfo, DevInfoData, &DevInstallParams))
        return FALSE;
    return (DevInstallParams.Flags & (DI_NEEDREBOOT | DI_NEEDRESTART)) != 0;
}

/**
 * Sets device install parameters for a quiet installation.
 */
static WINTUN_STATUS
SetQuietInstall(_In_ HDEVINFO DevInfo, _In_ SP_DEVINFO_DATA *DevInfoData)
{
    SP_DEVINSTALL_PARAMS_W DevInstallParams = { .cbSize = sizeof(SP_DEVINSTALL_PARAMS_W) };
    if (!SetupDiGetDeviceInstallParamsW(DevInfo, DevInfoData, &DevInstallParams))
        return GetLastError();
    DevInstallParams.Flags |= DI_QUIETINSTALL;
    if (!SetupDiSetDeviceInstallParamsW(DevInfo, DevInfoData, &DevInstallParams))
        return GetLastError();
    return ERROR_SUCCESS;
}

/**
 * Returns adapter GUID associated with device.
 *
 * @param DevInfo       A handle to the device information set that contains a device information element that
 *                      represents the device for which to open a registry key.
 *
 * @param DevInfoData   A pointer to a structure that specifies the device information element in DeviceInfoSet.
 *
 * @param CfgInstanceID  Pointer to a GUID to receive the adapter GUID.
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise
 */
static WINTUN_STATUS
GetNetCfgInstanceId(_In_ HDEVINFO DevInfo, _In_ SP_DEVINFO_DATA *DevInfoData, _Out_ GUID *CfgInstanceID)
{
    HKEY Key = SetupDiOpenDevRegKey(DevInfo, DevInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DRV, KEY_QUERY_VALUE);
    if (Key == INVALID_HANDLE_VALUE)
        return GetLastError();
    WCHAR *ValueStr;
    DWORD Result = RegistryQueryString(Key, L"NetCfgInstanceId", &ValueStr);
    if (Result != ERROR_SUCCESS)
        goto cleanupKey;
    Result = SUCCEEDED(CLSIDFromString(ValueStr, CfgInstanceID)) ? ERROR_SUCCESS : ERROR_INVALID_DATA;
    HeapFree(GetProcessHeap(), 0, ValueStr);
cleanupKey:
    RegCloseKey(Key);
    return Result;
}

/**
 * Returns device info list handle and adapter device info data.
 *
 * @param CfgInstanceID  The adapter GUID
 *
 * @param DevInfo       A pointer to receive the handle of the device information set that contains a device information
 *                      element that represents the device. Must be released with SetupDiDestroyDeviceInfoList(*DevInfo)
 *                      after use.
 *
 * @param DevInfoData   A pointer to a structure that receives specification of the device information element in
 *                      DeviceInfoSet.
 *
 * @return ERROR_SUCCESS on success; ERROR_FILE_NOT_FOUND if the device is not found; Win32 error code otherwise
 */
static WINTUN_STATUS
GetDevInfoData(_In_ const GUID *CfgInstanceID, _Out_ HDEVINFO *DevInfo, _Out_ SP_DEVINFO_DATA *DevInfoData)
{
    *DevInfo = SetupDiGetClassDevsExW(&CLASS_NET_GUID, NULL, NULL, DIGCF_PRESENT, NULL, NULL, NULL);
    if (!*DevInfo)
        return GetLastError();
    for (DWORD MemberIndex = 0;; ++MemberIndex)
    {
        DevInfoData->cbSize = sizeof(SP_DEVINFO_DATA);
        if (!SetupDiEnumDeviceInfo(*DevInfo, MemberIndex, DevInfoData))
        {
            if (GetLastError() == ERROR_NO_MORE_ITEMS)
                break;
            continue;
        }
        GUID CfgInstanceID2;
        if (GetNetCfgInstanceId(*DevInfo, DevInfoData, &CfgInstanceID2) == ERROR_SUCCESS &&
            !memcmp(CfgInstanceID, &CfgInstanceID2, sizeof(GUID)))
            return ERROR_SUCCESS;
    }
    SetupDiDestroyDeviceInfoList(*DevInfo);
    return ERROR_FILE_NOT_FOUND;
}

/**
 * Removes numbered suffix from adapter name.
 */
static void
RemoveNumberedSuffix(_In_z_ const WCHAR *Name, _Out_ WCHAR *Removed)
{
    size_t Len = wcslen(Name);
    if (Len && Name[Len - 1] < L'0' || Name[Len - 1] > L'9')
    {
        wmemcpy(Removed, Name, Len + 1);
        return;
    }
    for (size_t i = Len; i--;)
    {
        if (Name[i] >= L'0' && Name[i] <= L'9')
            continue;
        if (Name[i] == L' ')
        {
            wmemcpy(Removed, Name, i);
            Removed[i] = 0;
            return;
        }
        break;
    }
    wmemcpy(Removed, Name, Len + 1);
}

/**
 * Returns pool-specific device type name.
 */
static void
GetPoolDeviceTypeName(_In_z_count_c_(MAX_POOL) const WCHAR *Pool, _Out_cap_c_(MAX_POOL_DEVICE_TYPE) WCHAR *Name)
{
    _snwprintf_s(Name, MAX_POOL_DEVICE_TYPE, _TRUNCATE, L"%.*s Tunnel", MAX_POOL, Pool);
}

/**
 * Checks if SPDRP_DEVICEDESC or SPDRP_FRIENDLYNAME match device type name.
 */
static WINTUN_STATUS
IsPoolMember(
    _In_z_count_c_(MAX_POOL) const WCHAR *Pool,
    _In_ HDEVINFO DevInfo,
    _In_ SP_DEVINFO_DATA *DevInfoData,
    _Out_ BOOL *IsMember)
{
    HANDLE Heap = GetProcessHeap();
    WCHAR *DeviceDesc, *FriendlyName;
    DWORD Result = GetDeviceRegistryString(DevInfo, DevInfoData, SPDRP_DEVICEDESC, &DeviceDesc);
    if (Result != ERROR_SUCCESS)
        return Result;
    Result = GetDeviceRegistryString(DevInfo, DevInfoData, SPDRP_FRIENDLYNAME, &FriendlyName);
    if (Result != ERROR_SUCCESS)
        goto cleanupDeviceDesc;
    WCHAR PoolDeviceTypeName[MAX_POOL_DEVICE_TYPE];
    GetPoolDeviceTypeName(Pool, PoolDeviceTypeName);
    if (!_wcsicmp(FriendlyName, PoolDeviceTypeName) || !_wcsicmp(DeviceDesc, PoolDeviceTypeName))
    {
        *IsMember = TRUE;
        goto cleanupFriendlyName;
    }
    RemoveNumberedSuffix(FriendlyName, FriendlyName);
    RemoveNumberedSuffix(DeviceDesc, DeviceDesc);
    if (!_wcsicmp(FriendlyName, PoolDeviceTypeName) || !_wcsicmp(DeviceDesc, PoolDeviceTypeName))
    {
        *IsMember = TRUE;
        goto cleanupFriendlyName;
    }
    *IsMember = FALSE;
cleanupFriendlyName:
    HeapFree(Heap, 0, FriendlyName);
cleanupDeviceDesc:
    HeapFree(Heap, 0, DeviceDesc);
    return Result;
}

/**
 * Creates a Wintun adapter descriptor and populates it from the device's registry key.
 *
 * @param DevInfo       A handle to the device information set that contains a device information element that
 *                      represents the device for which to open a registry key.
 *
 * @param DevInfoData   A pointer to a structure that specifies the device information element in DeviceInfoSet.
 *
 * @param Pool          Name of the adapter pool
 *
 * @param Adapter       Pointer to a handle to receive the adapter descriptor. Must be released with
 *                      HeapFree(GetProcessHeap(), 0, *Adapter).
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise
 */
static WINTUN_STATUS
CreateAdapterData(
    _In_z_count_c_(MAX_POOL) const WCHAR *Pool,
    _In_ HDEVINFO DevInfo,
    _In_ SP_DEVINFO_DATA *DevInfoData,
    _Out_ WINTUN_ADAPTER **Adapter)
{
    DWORD Result;

    /* Open HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\<class>\<id> registry key. */
    HKEY Key = SetupDiOpenDevRegKey(DevInfo, DevInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DRV, KEY_QUERY_VALUE);
    if (Key == INVALID_HANDLE_VALUE)
        return GetLastError();

    HANDLE Heap = GetProcessHeap();
    *Adapter = HeapAlloc(Heap, 0, sizeof(WINTUN_ADAPTER));
    if (!*Adapter)
    {
        Result = ERROR_OUTOFMEMORY;
        goto cleanupKey;
    }

    /* Read the NetCfgInstanceId value and convert to GUID. */
    WCHAR *ValueStr;
    Result = RegistryQueryString(Key, L"NetCfgInstanceId", &ValueStr);
    if (Result != ERROR_SUCCESS)
        goto cleanupAdapter;
    if (FAILED(CLSIDFromString(ValueStr, &(*Adapter)->CfgInstanceID)))
    {
        HeapFree(GetProcessHeap(), 0, ValueStr);
        Result = ERROR_INVALID_DATA;
        goto cleanupAdapter;
    }
    HeapFree(GetProcessHeap(), 0, ValueStr);

    /* Read the NetLuidIndex value. */
    Result = RegistryQueryDWORD(Key, L"NetLuidIndex", &(*Adapter)->LuidIndex);
    if (Result != ERROR_SUCCESS)
        goto cleanupAdapter;

    /* Read the NetLuidIndex value. */
    Result = RegistryQueryDWORD(Key, L"*IfType", &(*Adapter)->IfType);
    if (Result != ERROR_SUCCESS)
        goto cleanupAdapter;

    DWORD Size;
    if (!SetupDiGetDeviceInstanceIdW(
            DevInfo, DevInfoData, (*Adapter)->DevInstanceID, _countof((*Adapter)->DevInstanceID), &Size))
    {
        Result = GetLastError();
        goto cleanupAdapter;
    }

    wcscpy_s((*Adapter)->Pool, _countof((*Adapter)->Pool), Pool);
    Result = ERROR_SUCCESS;

cleanupAdapter:
    if (Result != ERROR_SUCCESS)
        HeapFree(Heap, 0, *Adapter);
cleanupKey:
    RegCloseKey(Key);
    return Result;
}

/**
 * Returns the device-level registry key path.
 */
static void
GetDeviceRegPath(_In_ const WINTUN_ADAPTER *Adapter, _Out_cap_c_(MAX_REG_PATH) WCHAR *Path)
{
    _snwprintf_s(
        Path,
        MAX_REG_PATH,
        _TRUNCATE,
        L"SYSTEM\\CurrentControlSet\\Enum\\%.*s",
        MAX_INSTANCE_ID,
        Adapter->DevInstanceID);
}

/**
 * Returns the adapter-specific TCP/IP network registry key path.
 */
static void
GetTcpipAdapterRegPath(_In_ const WINTUN_ADAPTER *Adapter, _Out_cap_c_(MAX_REG_PATH) WCHAR *Path)
{
    WCHAR Guid[MAX_GUID_STRING_LEN];
    _snwprintf_s(
        Path,
        MAX_REG_PATH,
        _TRUNCATE,
        L"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Adapters\\%.*s",
        StringFromGUID2(&Adapter->CfgInstanceID, Guid, _countof(Guid)),
        Guid);
}

/**
 * Returns the interface-specific TCP/IP network registry key path.
 */
static WINTUN_STATUS
GetTcpipInterfaceRegPath(_In_ const WINTUN_ADAPTER *Adapter, _Out_cap_c_(MAX_REG_PATH) WCHAR *Path)
{
    DWORD Result;
    HKEY TcpipAdapterRegKey;
    WCHAR TcpipAdapterRegPath[MAX_REG_PATH];
    GetTcpipAdapterRegPath(Adapter, TcpipAdapterRegPath);
    Result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, TcpipAdapterRegPath, 0, KEY_QUERY_VALUE, &TcpipAdapterRegKey);
    if (Result != ERROR_SUCCESS)
        return Result;
    WCHAR *Paths;
    Result = RegistryQueryString(TcpipAdapterRegKey, L"IpConfig", &Paths);
    if (Result != ERROR_SUCCESS)
        goto cleanupTcpipAdapterRegKey;
    if (!Paths[0])
    {
        Result = ERROR_INVALID_DATA;
        goto cleanupPaths;
    }
    _snwprintf_s(Path, MAX_REG_PATH, _TRUNCATE, L"SYSTEM\\CurrentControlSet\\Services\\%s", Paths);
cleanupPaths:
    HeapFree(GetProcessHeap(), 0, Paths);
cleanupTcpipAdapterRegKey:
    RegCloseKey(TcpipAdapterRegKey);
    return Result;
}

/**
 * Releases Wintun adapter resources.
 *
 * @param Adapter       Adapter handle obtained with WintunGetAdapter or WintunCreateAdapter
 */
void WINAPI
WintunFreeAdapter(_In_ WINTUN_ADAPTER *Adapter)
{
    HeapFree(GetProcessHeap(), 0, Adapter);
}

/**
 * Finds a Wintun adapter by its name.
 *
 * @param Pool          Name of the adapter pool
 *
 * @param Name          Adapter name
 *
 * @param Adapter       Pointer to a handle to receive the adapter handle. Must be released with
 *                      WintunFreeAdapter.
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise;
 * ERROR_FILE_NOT_FOUND if adapter with given name is not found;
 * ERROR_ALREADY_EXISTS if adapter is found but not a Wintun-class or not a member of the pool
 */
WINTUN_STATUS WINAPI
WintunGetAdapter(_In_z_count_c_(MAX_POOL) const WCHAR *Pool, _In_z_ const WCHAR *Name, _Out_ WINTUN_ADAPTER **Adapter)
{
    DWORD Result;
    HANDLE Mutex = TakeNameMutex(Pool);
    if (!Mutex)
        return ERROR_INVALID_HANDLE;

    HDEVINFO DevInfo = SetupDiGetClassDevsExW(&CLASS_NET_GUID, NULL, NULL, DIGCF_PRESENT, NULL, NULL, NULL);
    if (DevInfo == INVALID_HANDLE_VALUE)
    {
        Result = GetLastError();
        goto cleanupMutex;
    }

    HANDLE Heap = GetProcessHeap();
    for (DWORD MemberIndex = 0;; ++MemberIndex)
    {
        SP_DEVINFO_DATA DevInfoData = { .cbSize = sizeof(SP_DEVINFO_DATA) };
        if (!SetupDiEnumDeviceInfo(DevInfo, MemberIndex, &DevInfoData))
        {
            if (GetLastError() == ERROR_NO_MORE_ITEMS)
                break;
            continue;
        }

        GUID CfgInstanceID;
        if (GetNetCfgInstanceId(DevInfo, &DevInfoData, &CfgInstanceID) != ERROR_SUCCESS)
            continue;

        /* TODO: is there a better way than comparing ifnames? */
        WCHAR Name2[MAX_ADAPTER_NAME], Name3[MAX_ADAPTER_NAME];
        if (NciGetConnectionName(&CfgInstanceID, Name2, sizeof(Name2), NULL) != ERROR_SUCCESS)
            continue;
        Name2[_countof(Name2) - 1] = 0;
        RemoveNumberedSuffix(Name2, Name3);
        if (_wcsicmp(Name, Name2) && _wcsicmp(Name, Name3))
            continue;

        /* Check the Hardware ID to make sure it's a real Wintun device. This avoids doing slow operations on non-Wintun
         * devices. */
        WCHAR *Hwids;
        Result = GetDeviceRegistryMultiString(DevInfo, &DevInfoData, SPDRP_HARDWAREID, &Hwids);
        if (Result != ERROR_SUCCESS)
            goto cleanupDevInfo;
        if (!IsOurHardwareID(Hwids))
        {
            HeapFree(Heap, 0, Hwids);
            Result = ERROR_ALREADY_EXISTS;
            goto cleanupDevInfo;
        }
        HeapFree(Heap, 0, Hwids);

        BOOL IsOurDriver;
        Result = IsUsingOurDriver(DevInfo, &DevInfoData, &IsOurDriver);
        if (Result != ERROR_SUCCESS)
            goto cleanupDevInfo;
        if (!IsOurDriver)
        {
            Result = ERROR_ALREADY_EXISTS;
            goto cleanupDevInfo;
        }

        BOOL IsMember;
        Result = IsPoolMember(Pool, DevInfo, &DevInfoData, &IsMember);
        if (Result != ERROR_SUCCESS)
            goto cleanupDevInfo;
        if (!IsMember)
        {
            Result = ERROR_ALREADY_EXISTS;
            goto cleanupDevInfo;
        }

        Result = CreateAdapterData(Pool, DevInfo, &DevInfoData, Adapter);
        goto cleanupDevInfo;
    }
    Result = ERROR_FILE_NOT_FOUND;
cleanupDevInfo:
    SetupDiDestroyDeviceInfoList(DevInfo);
cleanupMutex:
    ReleaseNameMutex(Mutex);
    return Result;
}

/**
 * Returns the name of the Wintun adapter.
 */
WINTUN_STATUS WINAPI
WintunGetAdapterName(_In_ const WINTUN_ADAPTER *Adapter, _Out_cap_c_(MAX_ADAPTER_NAME) WCHAR *Name)
{
    return NciGetConnectionName(&Adapter->CfgInstanceID, Name, MAX_ADAPTER_NAME * sizeof(WCHAR), NULL);
}

static WINTUN_STATUS
ConvertInterfaceAliasToGuid(_In_z_ const WCHAR *Name, _Out_ GUID *Guid)
{
    NET_LUID Luid;
    DWORD Result = ConvertInterfaceAliasToLuid(Name, &Luid);
    if (Result != NO_ERROR)
        return Result;
    return ConvertInterfaceLuidToGuid(&Luid, Guid);
}

/**
 * Sets name of the Wintun adapter.
 */
WINTUN_STATUS WINAPI
WintunSetAdapterName(_In_ const WINTUN_ADAPTER *Adapter, _In_z_count_c_(MAX_ADAPTER_NAME) const WCHAR *Name)
{
    DWORD Result;
    const int MaxSuffix = 1000;
    WCHAR AvailableName[MAX_ADAPTER_NAME];
    wcscpy_s(AvailableName, _countof(AvailableName), Name);
    for (int i = 0;; ++i)
    {
        Result = NciSetConnectionName(&Adapter->CfgInstanceID, AvailableName);
        if (Result == ERROR_DUP_NAME)
        {
            GUID Guid2;
            DWORD Result2 = ConvertInterfaceAliasToGuid(AvailableName, &Guid2);
            if (Result2 == ERROR_SUCCESS)
            {
                for (int j = 0; j < MaxSuffix; ++j)
                {
                    WCHAR Proposal[MAX_ADAPTER_NAME];
                    _snwprintf_s(Proposal, _countof(Proposal), _TRUNCATE, L"%.*s %d", MAX_ADAPTER_NAME, Name, j + 1);
                    if (_wcsnicmp(Proposal, AvailableName, MAX_ADAPTER_NAME) == 0)
                        continue;
                    Result2 = NciSetConnectionName(&Guid2, Proposal);
                    if (Result2 == ERROR_DUP_NAME)
                        continue;
                    if (Result2 == ERROR_SUCCESS)
                    {
                        Result = NciSetConnectionName(&Adapter->CfgInstanceID, AvailableName);
                        if (Result == ERROR_SUCCESS)
                            break;
                    }
                    break;
                }
            }
        }
        if (Result == ERROR_SUCCESS)
            break;
        if (i > MaxSuffix || Result != ERROR_DUP_NAME)
            return Result;
        _snwprintf_s(AvailableName, _countof(AvailableName), _TRUNCATE, L"%.*s %d", MAX_ADAPTER_NAME, Name, i + 1);
    }

    /* TODO: This should use NetSetup2 so that it doesn't get unset. */
    HKEY DeviceRegKey;
    WCHAR DeviceRegPath[MAX_REG_PATH];
    GetDeviceRegPath(Adapter, DeviceRegPath);
    Result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, DeviceRegPath, 0, KEY_SET_VALUE, &DeviceRegKey);
    if (Result != ERROR_SUCCESS)
        return Result;
    WCHAR PoolDeviceTypeName[MAX_POOL_DEVICE_TYPE];
    GetPoolDeviceTypeName(Adapter->Pool, PoolDeviceTypeName);
    Result = RegSetKeyValueW(
        DeviceRegKey,
        NULL,
        L"FriendlyName",
        REG_SZ,
        PoolDeviceTypeName,
        (DWORD)((wcslen(PoolDeviceTypeName) + 1) * sizeof(WCHAR)));
    RegCloseKey(DeviceRegKey);
    return Result;
}

/**
 * Returns the GUID of the adapter.
 *
 * @param Adapter       Adapter handle obtained with WintunGetAdapter or WintunCreateAdapter
 *
 * @param Guid          Pointer to GUID to receive adapter ID.
 */
void WINAPI
WintunGetAdapterGUID(_In_ const WINTUN_ADAPTER *Adapter, _Out_ GUID *Guid)
{
    memcpy_s(Guid, sizeof(*Guid), &Adapter->CfgInstanceID, sizeof(Adapter->CfgInstanceID));
}

/**
 * Returns the LUID of the adapter.
 *
 * @param Adapter       Adapter handle obtained with WintunGetAdapter or WintunCreateAdapter
 *
 * @param Luid          Pointer to LUID to receive adapter LUID.
 */
void WINAPI
WintunGetAdapterLUID(_In_ const WINTUN_ADAPTER *Adapter, _Out_ LUID *Luid)
{
    *(LONGLONG *)Luid = (((LONGLONG)Adapter->LuidIndex & ((1 << 24) - 1)) << 24) |
                        (((LONGLONG)Adapter->IfType & ((1 << 16) - 1)) << 48);
}

/**
 * Returns a handle to the adapter device object.
 *
 * @param Adapter       Adapter handle obtained with WintunGetAdapter or WintunCreateAdapter
 *
 * @param Handle        Pointer to receive the adapter device object handle. Must be released with CloseHandle.
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise
 */
WINTUN_STATUS WINAPI
WintunGetAdapterDeviceObject(_In_ const WINTUN_ADAPTER *Adapter, _Out_ HANDLE *Handle)
{
    HANDLE Heap = GetProcessHeap();
    ULONG InterfacesLen;
    DWORD Result = CM_Get_Device_Interface_List_SizeW(
        &InterfacesLen,
        (GUID *)&ADAPTER_NET_GUID,
        (DEVINSTID_W)Adapter->DevInstanceID,
        CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
    if (Result != CR_SUCCESS)
        return Result;
    WCHAR *Interfaces = HeapAlloc(Heap, 0, InterfacesLen * sizeof(WCHAR));
    if (!Interfaces)
        return ERROR_OUTOFMEMORY;
    Result = CM_Get_Device_Interface_ListW(
        (GUID *)&ADAPTER_NET_GUID,
        (DEVINSTID_W)Adapter->DevInstanceID,
        Interfaces,
        InterfacesLen,
        CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
    if (Result != CR_SUCCESS)
        goto cleanupBuf;
    *Handle = CreateFileW(
        Interfaces,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        NULL,
        OPEN_EXISTING,
        0,
        NULL);
    if (*Handle == INVALID_HANDLE_VALUE)
        Result = GetLastError();
cleanupBuf:
    HeapFree(Heap, 0, Interfaces);
    return Result;
}

/**
 * @return TRUE if DriverData date and version is newer than supplied parameters.
 */
static BOOL
IsNewer(_In_ const SP_DRVINFO_DATA_W *DriverData, _In_ const FILETIME *DriverDate, _In_ DWORDLONG DriverVersion)
{
    if (DriverData->DriverDate.dwHighDateTime > DriverDate->dwHighDateTime)
        return TRUE;
    if (DriverData->DriverDate.dwHighDateTime < DriverDate->dwHighDateTime)
        return FALSE;

    if (DriverData->DriverDate.dwLowDateTime > DriverDate->dwLowDateTime)
        return TRUE;
    if (DriverData->DriverDate.dwLowDateTime < DriverDate->dwLowDateTime)
        return FALSE;

    if (DriverData->DriverVersion > DriverVersion)
        return TRUE;
    if (DriverData->DriverVersion < DriverVersion)
        return FALSE;

    return FALSE;
}

/**
 * Creates a Wintun adapter.
 *
 * @param Pool          Name of the adapter pool
 *
 * @param Name          The requested name of the adapter
 *
 * @param RequestedGUID  The GUID of the created network adapter, which then influences NLA generation
 *                      deterministically. If it is set to NULL, the GUID is chosen by the system at random, and hence
 *                      a new NLA entry is created for each new adapter. It is called "requested" GUID because the API
 *                      it uses is completely undocumented, and so there could be minor interesting complications with
 *                      its usage.
 *
 * @param Adapter       Pointer to a handle to receive the adapter handle. Must be released with
 *                      WintunFreeAdapter.
 *
 * @param RebootRequired  Pointer to a boolean flag to be set to TRUE in case SetupAPI suggests a reboot. Must be
 *                      initialised to FALSE manually before this function is called.
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise
 */
WINTUN_STATUS WINAPI
WintunCreateAdapter(
    _In_z_count_c_(MAX_POOL) const WCHAR *Pool,
    _In_z_ const WCHAR *Name,
    _In_opt_ const GUID *RequestedGUID,
    _Out_ WINTUN_ADAPTER **Adapter,
    _Inout_ BOOL *RebootRequired)
{
    DWORD Result;
    HANDLE Mutex = TakeNameMutex(Pool);
    if (!Mutex)
        return ERROR_INVALID_HANDLE;

    HDEVINFO DevInfo = SetupDiCreateDeviceInfoListExW(&CLASS_NET_GUID, NULL, NULL, NULL);
    if (DevInfo == INVALID_HANDLE_VALUE)
    {
        Result = GetLastError();
        goto cleanupMutex;
    }

    WCHAR ClassName[MAX_CLASS_NAME_LEN];
    if (!SetupDiClassNameFromGuidExW(&CLASS_NET_GUID, ClassName, _countof(ClassName), NULL, NULL, NULL))
    {
        Result = GetLastError();
        goto cleanupDevInfo;
    }

    HANDLE Heap = GetProcessHeap();
    WCHAR PoolDeviceTypeName[MAX_POOL_DEVICE_TYPE];
    GetPoolDeviceTypeName(Pool, PoolDeviceTypeName);
    SP_DEVINFO_DATA DevInfoData = { .cbSize = sizeof(SP_DEVINFO_DATA) };
    if (!SetupDiCreateDeviceInfoW(
            DevInfo, ClassName, &CLASS_NET_GUID, PoolDeviceTypeName, NULL, DICD_GENERATE_ID, &DevInfoData))
    {
        Result = GetLastError();
        goto cleanupDevInfo;
    }
    Result = SetQuietInstall(DevInfo, &DevInfoData);
    if (Result != ERROR_SUCCESS)
        goto cleanupDevInfo;

    if (!SetupDiSetSelectedDevice(DevInfo, &DevInfoData))
    {
        Result = GetLastError();
        goto cleanupDevInfo;
    }

    static const WCHAR Hwids[_countof(WINTUN_HWID) + 1 /*Multi-string terminator*/] = WINTUN_HWID;
    if (!SetupDiSetDeviceRegistryPropertyW(DevInfo, &DevInfoData, SPDRP_HARDWAREID, (const BYTE *)Hwids, sizeof(Hwids)))
    {
        Result = GetLastError();
        goto cleanupDevInfo;
    }
    if (!SetupDiBuildDriverInfoList(DevInfo, &DevInfoData, SPDIT_COMPATDRIVER)) /* TODO: This takes ~510ms */
    {
        Result = GetLastError();
        goto cleanupDevInfo;
    }

    FILETIME DriverDate = { 0, 0 };
    DWORDLONG DriverVersion = 0;
    for (DWORD DriverIndex = 0;; ++DriverIndex) /* TODO: This loop takes ~600ms */
    {
        SP_DRVINFO_DATA_W DriverData = { .cbSize = sizeof(SP_DRVINFO_DATA_W) };
        if (!SetupDiEnumDriverInfoW(DevInfo, &DevInfoData, SPDIT_COMPATDRIVER, DriverIndex, &DriverData))
        {
            if (GetLastError() == ERROR_NO_MORE_ITEMS)
                break;
            continue;
        }

        /* Check the driver version first, since the check is trivial and will save us iterating over hardware IDs for
         * any driver versioned prior our best match. */
        if (!IsNewer(&DriverData, &DriverDate, DriverVersion))
            continue;

        SP_DRVINFO_DETAIL_DATA_W *DriverDetailData;
        if (GetDriverInfoDetail(DevInfo, &DevInfoData, &DriverData, &DriverDetailData) != ERROR_SUCCESS)
            continue;
        if ((DriverDetailData->CompatIDsOffset <= 1 || _wcsicmp(DriverDetailData->HardwareID, WINTUN_HWID)) &&
            (!DriverDetailData->CompatIDsLength ||
             !IsOurHardwareID(DriverDetailData->HardwareID + DriverDetailData->CompatIDsOffset)))
        {
            HeapFree(Heap, 0, DriverDetailData);
            continue;
        }
        HeapFree(Heap, 0, DriverDetailData);

        if (!SetupDiSetSelectedDriverW(DevInfo, &DevInfoData, &DriverData))
            continue;

        DriverDate = DriverData.DriverDate;
        DriverVersion = DriverData.DriverVersion;
    }

    if (!DriverVersion)
    {
        Result = ERROR_FILE_NOT_FOUND;
        goto cleanupDriverInfoList;
    }

    if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, DevInfo, &DevInfoData))
    {
        Result = GetLastError();
        goto cleanupDevice;
    }
    SetupDiCallClassInstaller(DIF_REGISTER_COINSTALLERS, DevInfo, &DevInfoData); /* Ignore errors */

    HKEY NetDevRegKey = INVALID_HANDLE_VALUE;
    const int PollTimeout = 50 /* ms */;
    for (int i = 0; NetDevRegKey == INVALID_HANDLE_VALUE && i < WAIT_FOR_REGISTRY_TIMEOUT / PollTimeout; ++i)
    {
        if (i)
            Sleep(PollTimeout);
        NetDevRegKey = SetupDiOpenDevRegKey(
            DevInfo, &DevInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DRV, KEY_SET_VALUE | KEY_QUERY_VALUE | KEY_NOTIFY);
    }
    if (NetDevRegKey == INVALID_HANDLE_VALUE)
    {
        Result = GetLastError();
        goto cleanupDevice;
    }
    if (RequestedGUID)
    {
        WCHAR RequestedGUIDStr[MAX_GUID_STRING_LEN];
        Result = RegSetValueExW(
            NetDevRegKey,
            L"NetSetupAnticipatedInstanceId",
            0,
            REG_SZ,
            (const BYTE *)RequestedGUIDStr,
            StringFromGUID2(RequestedGUID, RequestedGUIDStr, _countof(RequestedGUIDStr)) * sizeof(WCHAR));
        if (Result != ERROR_SUCCESS)
            goto cleanupNetDevRegKey;
    }

    SetupDiCallClassInstaller(DIF_INSTALLINTERFACES, DevInfo, &DevInfoData); /* Ignore errors */

    if (!SetupDiCallClassInstaller(DIF_INSTALLDEVICE, DevInfo, &DevInfoData))
    {
        Result = GetLastError();
        goto cleanupNetDevRegKey;
    }
    *RebootRequired = *RebootRequired || CheckReboot(DevInfo, &DevInfoData);

    if (!SetupDiSetDeviceRegistryPropertyW(
            DevInfo,
            &DevInfoData,
            SPDRP_DEVICEDESC,
            (const BYTE *)PoolDeviceTypeName,
            (DWORD)((wcslen(PoolDeviceTypeName) + 1) * sizeof(WCHAR))))
    {
        Result = GetLastError();
        goto cleanupNetDevRegKey;
    }

    /* DIF_INSTALLDEVICE returns almost immediately, while the device installation continues in the background. It might
     * take a while, before all registry keys and values are populated. */
    WCHAR *DummyStr;
    Result = RegistryQueryStringWait(NetDevRegKey, L"NetCfgInstanceId", WAIT_FOR_REGISTRY_TIMEOUT, &DummyStr);
    if (Result != ERROR_SUCCESS)
        goto cleanupNetDevRegKey;
    HeapFree(Heap, 0, DummyStr);
    DWORD DummyDWORD;
    Result = RegistryQueryDWORDWait(NetDevRegKey, L"NetLuidIndex", WAIT_FOR_REGISTRY_TIMEOUT, &DummyDWORD);
    if (Result != ERROR_SUCCESS)
        goto cleanupNetDevRegKey;
    Result = RegistryQueryDWORDWait(NetDevRegKey, L"*IfType", WAIT_FOR_REGISTRY_TIMEOUT, &DummyDWORD);
    if (Result != ERROR_SUCCESS)
        goto cleanupNetDevRegKey;

    Result = CreateAdapterData(Pool, DevInfo, &DevInfoData, Adapter);
    if (Result != ERROR_SUCCESS)
        goto cleanupNetDevRegKey;

    HKEY TcpipAdapterRegKey;
    WCHAR TcpipAdapterRegPath[MAX_REG_PATH];
    GetTcpipAdapterRegPath(*Adapter, TcpipAdapterRegPath);
    Result = RegistryOpenKeyWait(
        HKEY_LOCAL_MACHINE,
        TcpipAdapterRegPath,
        KEY_QUERY_VALUE | KEY_NOTIFY,
        WAIT_FOR_REGISTRY_TIMEOUT,
        &TcpipAdapterRegKey);
    if (Result != ERROR_SUCCESS)
        goto cleanupAdapter;
    Result = RegistryQueryStringWait(TcpipAdapterRegKey, L"IpConfig", WAIT_FOR_REGISTRY_TIMEOUT, &DummyStr);
    if (Result != ERROR_SUCCESS)
        goto cleanupTcpipAdapterRegKey;
    HeapFree(Heap, 0, DummyStr);

    HKEY TcpipInterfaceRegKey;
    WCHAR TcpipInterfaceRegPath[MAX_REG_PATH];
    Result = GetTcpipInterfaceRegPath(*Adapter, TcpipInterfaceRegPath);
    if (Result != ERROR_SUCCESS)
        goto cleanupTcpipAdapterRegKey;
    Result = RegistryOpenKeyWait(
        HKEY_LOCAL_MACHINE,
        TcpipInterfaceRegPath,
        KEY_QUERY_VALUE | KEY_SET_VALUE,
        WAIT_FOR_REGISTRY_TIMEOUT,
        &TcpipInterfaceRegKey);
    if (Result != ERROR_SUCCESS)
        goto cleanupTcpipAdapterRegKey;

    const static DWORD EnableDeadGWDetect = 0;
    RegSetKeyValueW(
        TcpipInterfaceRegKey,
        NULL,
        L"EnableDeadGWDetect",
        REG_DWORD,
        &EnableDeadGWDetect,
        sizeof(EnableDeadGWDetect)); /* Ignore errors */

    Result = WintunSetAdapterName(*Adapter, Name);
    RegCloseKey(TcpipInterfaceRegKey);
cleanupTcpipAdapterRegKey:
    RegCloseKey(TcpipAdapterRegKey);
cleanupAdapter:
    if (Result != ERROR_SUCCESS)
        HeapFree(Heap, 0, *Adapter);
cleanupNetDevRegKey:
    RegCloseKey(NetDevRegKey);
cleanupDevice:
    if (Result != ERROR_SUCCESS)
    {
        /* The adapter failed to install, or the adapter ID was unobtainable. Clean-up. */
        SP_REMOVEDEVICE_PARAMS RemoveDeviceParams = { .ClassInstallHeader = { .cbSize = sizeof(SP_CLASSINSTALL_HEADER),
                                                                              .InstallFunction = DIF_REMOVE },
                                                      .Scope = DI_REMOVEDEVICE_GLOBAL };
        if (SetupDiSetClassInstallParamsW(
                DevInfo, &DevInfoData, &RemoveDeviceParams.ClassInstallHeader, sizeof(RemoveDeviceParams)) &&
            SetupDiCallClassInstaller(DIF_REMOVE, DevInfo, &DevInfoData))
            *RebootRequired = *RebootRequired || CheckReboot(DevInfo, &DevInfoData);
    }
cleanupDriverInfoList:
    SetupDiDestroyDriverInfoList(DevInfo, &DevInfoData, SPDIT_COMPATDRIVER);
cleanupDevInfo:
    SetupDiDestroyDeviceInfoList(DevInfo);
cleanupMutex:
    ReleaseNameMutex(Mutex);
    return Result;
}

/**
 * Deletes a Wintun adapter.
 *
 * @param Adapter       Adapter handle obtained with WintunGetAdapter or WintunCreateAdapter
 *
 * @param RebootRequired  Pointer to a boolean flag to be set to TRUE in case SetupAPI suggests a reboot. Must be
 *                      initialised to FALSE manually before this function is called.
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise. This function succeeds if the adapter was not found.
 */
WINTUN_STATUS WINAPI
WintunDeleteAdapter(_In_ const WINTUN_ADAPTER *Adapter, _Inout_ BOOL *RebootRequired)
{
    HDEVINFO DevInfo;
    SP_DEVINFO_DATA DevInfoData;
    DWORD Result = GetDevInfoData(&Adapter->CfgInstanceID, &DevInfo, &DevInfoData);
    if (Result == ERROR_FILE_NOT_FOUND)
        return ERROR_SUCCESS;
    if (Result != ERROR_SUCCESS)
        return Result;
    Result = SetQuietInstall(DevInfo, &DevInfoData);
    if (Result != ERROR_SUCCESS)
        goto cleanupDevInfo;
    SP_REMOVEDEVICE_PARAMS RemoveDeviceParams = { .ClassInstallHeader = { .cbSize = sizeof(SP_CLASSINSTALL_HEADER),
                                                                          .InstallFunction = DIF_REMOVE },
                                                  .Scope = DI_REMOVEDEVICE_GLOBAL };
    if (SetupDiSetClassInstallParamsW(
            DevInfo, &DevInfoData, &RemoveDeviceParams.ClassInstallHeader, sizeof(RemoveDeviceParams)) &&
        SetupDiCallClassInstaller(DIF_REMOVE, DevInfo, &DevInfoData))
        *RebootRequired = *RebootRequired || CheckReboot(DevInfo, &DevInfoData);
    else
        Result = GetLastError();
cleanupDevInfo:
    SetupDiDestroyDeviceInfoList(DevInfo);
    return Result;
}

/**
 * Enumerates all Wintun adapters.
 *
 * @param Pool          Name of the adapter pool
 *
 * @param Func          Callback function. To continue enumeration, the callback function must return TRUE; to stop
 *                      enumeration, it must return FALSE.
 *
 * @param Param         An application-defined value to be passed to the callback function
 *
 * @return ERROR_SUCCESS on success; Win32 error code otherwise
 */
WINTUN_STATUS WINAPI
WintunEnumAdapters(_In_z_count_c_(MAX_POOL) const WCHAR *Pool, _In_ WINTUN_ENUMPROC Func, _In_ LPARAM Param)
{
    DWORD Result;
    HANDLE Mutex = TakeNameMutex(Pool);
    if (!Mutex)
        return ERROR_INVALID_HANDLE;
    HDEVINFO DevInfo = SetupDiGetClassDevsExW(&CLASS_NET_GUID, NULL, NULL, DIGCF_PRESENT, NULL, NULL, NULL);
    if (DevInfo == INVALID_HANDLE_VALUE)
    {
        Result = GetLastError();
        goto cleanupMutex;
    }
    HANDLE Heap = GetProcessHeap();
    for (DWORD MemberIndex = 0;; ++MemberIndex)
    {
        SP_DEVINFO_DATA DevInfoData = { .cbSize = sizeof(SP_DEVINFO_DATA) };
        if (!SetupDiEnumDeviceInfo(DevInfo, MemberIndex, &DevInfoData))
        {
            if (GetLastError() == ERROR_NO_MORE_ITEMS)
            {
                Result = ERROR_SUCCESS;
                break;
            }
            continue;
        }

        /* Check the Hardware ID to make sure it's a real Wintun device. This avoids doing slow operations on non-Wintun
         * devices. */
        WCHAR *Hwids;
        Result = GetDeviceRegistryMultiString(DevInfo, &DevInfoData, SPDRP_HARDWAREID, &Hwids);
        if (Result != ERROR_SUCCESS)
            break;
        if (!IsOurHardwareID(Hwids))
        {
            HeapFree(Heap, 0, Hwids);
            continue;
        }
        HeapFree(Heap, 0, Hwids);

        BOOL IsOurDriver;
        Result = IsUsingOurDriver(DevInfo, &DevInfoData, &IsOurDriver);
        if (Result != ERROR_SUCCESS)
            break;
        if (!IsOurDriver)
            continue;

        BOOL IsMember;
        Result = IsPoolMember(Pool, DevInfo, &DevInfoData, &IsMember);
        if (Result != ERROR_SUCCESS)
            break;
        if (!IsMember)
            continue;

        WINTUN_ADAPTER *Adapter;
        Result = CreateAdapterData(Pool, DevInfo, &DevInfoData, &Adapter);
        if (Result != ERROR_SUCCESS)
            break;
        if (Func(Adapter, Param))
            HeapFree(Heap, 0, Adapter);
        else
        {
            HeapFree(Heap, 0, Adapter);
            break;
        }
    }
    SetupDiDestroyDeviceInfoList(DevInfo);
cleanupMutex:
    ReleaseNameMutex(Mutex);
    return Result;
}