2021-11-09 11:37:51 +00:00
|
|
|
//go:build windows
|
2018-05-01 23:45:06 +00:00
|
|
|
// +build windows
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
// Copypasta from the example files:
|
|
|
|
// https://github.com/golang/sys/blob/master/windows/svc/example
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2019-03-05 01:49:57 +00:00
|
|
|
"syscall"
|
2018-05-01 23:45:06 +00:00
|
|
|
"time"
|
|
|
|
"unsafe"
|
|
|
|
|
2021-02-05 01:44:03 +00:00
|
|
|
"github.com/pkg/errors"
|
2020-11-25 06:55:13 +00:00
|
|
|
"github.com/urfave/cli/v2"
|
2018-05-01 23:45:06 +00:00
|
|
|
"golang.org/x/sys/windows"
|
|
|
|
"golang.org/x/sys/windows/svc"
|
|
|
|
"golang.org/x/sys/windows/svc/eventlog"
|
|
|
|
"golang.org/x/sys/windows/svc/mgr"
|
2021-03-23 14:30:43 +00:00
|
|
|
|
|
|
|
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
|
|
|
|
"github.com/cloudflare/cloudflared/logger"
|
2018-05-01 23:45:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
windowsServiceName = "Cloudflared"
|
2021-09-28 07:39:40 +00:00
|
|
|
windowsServiceDescription = "Cloudflare Tunnel agent"
|
|
|
|
windowsServiceUrl = "https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/run-tunnel/run-as-service#windows"
|
2018-05-01 23:45:06 +00:00
|
|
|
|
|
|
|
recoverActionDelay = time.Second * 20
|
|
|
|
failureCountResetPeriod = time.Hour * 24
|
|
|
|
|
|
|
|
// not defined in golang.org/x/sys/windows package
|
|
|
|
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v=vs.85).aspx
|
|
|
|
serviceConfigFailureActionsFlag = 4
|
2019-03-05 01:49:57 +00:00
|
|
|
|
|
|
|
// ERROR_FAILED_SERVICE_CONTROLLER_CONNECT
|
|
|
|
// https://docs.microsoft.com/en-us/windows/desktop/debug/system-error-codes--1000-1299-
|
|
|
|
serviceControllerConnectionFailure = 1063
|
2020-12-28 18:10:01 +00:00
|
|
|
|
|
|
|
LogFieldWindowsServiceName = "windowsServiceName"
|
2018-05-01 23:45:06 +00:00
|
|
|
)
|
|
|
|
|
2021-01-25 21:51:58 +00:00
|
|
|
func runApp(app *cli.App, graceShutdownC chan struct{}) {
|
2018-05-01 23:45:06 +00:00
|
|
|
app.Commands = append(app.Commands, &cli.Command{
|
|
|
|
Name: "service",
|
2021-09-28 07:39:40 +00:00
|
|
|
Usage: "Manages the Cloudflare Tunnel Windows service",
|
2018-05-01 23:45:06 +00:00
|
|
|
Subcommands: []*cli.Command{
|
2021-01-25 21:51:58 +00:00
|
|
|
{
|
2018-05-01 23:45:06 +00:00
|
|
|
Name: "install",
|
2021-09-28 07:39:40 +00:00
|
|
|
Usage: "Install Cloudflare Tunnel as a Windows service",
|
2021-03-16 22:36:46 +00:00
|
|
|
Action: cliutil.ConfiguredAction(installWindowsService),
|
2021-02-05 01:44:03 +00:00
|
|
|
},
|
2021-01-25 21:51:58 +00:00
|
|
|
{
|
2018-05-01 23:45:06 +00:00
|
|
|
Name: "uninstall",
|
2021-09-28 07:39:40 +00:00
|
|
|
Usage: "Uninstall the Cloudflare Tunnel service",
|
2021-03-16 22:36:46 +00:00
|
|
|
Action: cliutil.ConfiguredAction(uninstallWindowsService),
|
2021-02-05 01:44:03 +00:00
|
|
|
},
|
2018-05-01 23:45:06 +00:00
|
|
|
},
|
|
|
|
})
|
|
|
|
|
2019-03-05 01:49:57 +00:00
|
|
|
// `IsAnInteractiveSession()` isn't exactly equivalent to "should the
|
|
|
|
// process run as a normal EXE?" There are legitimate non-service cases,
|
|
|
|
// like running cloudflared in a GCP startup script, for which
|
|
|
|
// `IsAnInteractiveSession()` returns false. For more context, see:
|
|
|
|
// https://github.com/judwhite/go-svc/issues/6
|
|
|
|
// It seems that the "correct way" to check "is this a normal EXE?" is:
|
|
|
|
// 1. attempt to connect to the Service Control Manager
|
|
|
|
// 2. get ERROR_FAILED_SERVICE_CONTROLLER_CONNECT
|
|
|
|
// This involves actually trying to start the service.
|
|
|
|
|
2020-11-25 06:55:13 +00:00
|
|
|
log := logger.Create(nil)
|
2020-04-29 20:51:32 +00:00
|
|
|
|
2018-05-01 23:45:06 +00:00
|
|
|
isIntSess, err := svc.IsAnInteractiveSession()
|
|
|
|
if err != nil {
|
2020-12-28 18:10:01 +00:00
|
|
|
log.Fatal().Err(err).Msg("failed to determine if we are running in an interactive session")
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
if isIntSess {
|
|
|
|
app.Run(os.Args)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run executes service name by calling windowsService which is a Handler
|
|
|
|
// interface that implements Execute method.
|
|
|
|
// It will set service status to stop after Execute returns
|
2021-01-25 21:51:58 +00:00
|
|
|
err = svc.Run(windowsServiceName, &windowsService{app: app, graceShutdownC: graceShutdownC})
|
2018-05-01 23:45:06 +00:00
|
|
|
if err != nil {
|
2019-03-05 01:49:57 +00:00
|
|
|
if errno, ok := err.(syscall.Errno); ok && int(errno) == serviceControllerConnectionFailure {
|
|
|
|
// Hack: assume this is a false negative from the IsAnInteractiveSession() check above.
|
|
|
|
// Run the app in "interactive" mode anyway.
|
|
|
|
app.Run(os.Args)
|
|
|
|
return
|
|
|
|
}
|
2020-12-28 18:10:01 +00:00
|
|
|
log.Fatal().Err(err).Msgf("%s service failed", windowsServiceName)
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type windowsService struct {
|
|
|
|
app *cli.App
|
|
|
|
graceShutdownC chan struct{}
|
|
|
|
}
|
|
|
|
|
2021-01-25 21:51:58 +00:00
|
|
|
// Execute is called by the service manager when service starts, the state
|
|
|
|
// of the service will be set to Stopped when this function returns.
|
2018-10-26 20:58:43 +00:00
|
|
|
func (s *windowsService) Execute(serviceArgs []string, r <-chan svc.ChangeRequest, statusChan chan<- svc.Status) (ssec bool, errno uint32) {
|
2020-11-25 06:55:13 +00:00
|
|
|
log := logger.Create(nil)
|
2019-03-05 01:49:57 +00:00
|
|
|
elog, err := eventlog.Open(windowsServiceName)
|
|
|
|
if err != nil {
|
2020-12-28 18:10:01 +00:00
|
|
|
log.Err(err).Msgf("Cannot open event log for %s", windowsServiceName)
|
2019-03-05 01:49:57 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
defer elog.Close()
|
|
|
|
|
|
|
|
elog.Info(1, fmt.Sprintf("%s service starting", windowsServiceName))
|
|
|
|
defer func() {
|
|
|
|
elog.Info(1, fmt.Sprintf("%s service stopped", windowsServiceName))
|
|
|
|
}()
|
|
|
|
|
2018-10-26 20:58:43 +00:00
|
|
|
// the arguments passed here are only meaningful if they were manually
|
|
|
|
// specified by the user, e.g. using the Services console or `sc start`.
|
|
|
|
// https://docs.microsoft.com/en-us/windows/desktop/services/service-entry-point
|
|
|
|
// https://stackoverflow.com/a/6235139
|
|
|
|
var args []string
|
|
|
|
if len(serviceArgs) > 1 {
|
|
|
|
args = serviceArgs
|
|
|
|
} else {
|
|
|
|
// fall back to the arguments from ImagePath (or, as sc calls it, binPath)
|
|
|
|
args = os.Args
|
|
|
|
}
|
2019-03-05 01:49:57 +00:00
|
|
|
elog.Info(1, fmt.Sprintf("%s service arguments: %v", windowsServiceName, args))
|
2018-10-26 20:58:43 +00:00
|
|
|
|
2018-05-01 23:45:06 +00:00
|
|
|
statusChan <- svc.Status{State: svc.StartPending}
|
|
|
|
errC := make(chan error)
|
|
|
|
go func() {
|
|
|
|
errC <- s.app.Run(args)
|
|
|
|
}()
|
2021-01-25 21:51:58 +00:00
|
|
|
statusChan <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown}
|
2018-05-01 23:45:06 +00:00
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case c := <-r:
|
|
|
|
switch c.Cmd {
|
|
|
|
case svc.Interrogate:
|
|
|
|
statusChan <- c.CurrentStatus
|
2020-07-07 15:44:07 +00:00
|
|
|
case svc.Stop, svc.Shutdown:
|
2021-01-25 21:51:58 +00:00
|
|
|
if s.graceShutdownC != nil {
|
|
|
|
// start graceful shutdown
|
|
|
|
elog.Info(1, "cloudflared starting graceful shutdown")
|
|
|
|
close(s.graceShutdownC)
|
|
|
|
s.graceShutdownC = nil
|
|
|
|
statusChan <- svc.Status{State: svc.StopPending}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// repeated attempts at graceful shutdown forces immediate stop
|
|
|
|
elog.Info(1, "cloudflared terminating immediately")
|
2018-05-01 23:45:06 +00:00
|
|
|
statusChan <- svc.Status{State: svc.StopPending}
|
2021-01-25 21:51:58 +00:00
|
|
|
return false, 0
|
2018-05-01 23:45:06 +00:00
|
|
|
default:
|
2019-03-05 01:49:57 +00:00
|
|
|
elog.Error(1, fmt.Sprintf("unexpected control request #%d", c))
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
case err := <-errC:
|
|
|
|
if err != nil {
|
2019-03-05 01:49:57 +00:00
|
|
|
elog.Error(1, fmt.Sprintf("cloudflared terminated with error %v", err))
|
2021-01-25 21:51:58 +00:00
|
|
|
ssec = true
|
2018-05-01 23:45:06 +00:00
|
|
|
errno = 1
|
|
|
|
} else {
|
2019-03-05 01:49:57 +00:00
|
|
|
elog.Info(1, "cloudflared terminated without error")
|
2018-05-01 23:45:06 +00:00
|
|
|
errno = 0
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func installWindowsService(c *cli.Context) error {
|
2021-01-13 16:20:41 +00:00
|
|
|
zeroLogger := logger.CreateLoggerFromContext(c, logger.EnableTerminalLog)
|
2020-04-29 20:51:32 +00:00
|
|
|
|
2021-09-28 07:39:40 +00:00
|
|
|
zeroLogger.Info().Msg("Installing Cloudflare Tunnel Windows service")
|
2018-05-01 23:45:06 +00:00
|
|
|
exepath, err := os.Executable()
|
|
|
|
if err != nil {
|
2021-02-05 01:44:03 +00:00
|
|
|
return errors.Wrap(err, "Cannot find path name that start the process")
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
m, err := mgr.Connect()
|
|
|
|
if err != nil {
|
2021-02-05 01:44:03 +00:00
|
|
|
return errors.Wrap(err, "Cannot establish a connection to the service control manager")
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
defer m.Disconnect()
|
|
|
|
s, err := m.OpenService(windowsServiceName)
|
2021-01-13 16:20:41 +00:00
|
|
|
log := zeroLogger.With().Str(LogFieldWindowsServiceName, windowsServiceName).Logger()
|
2018-05-01 23:45:06 +00:00
|
|
|
if err == nil {
|
|
|
|
s.Close()
|
2021-02-05 01:44:03 +00:00
|
|
|
return fmt.Errorf("Service %s already exists", windowsServiceName)
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
2022-02-23 16:18:45 +00:00
|
|
|
extraArgs, err := getServiceExtraArgsFromCliArgs(c, &log)
|
|
|
|
if err != nil {
|
|
|
|
errMsg := "Unable to determine extra arguments for windows service"
|
|
|
|
log.Err(err).Msg(errMsg)
|
|
|
|
return errors.Wrap(err, errMsg)
|
|
|
|
}
|
|
|
|
|
2018-05-01 23:45:06 +00:00
|
|
|
config := mgr.Config{StartType: mgr.StartAutomatic, DisplayName: windowsServiceDescription}
|
2022-02-23 16:18:45 +00:00
|
|
|
s, err = m.CreateService(windowsServiceName, exepath, config, extraArgs...)
|
2018-05-01 23:45:06 +00:00
|
|
|
if err != nil {
|
2021-02-05 01:44:03 +00:00
|
|
|
return errors.Wrap(err, "Cannot install service")
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
defer s.Close()
|
2021-09-28 07:39:40 +00:00
|
|
|
log.Info().Msg("Cloudflare Tunnel agent service is installed")
|
2018-05-01 23:45:06 +00:00
|
|
|
err = eventlog.InstallAsEventCreate(windowsServiceName, eventlog.Error|eventlog.Warning|eventlog.Info)
|
|
|
|
if err != nil {
|
|
|
|
s.Delete()
|
2021-02-05 01:44:03 +00:00
|
|
|
return errors.Wrap(err, "Cannot install event logger")
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
2022-03-17 22:51:53 +00:00
|
|
|
|
2018-05-01 23:45:06 +00:00
|
|
|
err = configRecoveryOption(s.Handle)
|
|
|
|
if err != nil {
|
2020-12-28 18:10:01 +00:00
|
|
|
log.Err(err).Msg("Cannot set service recovery actions")
|
2020-11-25 06:55:13 +00:00
|
|
|
log.Info().Msgf("See %s to manually configure service recovery actions", windowsServiceUrl)
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
2022-03-17 22:51:53 +00:00
|
|
|
|
|
|
|
return s.Start()
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func uninstallWindowsService(c *cli.Context) error {
|
2020-12-28 18:10:01 +00:00
|
|
|
log := logger.CreateLoggerFromContext(c, logger.EnableTerminalLog).
|
|
|
|
With().
|
|
|
|
Str(LogFieldWindowsServiceName, windowsServiceName).Logger()
|
2020-04-29 20:51:32 +00:00
|
|
|
|
2021-09-28 07:39:40 +00:00
|
|
|
log.Info().Msg("Uninstalling Cloudflare Tunnel Windows Service")
|
2018-05-01 23:45:06 +00:00
|
|
|
m, err := mgr.Connect()
|
|
|
|
if err != nil {
|
2021-02-05 01:44:03 +00:00
|
|
|
return errors.Wrap(err, "Cannot establish a connection to the service control manager")
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
defer m.Disconnect()
|
|
|
|
s, err := m.OpenService(windowsServiceName)
|
|
|
|
if err != nil {
|
2021-02-05 01:44:03 +00:00
|
|
|
return fmt.Errorf("Service %s is not installed", windowsServiceName)
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
defer s.Close()
|
2022-03-17 22:51:53 +00:00
|
|
|
|
|
|
|
if status, err := s.Query(); err == nil && status.State == svc.Running {
|
|
|
|
log.Info().Msg("Stopping Cloudflare Tunnel agent service")
|
|
|
|
if _, err := s.Control(svc.Stop); err != nil {
|
|
|
|
log.Info().Err(err).Msg("Failed to stop Cloudflare Tunnel agent service, you may need to stop it manually to complete uninstall.")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-01 23:45:06 +00:00
|
|
|
err = s.Delete()
|
|
|
|
if err != nil {
|
2021-02-05 01:44:03 +00:00
|
|
|
return errors.Wrap(err, "Cannot delete service")
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
2021-09-28 07:39:40 +00:00
|
|
|
log.Info().Msg("Cloudflare Tunnel agent service is uninstalled")
|
2018-05-01 23:45:06 +00:00
|
|
|
err = eventlog.Remove(windowsServiceName)
|
|
|
|
if err != nil {
|
2021-02-05 01:44:03 +00:00
|
|
|
return errors.Wrap(err, "Cannot remove event logger")
|
2018-05-01 23:45:06 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// defined in https://msdn.microsoft.com/en-us/library/windows/desktop/ms685126(v=vs.85).aspx
|
|
|
|
type scAction int
|
|
|
|
|
|
|
|
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms685126(v=vs.85).aspx
|
|
|
|
const (
|
|
|
|
scActionNone scAction = iota
|
|
|
|
scActionRestart
|
|
|
|
scActionReboot
|
|
|
|
scActionRunCommand
|
|
|
|
)
|
|
|
|
|
|
|
|
// defined in https://msdn.microsoft.com/en-us/library/windows/desktop/ms685939(v=vs.85).aspx
|
|
|
|
type serviceFailureActions struct {
|
|
|
|
// time to wait to reset the failure count to zero if there are no failures in seconds
|
|
|
|
resetPeriod uint32
|
|
|
|
rebootMsg *uint16
|
|
|
|
command *uint16
|
|
|
|
// If failure count is greater than actionCount, the service controller repeats
|
|
|
|
// the last action in actions
|
|
|
|
actionCount uint32
|
|
|
|
actions uintptr
|
|
|
|
}
|
|
|
|
|
|
|
|
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms685937(v=vs.85).aspx
|
|
|
|
// Not supported in Windows Server 2003 and Windows XP
|
|
|
|
type serviceFailureActionsFlag struct {
|
|
|
|
// enableActionsForStopsWithErr is of type BOOL, which is declared as
|
|
|
|
// typedef int BOOL in C
|
|
|
|
enableActionsForStopsWithErr int
|
|
|
|
}
|
|
|
|
|
|
|
|
type recoveryAction struct {
|
|
|
|
recoveryType uint32
|
|
|
|
// The time to wait before performing the specified action, in milliseconds
|
|
|
|
delay uint32
|
|
|
|
}
|
|
|
|
|
|
|
|
// until https://github.com/golang/go/issues/23239 is release, we will need to
|
|
|
|
// configure through ChangeServiceConfig2
|
|
|
|
func configRecoveryOption(handle windows.Handle) error {
|
|
|
|
actions := []recoveryAction{
|
|
|
|
{recoveryType: uint32(scActionRestart), delay: uint32(recoverActionDelay / time.Millisecond)},
|
|
|
|
}
|
|
|
|
serviceRecoveryActions := serviceFailureActions{
|
|
|
|
resetPeriod: uint32(failureCountResetPeriod / time.Second),
|
|
|
|
actionCount: uint32(len(actions)),
|
|
|
|
actions: uintptr(unsafe.Pointer(&actions[0])),
|
|
|
|
}
|
|
|
|
if err := windows.ChangeServiceConfig2(handle, windows.SERVICE_CONFIG_FAILURE_ACTIONS, (*byte)(unsafe.Pointer(&serviceRecoveryActions))); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
serviceFailureActionsFlag := serviceFailureActionsFlag{enableActionsForStopsWithErr: 1}
|
|
|
|
return windows.ChangeServiceConfig2(handle, serviceConfigFailureActionsFlag, (*byte)(unsafe.Pointer(&serviceFailureActionsFlag)))
|
|
|
|
}
|