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

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2019-2022 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package services
     7  
     8  import (
     9  	"errors"
    10  	"log"
    11  	"sync"
    12  	"time"
    13  
    14  	"golang.org/x/sys/windows"
    15  	"golang.org/x/sys/windows/svc"
    16  	"golang.zx2c4.com/wireguard/windows/version"
    17  )
    18  
    19  var (
    20  	startedAtBoot     bool
    21  	startedAtBootOnce sync.Once
    22  )
    23  
    24  func StartedAtBoot() bool {
    25  	startedAtBootOnce.Do(func() {
    26  		if isService, err := svc.IsWindowsService(); err == nil && !isService {
    27  			return
    28  		}
    29  		if reason, err := svc.DynamicStartReason(); err == nil {
    30  			startedAtBoot = (reason&svc.StartReasonAuto) != 0 || (reason&svc.StartReasonDelayedAuto) != 0
    31  		} else if errors.Is(err, windows.ERROR_PROC_NOT_FOUND) {
    32  			// TODO: Below this line is Windows 7 compatibility code, which hopefully we can delete at some point.
    33  			startedAtBoot = windows.DurationSinceBoot() < time.Minute*10
    34  		} else {
    35  			log.Printf("Unable to determine service start reason: %v", err)
    36  		}
    37  	})
    38  	return startedAtBoot
    39  }
    40  
    41  func PrintStarting() {
    42  	boot := ""
    43  	if StartedAtBoot() {
    44  		boot = " at boot"
    45  	}
    46  	log.Printf("Starting%s %s", boot, version.UserAgent())
    47  }