golang.zx2c4.com/wireguard/windows@v0.5.4-0.20230123132234-dcc0eb72a04b/manager/ipc_driver.go (about)

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2019-2022 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package manager
     7  
     8  import (
     9  	"sync"
    10  
    11  	"golang.zx2c4.com/wireguard/windows/driver"
    12  )
    13  
    14  type lockedDriverAdapter struct {
    15  	*driver.Adapter
    16  	sync.Mutex
    17  }
    18  
    19  var (
    20  	driverAdapters     = make(map[string]*lockedDriverAdapter)
    21  	driverAdaptersLock sync.RWMutex
    22  )
    23  
    24  func findDriverAdapter(tunnelName string) (*lockedDriverAdapter, error) {
    25  	driverAdaptersLock.RLock()
    26  	driverAdapter, ok := driverAdapters[tunnelName]
    27  	if ok {
    28  		driverAdapter.Lock()
    29  		driverAdaptersLock.RUnlock()
    30  		return driverAdapter, nil
    31  	}
    32  	driverAdaptersLock.RUnlock()
    33  	driverAdaptersLock.Lock()
    34  	defer driverAdaptersLock.Unlock()
    35  	driverAdapter, ok = driverAdapters[tunnelName]
    36  	if ok {
    37  		driverAdapter.Lock()
    38  		return driverAdapter, nil
    39  	}
    40  	driverAdapter = &lockedDriverAdapter{}
    41  	var err error
    42  	driverAdapter.Adapter, err = driver.OpenAdapter(tunnelName)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	driverAdapters[tunnelName] = driverAdapter
    47  	driverAdapter.Lock()
    48  	return driverAdapter, nil
    49  }
    50  
    51  func releaseDriverAdapter(tunnelName string) {
    52  	driverAdaptersLock.Lock()
    53  	defer driverAdaptersLock.Unlock()
    54  	driverAdapter, ok := driverAdapters[tunnelName]
    55  	if !ok {
    56  		return
    57  	}
    58  	driverAdapter.Lock()
    59  	delete(driverAdapters, tunnelName)
    60  	driverAdapter.Unlock()
    61  }