summaryrefslogtreecommitdiffhomepage
path: root/tun/wintun/wintun_windows.go
blob: 2f8fcc1e4cde5f67daff7dc321b8e75652c90860 (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
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019 WireGuard LLC. All Rights Reserved.
 */

package wintun

import (
	"errors"
	"fmt"
	"strings"
	"time"
	"unsafe"

	"golang.org/x/sys/windows"
	"golang.org/x/sys/windows/registry"

	"golang.zx2c4.com/wireguard/tun/wintun/netshell"
	registryEx "golang.zx2c4.com/wireguard/tun/wintun/registry"
	"golang.zx2c4.com/wireguard/tun/wintun/setupapi"
)

// Wintun is a handle of a Wintun adapter.
type Wintun struct {
	cfgInstanceID windows.GUID
	devInstanceID string
	luidIndex     uint32
	ifType        uint32
}

var deviceClassNetGUID = windows.GUID{Data1: 0x4d36e972, Data2: 0xe325, Data3: 0x11ce, Data4: [8]byte{0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18}}
var deviceInterfaceNetGUID = windows.GUID{Data1: 0xcac88484, Data2: 0x7515, Data3: 0x4c03, Data4: [8]byte{0x82, 0xe6, 0x71, 0xa8, 0x7a, 0xba, 0xc3, 0x61}}

const (
	deviceTypeName         = "WireGuard Tunnel"
	hardwareID             = "Wintun"
	waitForRegistryTimeout = time.Second * 10
)

// makeWintun creates a Wintun interface handle and populates it from the device's registry key.
func makeWintun(deviceInfoSet setupapi.DevInfo, deviceInfoData *setupapi.DevInfoData) (*Wintun, error) {
	// Open HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\<class>\<id> registry key.
	key, err := deviceInfoSet.OpenDevRegKey(deviceInfoData, setupapi.DICS_FLAG_GLOBAL, 0, setupapi.DIREG_DRV, registry.QUERY_VALUE)
	if err != nil {
		return nil, fmt.Errorf("Device-specific registry key open failed: %v", err)
	}
	defer key.Close()

	// Read the NetCfgInstanceId value.
	valueStr, err := registryEx.GetStringValue(key, "NetCfgInstanceId")
	if err != nil {
		return nil, fmt.Errorf("RegQueryStringValue(\"NetCfgInstanceId\") failed: %v", err)
	}

	// Convert to GUID.
	ifid, err := windows.GUIDFromString(valueStr)
	if err != nil {
		return nil, fmt.Errorf("NetCfgInstanceId registry value is not a GUID (expected: \"{...}\", provided: %q)", valueStr)
	}

	// Read the NetLuidIndex value.
	luidIdx, _, err := key.GetIntegerValue("NetLuidIndex")
	if err != nil {
		return nil, fmt.Errorf("RegQueryValue(\"NetLuidIndex\") failed: %v", err)
	}

	// Read the NetLuidIndex value.
	ifType, _, err := key.GetIntegerValue("*IfType")
	if err != nil {
		return nil, fmt.Errorf("RegQueryValue(\"*IfType\") failed: %v", err)
	}

	instanceID, err := deviceInfoSet.DeviceInstanceID(deviceInfoData)
	if err != nil {
		return nil, fmt.Errorf("DeviceInstanceID failed: %v", err)
	}

	return &Wintun{
		cfgInstanceID: ifid,
		devInstanceID: instanceID,
		luidIndex:     uint32(luidIdx),
		ifType:        uint32(ifType),
	}, nil
}

// GetInterface finds a Wintun interface by its name. This function returns
// the interface if found, or windows.ERROR_OBJECT_NOT_FOUND otherwise. If
// the interface is found but not a Wintun-class, this function returns
// windows.ERROR_ALREADY_EXISTS.
func GetInterface(ifname string) (*Wintun, error) {
	// Create a list of network devices.
	devInfoList, err := setupapi.SetupDiGetClassDevsEx(&deviceClassNetGUID, "", 0, setupapi.DIGCF_PRESENT, setupapi.DevInfo(0), "")
	if err != nil {
		return nil, fmt.Errorf("SetupDiGetClassDevsEx(%v) failed: %v", deviceClassNetGUID, err)
	}
	defer devInfoList.Close()

	// Windows requires each interface to have a different name. When
	// enforcing this, Windows treats interface names case-insensitive. If an
	// interface "FooBar" exists and this function reports there is no
	// interface "foobar", an attempt to create a new interface and name it
	// "foobar" would cause conflict with "FooBar".
	ifname = strings.ToLower(ifname)

	for index := 0; ; index++ {
		deviceData, err := devInfoList.EnumDeviceInfo(index)
		if err != nil {
			if err == windows.ERROR_NO_MORE_ITEMS {
				break
			}
			continue
		}

		wintun, err := makeWintun(devInfoList, deviceData)
		if err != nil {
			continue
		}

		// TODO: is there a better way than comparing ifnames?
		ifname2, err := wintun.InterfaceName()
		if err != nil {
			continue
		}

		if ifname == strings.ToLower(ifname2) {
			err = devInfoList.BuildDriverInfoList(deviceData, setupapi.SPDIT_COMPATDRIVER)
			if err != nil {
				return nil, fmt.Errorf("SetupDiBuildDriverInfoList failed: %v", err)
			}
			defer devInfoList.DestroyDriverInfoList(deviceData, setupapi.SPDIT_COMPATDRIVER)

			for index := 0; ; index++ {
				driverData, err := devInfoList.EnumDriverInfo(deviceData, setupapi.SPDIT_COMPATDRIVER, index)
				if err != nil {
					if err == windows.ERROR_NO_MORE_ITEMS {
						break
					}
					continue
				}

				// Get driver info details.
				driverDetailData, err := devInfoList.DriverInfoDetail(deviceData, driverData)
				if err != nil {
					continue
				}

				if driverDetailData.IsCompatible(hardwareID) {
					return wintun, nil
				}
			}

			// This interface is not using Wintun driver.
			return nil, windows.ERROR_ALREADY_EXISTS
		}
	}

	return nil, windows.ERROR_OBJECT_NOT_FOUND
}

// CreateInterface creates a Wintun interface. description is a string that
// supplies the text description of the device. The description is optional
// and can be "". requestedGUID is the GUID of the created network interface,
// which then influences NLA generation deterministically. If it is set to nil,
// the GUID is chosen by the system at random, and hence a new NLA entry is
// created for each new interface. It is called "requested" GUID because the
// API it uses is completely undocumented, and so there could be minor
// interesting complications with its usage. This function returns the network
// interface ID and a flag if reboot is required.
//
func CreateInterface(description string, requestedGUID *windows.GUID) (wintun *Wintun, rebootRequired bool, err error) {
	// Create an empty device info set for network adapter device class.
	devInfoList, err := setupapi.SetupDiCreateDeviceInfoListEx(&deviceClassNetGUID, 0, "")
	if err != nil {
		err = fmt.Errorf("SetupDiCreateDeviceInfoListEx(%v) failed: %v", deviceClassNetGUID, err)
		return
	}
	defer devInfoList.Close()

	// Get the device class name from GUID.
	className, err := setupapi.SetupDiClassNameFromGuidEx(&deviceClassNetGUID, "")
	if err != nil {
		err = fmt.Errorf("SetupDiClassNameFromGuidEx(%v) failed: %v", deviceClassNetGUID, err)
		return
	}

	// Create a new device info element and add it to the device info set.
	deviceData, err := devInfoList.CreateDeviceInfo(className, &deviceClassNetGUID, description, 0, setupapi.DICD_GENERATE_ID)
	if err != nil {
		err = fmt.Errorf("SetupDiCreateDeviceInfo failed: %v", err)
		return
	}

	err = setQuietInstall(devInfoList, deviceData)
	if err != nil {
		err = fmt.Errorf("Setting quiet installation failed: %v", err)
		return
	}

	// Set a device information element as the selected member of a device information set.
	err = devInfoList.SetSelectedDevice(deviceData)
	if err != nil {
		err = fmt.Errorf("SetupDiSetSelectedDevice failed: %v", err)
		return
	}

	// Set Plug&Play device hardware ID property.
	err = devInfoList.SetDeviceRegistryPropertyString(deviceData, setupapi.SPDRP_HARDWAREID, hardwareID)
	if err != nil {
		err = fmt.Errorf("SetupDiSetDeviceRegistryProperty(SPDRP_HARDWAREID) failed: %v", err)
		return
	}

	err = devInfoList.BuildDriverInfoList(deviceData, setupapi.SPDIT_COMPATDRIVER) // TODO: This takes ~510ms
	if err != nil {
		err = fmt.Errorf("SetupDiBuildDriverInfoList failed: %v", err)
		return
	}
	defer devInfoList.DestroyDriverInfoList(deviceData, setupapi.SPDIT_COMPATDRIVER)

	driverDate := windows.Filetime{}
	driverVersion := uint64(0)
	for index := 0; ; index++ { // TODO: This loop takes ~600ms
		driverData, err := devInfoList.EnumDriverInfo(deviceData, setupapi.SPDIT_COMPATDRIVER, index)
		if err != nil {
			if err == windows.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 driverData.IsNewer(driverDate, driverVersion) {
			driverDetailData, err := devInfoList.DriverInfoDetail(deviceData, driverData)
			if err != nil {
				continue
			}

			if driverDetailData.IsCompatible(hardwareID) {
				err := devInfoList.SetSelectedDriver(deviceData, driverData)
				if err != nil {
					continue
				}

				driverDate = driverData.DriverDate
				driverVersion = driverData.DriverVersion
			}
		}
	}

	if driverVersion == 0 {
		err = fmt.Errorf("No driver for device %q installed", hardwareID)
		return
	}

	// Call appropriate class installer.
	err = devInfoList.CallClassInstaller(setupapi.DIF_REGISTERDEVICE, deviceData)
	if err != nil {
		err = fmt.Errorf("SetupDiCallClassInstaller(DIF_REGISTERDEVICE) failed: %v", err)
		return
	}

	// Register device co-installers if any. (Ignore errors)
	devInfoList.CallClassInstaller(setupapi.DIF_REGISTER_COINSTALLERS, deviceData)

	var netDevRegKey registry.Key
	const pollTimeout = time.Millisecond * 50
	for i := 0; i < int(waitForRegistryTimeout/pollTimeout); i++ {
		if i != 0 {
			time.Sleep(pollTimeout)
		}
		netDevRegKey, err = devInfoList.OpenDevRegKey(deviceData, setupapi.DICS_FLAG_GLOBAL, 0, setupapi.DIREG_DRV, registry.SET_VALUE|registry.QUERY_VALUE|registry.NOTIFY)
		if err == nil {
			break
		}
	}
	if err != nil {
		err = fmt.Errorf("SetupDiOpenDevRegKey failed: %v", err)
		return
	}
	defer netDevRegKey.Close()
	if requestedGUID != nil {
		err = netDevRegKey.SetStringValue("NetSetupAnticipatedInstanceId", requestedGUID.String())
		if err != nil {
			err = fmt.Errorf("SetStringValue(NetSetupAnticipatedInstanceId) failed: %v", err)
			return
		}
	}

	// Install interfaces if any. (Ignore errors)
	devInfoList.CallClassInstaller(setupapi.DIF_INSTALLINTERFACES, deviceData)
	defer func() {
		if err != nil {
			// The interface failed to install, or the interface ID was unobtainable. Clean-up.
			removeDeviceParams := setupapi.RemoveDeviceParams{
				ClassInstallHeader: *setupapi.MakeClassInstallHeader(setupapi.DIF_REMOVE),
				Scope:              setupapi.DI_REMOVEDEVICE_GLOBAL,
			}

			// Set class installer parameters for DIF_REMOVE.
			if devInfoList.SetClassInstallParams(deviceData, &removeDeviceParams.ClassInstallHeader, uint32(unsafe.Sizeof(removeDeviceParams))) == nil {
				// Call appropriate class installer.
				if devInfoList.CallClassInstaller(setupapi.DIF_REMOVE, deviceData) == nil {
					rebootRequired = rebootRequired || checkReboot(devInfoList, deviceData)
				}
			}

			wintun = nil
		}
	}()

	// Install the device.
	err = devInfoList.CallClassInstaller(setupapi.DIF_INSTALLDEVICE, deviceData)
	if err != nil {
		err = fmt.Errorf("SetupDiCallClassInstaller(DIF_INSTALLDEVICE) failed: %v", err)
		return
	}
	rebootRequired = checkReboot(devInfoList, deviceData)

	// 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.
	_, err = registryEx.GetStringValueWait(netDevRegKey, "NetCfgInstanceId", waitForRegistryTimeout)
	if err != nil {
		err = fmt.Errorf("GetStringValueWait(NetCfgInstanceId) failed: %v", err)
		return
	}
	_, err = registryEx.GetIntegerValueWait(netDevRegKey, "NetLuidIndex", waitForRegistryTimeout)
	if err != nil {
		err = fmt.Errorf("GetIntegerValueWait(NetLuidIndex) failed: %v", err)
		return
	}
	_, err = registryEx.GetIntegerValueWait(netDevRegKey, "*IfType", waitForRegistryTimeout)
	if err != nil {
		err = fmt.Errorf("GetIntegerValueWait(*IfType) failed: %v", err)
		return
	}

	// Get network interface.
	wintun, err = makeWintun(devInfoList, deviceData)
	if err != nil {
		err = fmt.Errorf("makeWintun failed: %v", err)
		return
	}

	// Name ourselves.
	deviceRegKey, err := registry.OpenKey(registry.LOCAL_MACHINE, wintun.deviceRegKeyName(), registry.SET_VALUE)
	if err != nil {
		err = fmt.Errorf("Device-level registry key open failed: %v", err)
		return
	}
	defer deviceRegKey.Close()
	err = deviceRegKey.SetStringValue("DeviceDesc", deviceTypeName)
	if err != nil {
		err = fmt.Errorf("SetStringValue(DeviceDesc) failed: %v", err)
		return
	}
	err = deviceRegKey.SetStringValue("FriendlyName", deviceTypeName)
	if err != nil {
		err = fmt.Errorf("SetStringValue(FriendlyName) failed: %v", err)
		return
	}

	// Wait for network registry key to emerge and populate.
	netRegKey, err := registryEx.OpenKeyWait(
		registry.LOCAL_MACHINE,
		wintun.netRegKeyName(),
		registry.QUERY_VALUE|registry.NOTIFY,
		waitForRegistryTimeout)
	if err != nil {
		err = fmt.Errorf("makeWintun failed: %v", err)
		return
	}
	defer netRegKey.Close()
	_, err = registryEx.GetStringValueWait(netRegKey, "Name", waitForRegistryTimeout)
	if err != nil {
		err = fmt.Errorf("GetStringValueWait(Name) failed: %v", err)
		return
	}
	_, err = registryEx.GetStringValueWait(netRegKey, "PnPInstanceId", waitForRegistryTimeout)
	if err != nil {
		err = fmt.Errorf("GetStringValueWait(PnPInstanceId) failed: %v", err)
		return
	}

	// Wait for TCP/IP adapter registry key to emerge and populate.
	tcpipAdapterRegKey, err := registryEx.OpenKeyWait(
		registry.LOCAL_MACHINE,
		wintun.tcpipAdapterRegKeyName(), registry.QUERY_VALUE|registry.NOTIFY,
		waitForRegistryTimeout)
	if err != nil {
		err = fmt.Errorf("OpenKeyWait(HKLM\\%s) failed: %v", wintun.tcpipAdapterRegKeyName(), err)
		return
	}
	defer tcpipAdapterRegKey.Close()
	_, err = registryEx.GetStringValueWait(tcpipAdapterRegKey, "IpConfig", waitForRegistryTimeout)
	if err != nil {
		err = fmt.Errorf("GetStringValueWait(IpConfig) failed: %v", err)
		return
	}

	tcpipInterfaceRegKeyName, err := wintun.tcpipInterfaceRegKeyName()
	if err != nil {
		err = fmt.Errorf("tcpipInterfaceRegKeyName failed: %v", err)
		return
	}

	// Wait for TCP/IP interface registry key to emerge.
	tcpipInterfaceRegKey, err := registryEx.OpenKeyWait(
		registry.LOCAL_MACHINE,
		tcpipInterfaceRegKeyName, registry.QUERY_VALUE | registry.SET_VALUE,
		waitForRegistryTimeout)
	if err != nil {
		err = fmt.Errorf("OpenKeyWait(HKLM\\%s) failed: %v", tcpipInterfaceRegKeyName, err)
		return
	}
	defer tcpipInterfaceRegKey.Close()
	// Disable dead gateway detection on our interface.
	tcpipInterfaceRegKey.SetDWordValue("EnableDeadGWDetect", 0)

	return
}

// DeleteInterface deletes a Wintun interface. This function succeeds
// if the interface was not found. It returns a bool indicating whether
// a reboot is required.
func (wintun *Wintun) DeleteInterface() (rebootRequired bool, err error) {
	devInfoList, deviceData, err := wintun.deviceData()
	if err == windows.ERROR_OBJECT_NOT_FOUND {
		return false, nil
	}
	if err != nil {
		return false, err
	}
	defer devInfoList.Close()

	// Remove the device.
	removeDeviceParams := setupapi.RemoveDeviceParams{
		ClassInstallHeader: *setupapi.MakeClassInstallHeader(setupapi.DIF_REMOVE),
		Scope:              setupapi.DI_REMOVEDEVICE_GLOBAL,
	}

	// Set class installer parameters for DIF_REMOVE.
	err = devInfoList.SetClassInstallParams(deviceData, &removeDeviceParams.ClassInstallHeader, uint32(unsafe.Sizeof(removeDeviceParams)))
	if err != nil {
		return false, fmt.Errorf("SetupDiSetClassInstallParams failed: %v", err)
	}

	// Call appropriate class installer.
	err = devInfoList.CallClassInstaller(setupapi.DIF_REMOVE, deviceData)
	if err != nil {
		return false, fmt.Errorf("SetupDiCallClassInstaller failed: %v", err)
	}

	return checkReboot(devInfoList, deviceData), nil
}

// DeleteAllInterfaces deletes all Wintun interfaces, and returns which
// ones it deleted, whether a reboot is required after, and which errors
// occurred during the process.
func DeleteAllInterfaces() (deviceInstancesDeleted []uint32, rebootRequired bool, errors []error) {
	devInfoList, err := setupapi.SetupDiGetClassDevsEx(&deviceClassNetGUID, "", 0, setupapi.DIGCF_PRESENT, setupapi.DevInfo(0), "")
	if err != nil {
		return nil, false, []error{fmt.Errorf("SetupDiGetClassDevsEx(%v) failed: %v", deviceClassNetGUID, err.Error())}
	}
	defer devInfoList.Close()

	for i := 0; ; i++ {
		deviceData, err := devInfoList.EnumDeviceInfo(i)
		if err != nil {
			if err == windows.ERROR_NO_MORE_ITEMS {
				break
			}
			continue
		}

		err = devInfoList.BuildDriverInfoList(deviceData, setupapi.SPDIT_COMPATDRIVER)
		if err != nil {
			continue
		}
		defer devInfoList.DestroyDriverInfoList(deviceData, setupapi.SPDIT_COMPATDRIVER)

		isWintun := false
		for j := 0; ; j++ {
			driverData, err := devInfoList.EnumDriverInfo(deviceData, setupapi.SPDIT_COMPATDRIVER, j)
			if err != nil {
				if err == windows.ERROR_NO_MORE_ITEMS {
					break
				}
				continue
			}
			driverDetailData, err := devInfoList.DriverInfoDetail(deviceData, driverData)
			if err != nil {
				continue
			}
			if driverDetailData.IsCompatible(hardwareID) {
				isWintun = true
				break
			}
		}
		if !isWintun {
			continue
		}

		err = setQuietInstall(devInfoList, deviceData)
		if err != nil {
			errors = append(errors, err)
			continue
		}

		inst := deviceData.DevInst
		removeDeviceParams := setupapi.RemoveDeviceParams{
			ClassInstallHeader: *setupapi.MakeClassInstallHeader(setupapi.DIF_REMOVE),
			Scope:              setupapi.DI_REMOVEDEVICE_GLOBAL,
		}
		err = devInfoList.SetClassInstallParams(deviceData, &removeDeviceParams.ClassInstallHeader, uint32(unsafe.Sizeof(removeDeviceParams)))
		if err != nil {
			errors = append(errors, err)
			continue
		}
		err = devInfoList.CallClassInstaller(setupapi.DIF_REMOVE, deviceData)
		if err != nil {
			errors = append(errors, err)
			continue
		}
		rebootRequired = rebootRequired || checkReboot(devInfoList, deviceData)
		deviceInstancesDeleted = append(deviceInstancesDeleted, inst)
	}
	return
}

// checkReboot checks device install parameters if a system reboot is required.
func checkReboot(deviceInfoSet setupapi.DevInfo, deviceInfoData *setupapi.DevInfoData) bool {
	devInstallParams, err := deviceInfoSet.DeviceInstallParams(deviceInfoData)
	if err != nil {
		return false
	}

	return (devInstallParams.Flags & (setupapi.DI_NEEDREBOOT | setupapi.DI_NEEDRESTART)) != 0
}

// setQuietInstall sets device install parameters for a quiet installation
func setQuietInstall(deviceInfoSet setupapi.DevInfo, deviceInfoData *setupapi.DevInfoData) error {
	devInstallParams, err := deviceInfoSet.DeviceInstallParams(deviceInfoData)
	if err != nil {
		return err
	}

	devInstallParams.Flags |= setupapi.DI_QUIETINSTALL
	return deviceInfoSet.SetDeviceInstallParams(deviceInfoData, devInstallParams)
}

// InterfaceName returns the name of the Wintun interface.
func (wintun *Wintun) InterfaceName() (string, error) {
	key, err := registry.OpenKey(registry.LOCAL_MACHINE, wintun.netRegKeyName(), registry.QUERY_VALUE)
	if err != nil {
		return "", fmt.Errorf("Network-specific registry key open failed: %v", err)
	}
	defer key.Close()

	// Get the interface name.
	return registryEx.GetStringValue(key, "Name")
}

// SetInterfaceName sets name of the Wintun interface.
func (wintun *Wintun) SetInterfaceName(ifname string) error {
	// We have to tell the various runtime COM services about the new name too. We ignore the
	// error because netshell isn't available on servercore.
	// TODO: netsh.exe falls back to NciSetConnection in this case. If somebody complains, maybe
	// we should do the same.
	netshell.HrRenameConnection(&wintun.cfgInstanceID, windows.StringToUTF16Ptr(ifname))

	// Set the interface name. The above line should have done this too, but in case it failed, we force it.
	key, err := registry.OpenKey(registry.LOCAL_MACHINE, wintun.netRegKeyName(), registry.SET_VALUE)
	if err != nil {
		return fmt.Errorf("Network-specific registry key open failed: %v", err)
	}
	defer key.Close()
	return key.SetStringValue("Name", ifname)
}

// netRegKeyName returns the interface-specific network registry key name.
func (wintun *Wintun) netRegKeyName() string {
	return fmt.Sprintf("SYSTEM\\CurrentControlSet\\Control\\Network\\%v\\%v\\Connection", deviceClassNetGUID, wintun.cfgInstanceID)
}

// tcpipAdapterRegKeyName returns the adapter-specific TCP/IP network registry key name.
func (wintun *Wintun) tcpipAdapterRegKeyName() string {
	return fmt.Sprintf("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Adapters\\%v", wintun.cfgInstanceID)
}

// deviceRegKeyName returns the device-level registry key name
func (wintun *Wintun) deviceRegKeyName() string {
	return fmt.Sprintf("SYSTEM\\CurrentControlSet\\Enum\\%v", wintun.devInstanceID)
}

// tcpipInterfaceRegKeyName returns the interface-specific TCP/IP network registry key name.
func (wintun *Wintun) tcpipInterfaceRegKeyName() (path string, err error) {
	key, err := registry.OpenKey(registry.LOCAL_MACHINE, wintun.tcpipAdapterRegKeyName(), registry.QUERY_VALUE)
	if err != nil {
		return "", fmt.Errorf("Error opening adapter-specific TCP/IP network registry key: %v", err)
	}
	paths, _, err := key.GetStringsValue("IpConfig")
	key.Close()
	if err != nil {
		return "", fmt.Errorf("Error reading IpConfig registry key: %v", err)
	}
	if len(paths) == 0 {
		return "", errors.New("No TCP/IP interfaces found on adapter")
	}
	return fmt.Sprintf("SYSTEM\\CurrentControlSet\\Services\\%s", paths[0]), nil
}

// deviceData returns TUN device info list handle and interface device info
// data. The device info list handle must be closed after use. In case the
// device is not found, windows.ERROR_OBJECT_NOT_FOUND is returned.
func (wintun *Wintun) deviceData() (setupapi.DevInfo, *setupapi.DevInfoData, error) {
	// Create a list of network devices.
	devInfoList, err := setupapi.SetupDiGetClassDevsEx(&deviceClassNetGUID, "", 0, setupapi.DIGCF_PRESENT, setupapi.DevInfo(0), "")
	if err != nil {
		return 0, nil, fmt.Errorf("SetupDiGetClassDevsEx(%v) failed: %v", deviceClassNetGUID, err.Error())
	}

	for index := 0; ; index++ {
		deviceData, err := devInfoList.EnumDeviceInfo(index)
		if err != nil {
			if err == windows.ERROR_NO_MORE_ITEMS {
				break
			}
			continue
		}

		// Get interface ID.
		// TODO: Store some ID in the Wintun object such that this call isn't required.
		wintun2, err := makeWintun(devInfoList, deviceData)
		if err != nil {
			continue
		}

		if wintun.cfgInstanceID == wintun2.cfgInstanceID {
			err = setQuietInstall(devInfoList, deviceData)
			if err != nil {
				devInfoList.Close()
				return 0, nil, fmt.Errorf("Setting quiet installation failed: %v", err)
			}
			return devInfoList, deviceData, nil
		}
	}

	devInfoList.Close()
	return 0, nil, windows.ERROR_OBJECT_NOT_FOUND
}

// AdapterHandle returns a handle to the adapter device object.
func (wintun *Wintun) AdapterHandle() (windows.Handle, error) {
	interfaces, err := setupapi.CM_Get_Device_Interface_List(wintun.devInstanceID, &deviceInterfaceNetGUID, setupapi.CM_GET_DEVICE_INTERFACE_LIST_PRESENT)
	if err != nil {
		return windows.InvalidHandle, err
	}
	handle, err := windows.CreateFile(windows.StringToUTF16Ptr(interfaces[0]), windows.GENERIC_READ|windows.GENERIC_WRITE, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, 0, 0)
	if err != nil {
		return windows.InvalidHandle, fmt.Errorf("Open NDIS device failed: %v", err)
	}
	return handle, nil
}

// GUID returns the GUID of the interface.
func (wintun *Wintun) GUID() windows.GUID {
	return wintun.cfgInstanceID
}

// LUID returns the LUID of the interface.
func (wintun *Wintun) LUID() uint64 {
	return ((uint64(wintun.luidIndex) & ((1 << 24) - 1)) << 24) | ((uint64(wintun.ifType) & ((1 << 16) - 1)) << 48)
}