github.com/tailscale/wireguard-go@v0.0.20201119-0.20210522003738-46b531feb08a/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/tailscale/wireguard-go/conn"
    15  	"github.com/tailscale/wireguard-go/device"
    16  	"github.com/tailscale/wireguard-go/ipc"
    17  	"github.com/tailscale/wireguard-go/tun"
    18  )
    19  
    20  const (
    21  	ExitSetupSuccess = 0
    22  	ExitSetupFailed  = 1
    23  )
    24  
    25  func main() {
    26  	if len(os.Args) != 2 {
    27  		os.Exit(ExitSetupFailed)
    28  	}
    29  	interfaceName := os.Args[1]
    30  
    31  	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.")
    32  
    33  	logger := device.NewLogger(
    34  		device.LogLevelVerbose,
    35  		fmt.Sprintf("(%s) ", interfaceName),
    36  	)
    37  	logger.Verbosef("Starting wireguard-go version %s", Version)
    38  
    39  	tun, err := tun.CreateTUN(interfaceName, 0)
    40  	if err == nil {
    41  		realInterfaceName, err2 := tun.Name()
    42  		if err2 == nil {
    43  			interfaceName = realInterfaceName
    44  		}
    45  	} else {
    46  		logger.Errorf("Failed to create TUN device: %v", err)
    47  		os.Exit(ExitSetupFailed)
    48  	}
    49  
    50  	device := device.NewDevice(tun, conn.NewDefaultBind(), logger)
    51  	err = device.Up()
    52  	if err != nil {
    53  		logger.Errorf("Failed to bring up device: %v", err)
    54  		os.Exit(ExitSetupFailed)
    55  	}
    56  	logger.Verbosef("Device started")
    57  
    58  	uapi, err := ipc.UAPIListen(interfaceName)
    59  	if err != nil {
    60  		logger.Errorf("Failed to listen on uapi socket: %v", err)
    61  		os.Exit(ExitSetupFailed)
    62  	}
    63  
    64  	errs := make(chan error)
    65  	term := make(chan os.Signal, 1)
    66  
    67  	go func() {
    68  		for {
    69  			conn, err := uapi.Accept()
    70  			if err != nil {
    71  				errs <- err
    72  				return
    73  			}
    74  			go device.IpcHandle(conn)
    75  		}
    76  	}()
    77  	logger.Verbosef("UAPI listener started")
    78  
    79  	// wait for program to terminate
    80  
    81  	signal.Notify(term, os.Interrupt)
    82  	signal.Notify(term, os.Kill)
    83  	signal.Notify(term, syscall.SIGTERM)
    84  
    85  	select {
    86  	case <-term:
    87  	case <-errs:
    88  	case <-device.Wait():
    89  	}
    90  
    91  	// clean up
    92  
    93  	uapi.Close()
    94  	device.Close()
    95  
    96  	logger.Verbosef("Shutting down")
    97  }