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 "golang.org/x/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 if c.ServiceType == 0 {
89 c.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS
91 s := syscall.EscapeArg(exepath)
92 for _, v := range args {
93 s += " " + syscall.EscapeArg(v)
95 h, err := windows.CreateService(m.Handle, toPtr(name), toPtr(c.DisplayName),
96 windows.SERVICE_ALL_ACCESS, c.ServiceType,
97 c.StartType, c.ErrorControl, toPtr(s), toPtr(c.LoadOrderGroup),
98 nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName), toPtr(c.Password))
102 if c.Description != "" {
103 err = updateDescription(h, c.Description)
108 return &Service{Name: name, Handle: h}, nil
111 // OpenService retrieves access to service name, so it can
112 // be interrogated and controlled.
113 func (m *Mgr) OpenService(name string) (*Service, error) {
114 h, err := windows.OpenService(m.Handle, syscall.StringToUTF16Ptr(name), windows.SERVICE_ALL_ACCESS)
118 return &Service{Name: name, Handle: h}, nil