github.com/liloew/wireguard-go@v0.0.0-20220224014633-9cd745e6f114/main_windows.go (about)

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package main
     7  
     8  import (
     9  	"fmt"
    10  	"os"
    11  	"os/signal"
    12  	"syscall"
    13  
    14  	"github.com/liloew/wireguard-go/conn"
    15  	"github.com/liloew/wireguard-go/device"
    16  	"github.com/liloew/wireguard-go/ipc"
    17  
    18  	"github.com/liloew/wireguard-go/tun"
    19  )
    20  
    21  const (
    22  	ExitSetupSuccess = 0
    23  	ExitSetupFailed  = 1
    24  )
    25  
    26  func main() {
    27  	if len(os.Args) != 2 {
    28  		os.Exit(ExitSetupFailed)
    29  	}
    30  	interfaceName := os.Args[1]
    31  
    32  	fmt.Fprintln(os.Stderr, "Warning: this is a test program for Windows, mainly used for debugging this Go package. For a real WireGuard for Windows client, the repo you want is <https://git.zx2c4.com/wireguard-windows/>, which includes this code as a module.")
    33  
    34  	logger := device.NewLogger(
    35  		device.LogLevelVerbose,
    36  		fmt.Sprintf("(%s) ", interfaceName),
    37  	)
    38  	logger.Verbosef("Starting wireguard-go version %s", Version)
    39  
    40  	tun, err := tun.CreateTUN(interfaceName, 0, false)
    41  	if err == nil {
    42  		realInterfaceName, err2 := tun.Name()
    43  		if err2 == nil {
    44  			interfaceName = realInterfaceName
    45  		}
    46  	} else {
    47  		logger.Errorf("Failed to create TUN device: %v", err)
    48  		os.Exit(ExitSetupFailed)
    49  	}
    50  
    51  	device := device.NewDevice(tun, conn.NewDefaultBind(), logger)
    52  	err = device.Up()
    53  	if err != nil {
    54  		logger.Errorf("Failed to bring up device: %v", err)
    55  		os.Exit(ExitSetupFailed)
    56  	}
    57  	logger.Verbosef("Device started")
    58  
    59  	uapi, err := ipc.UAPIListen(interfaceName)
    60  	if err != nil {
    61  		logger.Errorf("Failed to listen on uapi socket: %v", err)
    62  		os.Exit(ExitSetupFailed)
    63  	}
    64  
    65  	errs := make(chan error)
    66  	term := make(chan os.Signal, 1)
    67  
    68  	go func() {
    69  		for {
    70  			conn, err := uapi.Accept()
    71  			if err != nil {
    72  				errs <- err
    73  				return
    74  			}
    75  			go device.IpcHandle(conn)
    76  		}
    77  	}()
    78  	logger.Verbosef("UAPI listener started")
    79  
    80  	// wait for program to terminate
    81  
    82  	signal.Notify(term, os.Interrupt)
    83  	signal.Notify(term, os.Kill)
    84  	signal.Notify(term, syscall.SIGTERM)
    85  
    86  	select {
    87  	case <-term:
    88  	case <-errs:
    89  	case <-device.Wait():
    90  	}
    91  
    92  	// clean up
    93  
    94  	uapi.Close()
    95  	device.Close()
    96  
    97  	logger.Verbosef("Shutting down")
    98  }