1
// Copyright 2012 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
7
// Package mgr can be used to manage Windows service programs.
8
// It can be used to install and remove them. It can also start,
9
// stop and pause them. The package can query / change current
10
// service state and config parameters.
18
"github.com/gabriel-samfira/sys/windows"
21
// Mgr is used to manage Windows service.
26
// Connect establishes a connection to the service control manager.
27
func Connect() (*Mgr, error) {
28
return ConnectRemote("")
31
// ConnectRemote establishes a connection to the
32
// service control manager on computer named host.
33
func ConnectRemote(host string) (*Mgr, error) {
36
s = syscall.StringToUTF16Ptr(host)
38
h, err := windows.OpenSCManager(s, nil, windows.SC_MANAGER_ALL_ACCESS)
42
return &Mgr{Handle: h}, nil
45
// Disconnect closes connection to the service control manager m.
46
func (m *Mgr) Disconnect() error {
47
return windows.CloseServiceHandle(m.Handle)
50
func toPtr(s string) *uint16 {
54
return syscall.StringToUTF16Ptr(s)
57
// toStringBlock terminates strings in ss with 0, and then
58
// concatenates them together. It also adds extra 0 at the end.
59
func toStringBlock(ss []string) *uint16 {
64
for _, s := range ss {
73
return &utf16.Encode([]rune(t))[0]
76
// CreateService installs new service name on the system.
77
// The service will be executed by running exepath binary.
78
// Use config c to specify service parameters.
79
// If service StartType is set to StartAutomatic,
80
// args will be passed to svc.Handle.Execute.
81
func (m *Mgr) CreateService(name, exepath string, c Config, args ...string) (*Service, error) {
83
c.StartType = StartManual
85
if c.ErrorControl == 0 {
86
c.ErrorControl = ErrorNormal
88
s := syscall.EscapeArg(exepath)
89
for _, v := range args {
90
s += " " + syscall.EscapeArg(v)
92
h, err := windows.CreateService(m.Handle, toPtr(name), toPtr(c.DisplayName),
93
windows.SERVICE_ALL_ACCESS, windows.SERVICE_WIN32_OWN_PROCESS,
94
c.StartType, c.ErrorControl, toPtr(s), toPtr(c.LoadOrderGroup),
95
nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName), toPtr(c.Password))
99
if c.Description != "" {
100
err = updateDescription(h, c.Description)
105
return &Service{Name: name, Handle: h}, nil
108
// OpenService retrieves access to service name, so it can
109
// be interrogated and controlled.
110
func (m *Mgr) OpenService(name string) (*Service, error) {
111
h, err := windows.OpenService(m.Handle, syscall.StringToUTF16Ptr(name), windows.SERVICE_ALL_ACCESS)
115
return &Service{Name: name, Handle: h}, nil