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

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2019-2022 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package conf
     7  
     8  import (
     9  	"log"
    10  
    11  	"golang.org/x/sys/windows"
    12  )
    13  
    14  var haveStartedWatchingConfigDir bool
    15  
    16  func startWatchingConfigDir() {
    17  	if haveStartedWatchingConfigDir {
    18  		return
    19  	}
    20  	haveStartedWatchingConfigDir = true
    21  	go func() {
    22  		h := windows.InvalidHandle
    23  		defer func() {
    24  			if h != windows.InvalidHandle {
    25  				windows.FindCloseChangeNotification(h)
    26  			}
    27  			haveStartedWatchingConfigDir = false
    28  		}()
    29  	startover:
    30  		configFileDir, err := tunnelConfigurationsDirectory()
    31  		if err != nil {
    32  			return
    33  		}
    34  		h, err = windows.FindFirstChangeNotification(configFileDir, true, windows.FILE_NOTIFY_CHANGE_FILE_NAME|windows.FILE_NOTIFY_CHANGE_DIR_NAME|windows.FILE_NOTIFY_CHANGE_ATTRIBUTES|windows.FILE_NOTIFY_CHANGE_SIZE|windows.FILE_NOTIFY_CHANGE_LAST_WRITE|windows.FILE_NOTIFY_CHANGE_LAST_ACCESS|windows.FILE_NOTIFY_CHANGE_CREATION|windows.FILE_NOTIFY_CHANGE_SECURITY)
    35  		if err != nil {
    36  			log.Printf("Unable to monitor config directory: %v", err)
    37  			return
    38  		}
    39  		for {
    40  			s, err := windows.WaitForSingleObject(h, windows.INFINITE)
    41  			if err != nil || s == windows.WAIT_FAILED {
    42  				log.Printf("Unable to wait on config directory watcher: %v", err)
    43  				windows.FindCloseChangeNotification(h)
    44  				h = windows.InvalidHandle
    45  				goto startover
    46  			}
    47  
    48  			for cb := range storeCallbacks {
    49  				cb.cb()
    50  			}
    51  
    52  			err = windows.FindNextChangeNotification(h)
    53  			if err != nil {
    54  				log.Printf("Unable to monitor config directory again: %v", err)
    55  				windows.FindCloseChangeNotification(h)
    56  				h = windows.InvalidHandle
    57  				goto startover
    58  			}
    59  		}
    60  	}()
    61  }