service.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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.
  4. //go:build windows
  5. // +build windows
  6. // Package svc provides everything required to build Windows service.
  7. //
  8. package svc
  9. import (
  10. "errors"
  11. "sync"
  12. "unsafe"
  13. "golang.org/x/sys/internal/unsafeheader"
  14. "golang.org/x/sys/windows"
  15. )
  16. // State describes service execution state (Stopped, Running and so on).
  17. type State uint32
  18. const (
  19. Stopped = State(windows.SERVICE_STOPPED)
  20. StartPending = State(windows.SERVICE_START_PENDING)
  21. StopPending = State(windows.SERVICE_STOP_PENDING)
  22. Running = State(windows.SERVICE_RUNNING)
  23. ContinuePending = State(windows.SERVICE_CONTINUE_PENDING)
  24. PausePending = State(windows.SERVICE_PAUSE_PENDING)
  25. Paused = State(windows.SERVICE_PAUSED)
  26. )
  27. // Cmd represents service state change request. It is sent to a service
  28. // by the service manager, and should be actioned upon by the service.
  29. type Cmd uint32
  30. const (
  31. Stop = Cmd(windows.SERVICE_CONTROL_STOP)
  32. Pause = Cmd(windows.SERVICE_CONTROL_PAUSE)
  33. Continue = Cmd(windows.SERVICE_CONTROL_CONTINUE)
  34. Interrogate = Cmd(windows.SERVICE_CONTROL_INTERROGATE)
  35. Shutdown = Cmd(windows.SERVICE_CONTROL_SHUTDOWN)
  36. ParamChange = Cmd(windows.SERVICE_CONTROL_PARAMCHANGE)
  37. NetBindAdd = Cmd(windows.SERVICE_CONTROL_NETBINDADD)
  38. NetBindRemove = Cmd(windows.SERVICE_CONTROL_NETBINDREMOVE)
  39. NetBindEnable = Cmd(windows.SERVICE_CONTROL_NETBINDENABLE)
  40. NetBindDisable = Cmd(windows.SERVICE_CONTROL_NETBINDDISABLE)
  41. DeviceEvent = Cmd(windows.SERVICE_CONTROL_DEVICEEVENT)
  42. HardwareProfileChange = Cmd(windows.SERVICE_CONTROL_HARDWAREPROFILECHANGE)
  43. PowerEvent = Cmd(windows.SERVICE_CONTROL_POWEREVENT)
  44. SessionChange = Cmd(windows.SERVICE_CONTROL_SESSIONCHANGE)
  45. PreShutdown = Cmd(windows.SERVICE_CONTROL_PRESHUTDOWN)
  46. )
  47. // Accepted is used to describe commands accepted by the service.
  48. // Note that Interrogate is always accepted.
  49. type Accepted uint32
  50. const (
  51. AcceptStop = Accepted(windows.SERVICE_ACCEPT_STOP)
  52. AcceptShutdown = Accepted(windows.SERVICE_ACCEPT_SHUTDOWN)
  53. AcceptPauseAndContinue = Accepted(windows.SERVICE_ACCEPT_PAUSE_CONTINUE)
  54. AcceptParamChange = Accepted(windows.SERVICE_ACCEPT_PARAMCHANGE)
  55. AcceptNetBindChange = Accepted(windows.SERVICE_ACCEPT_NETBINDCHANGE)
  56. AcceptHardwareProfileChange = Accepted(windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE)
  57. AcceptPowerEvent = Accepted(windows.SERVICE_ACCEPT_POWEREVENT)
  58. AcceptSessionChange = Accepted(windows.SERVICE_ACCEPT_SESSIONCHANGE)
  59. AcceptPreShutdown = Accepted(windows.SERVICE_ACCEPT_PRESHUTDOWN)
  60. )
  61. // Status combines State and Accepted commands to fully describe running service.
  62. type Status struct {
  63. State State
  64. Accepts Accepted
  65. CheckPoint uint32 // used to report progress during a lengthy operation
  66. WaitHint uint32 // estimated time required for a pending operation, in milliseconds
  67. ProcessId uint32 // if the service is running, the process identifier of it, and otherwise zero
  68. Win32ExitCode uint32 // set if the service has exited with a win32 exit code
  69. ServiceSpecificExitCode uint32 // set if the service has exited with a service-specific exit code
  70. }
  71. // StartReason is the reason that the service was started.
  72. type StartReason uint32
  73. const (
  74. StartReasonDemand = StartReason(windows.SERVICE_START_REASON_DEMAND)
  75. StartReasonAuto = StartReason(windows.SERVICE_START_REASON_AUTO)
  76. StartReasonTrigger = StartReason(windows.SERVICE_START_REASON_TRIGGER)
  77. StartReasonRestartOnFailure = StartReason(windows.SERVICE_START_REASON_RESTART_ON_FAILURE)
  78. StartReasonDelayedAuto = StartReason(windows.SERVICE_START_REASON_DELAYEDAUTO)
  79. )
  80. // ChangeRequest is sent to the service Handler to request service status change.
  81. type ChangeRequest struct {
  82. Cmd Cmd
  83. EventType uint32
  84. EventData uintptr
  85. CurrentStatus Status
  86. Context uintptr
  87. }
  88. // Handler is the interface that must be implemented to build Windows service.
  89. type Handler interface {
  90. // Execute will be called by the package code at the start of
  91. // the service, and the service will exit once Execute completes.
  92. // Inside Execute you must read service change requests from r and
  93. // act accordingly. You must keep service control manager up to date
  94. // about state of your service by writing into s as required.
  95. // args contains service name followed by argument strings passed
  96. // to the service.
  97. // You can provide service exit code in exitCode return parameter,
  98. // with 0 being "no error". You can also indicate if exit code,
  99. // if any, is service specific or not by using svcSpecificEC
  100. // parameter.
  101. Execute(args []string, r <-chan ChangeRequest, s chan<- Status) (svcSpecificEC bool, exitCode uint32)
  102. }
  103. type ctlEvent struct {
  104. cmd Cmd
  105. eventType uint32
  106. eventData uintptr
  107. context uintptr
  108. errno uint32
  109. }
  110. // service provides access to windows service api.
  111. type service struct {
  112. name string
  113. h windows.Handle
  114. c chan ctlEvent
  115. handler Handler
  116. }
  117. type exitCode struct {
  118. isSvcSpecific bool
  119. errno uint32
  120. }
  121. func (s *service) updateStatus(status *Status, ec *exitCode) error {
  122. if s.h == 0 {
  123. return errors.New("updateStatus with no service status handle")
  124. }
  125. var t windows.SERVICE_STATUS
  126. t.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS
  127. t.CurrentState = uint32(status.State)
  128. if status.Accepts&AcceptStop != 0 {
  129. t.ControlsAccepted |= windows.SERVICE_ACCEPT_STOP
  130. }
  131. if status.Accepts&AcceptShutdown != 0 {
  132. t.ControlsAccepted |= windows.SERVICE_ACCEPT_SHUTDOWN
  133. }
  134. if status.Accepts&AcceptPauseAndContinue != 0 {
  135. t.ControlsAccepted |= windows.SERVICE_ACCEPT_PAUSE_CONTINUE
  136. }
  137. if status.Accepts&AcceptParamChange != 0 {
  138. t.ControlsAccepted |= windows.SERVICE_ACCEPT_PARAMCHANGE
  139. }
  140. if status.Accepts&AcceptNetBindChange != 0 {
  141. t.ControlsAccepted |= windows.SERVICE_ACCEPT_NETBINDCHANGE
  142. }
  143. if status.Accepts&AcceptHardwareProfileChange != 0 {
  144. t.ControlsAccepted |= windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE
  145. }
  146. if status.Accepts&AcceptPowerEvent != 0 {
  147. t.ControlsAccepted |= windows.SERVICE_ACCEPT_POWEREVENT
  148. }
  149. if status.Accepts&AcceptSessionChange != 0 {
  150. t.ControlsAccepted |= windows.SERVICE_ACCEPT_SESSIONCHANGE
  151. }
  152. if status.Accepts&AcceptPreShutdown != 0 {
  153. t.ControlsAccepted |= windows.SERVICE_ACCEPT_PRESHUTDOWN
  154. }
  155. if ec.errno == 0 {
  156. t.Win32ExitCode = windows.NO_ERROR
  157. t.ServiceSpecificExitCode = windows.NO_ERROR
  158. } else if ec.isSvcSpecific {
  159. t.Win32ExitCode = uint32(windows.ERROR_SERVICE_SPECIFIC_ERROR)
  160. t.ServiceSpecificExitCode = ec.errno
  161. } else {
  162. t.Win32ExitCode = ec.errno
  163. t.ServiceSpecificExitCode = windows.NO_ERROR
  164. }
  165. t.CheckPoint = status.CheckPoint
  166. t.WaitHint = status.WaitHint
  167. return windows.SetServiceStatus(s.h, &t)
  168. }
  169. var (
  170. initCallbacks sync.Once
  171. ctlHandlerCallback uintptr
  172. serviceMainCallback uintptr
  173. )
  174. func ctlHandler(ctl, evtype, evdata, context uintptr) uintptr {
  175. s := (*service)(unsafe.Pointer(context))
  176. e := ctlEvent{cmd: Cmd(ctl), eventType: uint32(evtype), eventData: evdata, context: 123456} // Set context to 123456 to test issue #25660.
  177. s.c <- e
  178. return 0
  179. }
  180. var theService service // This is, unfortunately, a global, which means only one service per process.
  181. // serviceMain is the entry point called by the service manager, registered earlier by
  182. // the call to StartServiceCtrlDispatcher.
  183. func serviceMain(argc uint32, argv **uint16) uintptr {
  184. handle, err := windows.RegisterServiceCtrlHandlerEx(windows.StringToUTF16Ptr(theService.name), ctlHandlerCallback, uintptr(unsafe.Pointer(&theService)))
  185. if sysErr, ok := err.(windows.Errno); ok {
  186. return uintptr(sysErr)
  187. } else if err != nil {
  188. return uintptr(windows.ERROR_UNKNOWN_EXCEPTION)
  189. }
  190. theService.h = handle
  191. defer func() {
  192. theService.h = 0
  193. }()
  194. var args16 []*uint16
  195. hdr := (*unsafeheader.Slice)(unsafe.Pointer(&args16))
  196. hdr.Data = unsafe.Pointer(argv)
  197. hdr.Len = int(argc)
  198. hdr.Cap = int(argc)
  199. args := make([]string, len(args16))
  200. for i, a := range args16 {
  201. args[i] = windows.UTF16PtrToString(a)
  202. }
  203. cmdsToHandler := make(chan ChangeRequest)
  204. changesFromHandler := make(chan Status)
  205. exitFromHandler := make(chan exitCode)
  206. go func() {
  207. ss, errno := theService.handler.Execute(args, cmdsToHandler, changesFromHandler)
  208. exitFromHandler <- exitCode{ss, errno}
  209. }()
  210. ec := exitCode{isSvcSpecific: true, errno: 0}
  211. outcr := ChangeRequest{
  212. CurrentStatus: Status{State: Stopped},
  213. }
  214. var outch chan ChangeRequest
  215. inch := theService.c
  216. loop:
  217. for {
  218. select {
  219. case r := <-inch:
  220. if r.errno != 0 {
  221. ec.errno = r.errno
  222. break loop
  223. }
  224. inch = nil
  225. outch = cmdsToHandler
  226. outcr.Cmd = r.cmd
  227. outcr.EventType = r.eventType
  228. outcr.EventData = r.eventData
  229. outcr.Context = r.context
  230. case outch <- outcr:
  231. inch = theService.c
  232. outch = nil
  233. case c := <-changesFromHandler:
  234. err := theService.updateStatus(&c, &ec)
  235. if err != nil {
  236. ec.errno = uint32(windows.ERROR_EXCEPTION_IN_SERVICE)
  237. if err2, ok := err.(windows.Errno); ok {
  238. ec.errno = uint32(err2)
  239. }
  240. break loop
  241. }
  242. outcr.CurrentStatus = c
  243. case ec = <-exitFromHandler:
  244. break loop
  245. }
  246. }
  247. theService.updateStatus(&Status{State: Stopped}, &ec)
  248. return windows.NO_ERROR
  249. }
  250. // Run executes service name by calling appropriate handler function.
  251. func Run(name string, handler Handler) error {
  252. initCallbacks.Do(func() {
  253. ctlHandlerCallback = windows.NewCallback(ctlHandler)
  254. serviceMainCallback = windows.NewCallback(serviceMain)
  255. })
  256. theService.name = name
  257. theService.handler = handler
  258. theService.c = make(chan ctlEvent)
  259. t := []windows.SERVICE_TABLE_ENTRY{
  260. {ServiceName: windows.StringToUTF16Ptr(theService.name), ServiceProc: serviceMainCallback},
  261. {ServiceName: nil, ServiceProc: 0},
  262. }
  263. return windows.StartServiceCtrlDispatcher(&t[0])
  264. }
  265. // StatusHandle returns service status handle. It is safe to call this function
  266. // from inside the Handler.Execute because then it is guaranteed to be set.
  267. func StatusHandle() windows.Handle {
  268. return theService.h
  269. }
  270. // DynamicStartReason returns the reason why the service was started. It is safe
  271. // to call this function from inside the Handler.Execute because then it is
  272. // guaranteed to be set.
  273. func DynamicStartReason() (StartReason, error) {
  274. var allocReason *uint32
  275. err := windows.QueryServiceDynamicInformation(theService.h, windows.SERVICE_DYNAMIC_INFORMATION_LEVEL_START_REASON, unsafe.Pointer(&allocReason))
  276. if err != nil {
  277. return 0, err
  278. }
  279. reason := StartReason(*allocReason)
  280. windows.LocalFree(windows.Handle(unsafe.Pointer(allocReason)))
  281. return reason, nil
  282. }