You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

363 lines
11 KiB

  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. // +build windows
  5. // Package svc provides everything required to build Windows service.
  6. //
  7. package svc
  8. import (
  9. "errors"
  10. "runtime"
  11. "syscall"
  12. "unsafe"
  13. "golang.org/x/sys/windows"
  14. )
  15. // State describes service execution state (Stopped, Running and so on).
  16. type State uint32
  17. const (
  18. Stopped = State(windows.SERVICE_STOPPED)
  19. StartPending = State(windows.SERVICE_START_PENDING)
  20. StopPending = State(windows.SERVICE_STOP_PENDING)
  21. Running = State(windows.SERVICE_RUNNING)
  22. ContinuePending = State(windows.SERVICE_CONTINUE_PENDING)
  23. PausePending = State(windows.SERVICE_PAUSE_PENDING)
  24. Paused = State(windows.SERVICE_PAUSED)
  25. )
  26. // Cmd represents service state change request. It is sent to a service
  27. // by the service manager, and should be actioned upon by the service.
  28. type Cmd uint32
  29. const (
  30. Stop = Cmd(windows.SERVICE_CONTROL_STOP)
  31. Pause = Cmd(windows.SERVICE_CONTROL_PAUSE)
  32. Continue = Cmd(windows.SERVICE_CONTROL_CONTINUE)
  33. Interrogate = Cmd(windows.SERVICE_CONTROL_INTERROGATE)
  34. Shutdown = Cmd(windows.SERVICE_CONTROL_SHUTDOWN)
  35. ParamChange = Cmd(windows.SERVICE_CONTROL_PARAMCHANGE)
  36. NetBindAdd = Cmd(windows.SERVICE_CONTROL_NETBINDADD)
  37. NetBindRemove = Cmd(windows.SERVICE_CONTROL_NETBINDREMOVE)
  38. NetBindEnable = Cmd(windows.SERVICE_CONTROL_NETBINDENABLE)
  39. NetBindDisable = Cmd(windows.SERVICE_CONTROL_NETBINDDISABLE)
  40. DeviceEvent = Cmd(windows.SERVICE_CONTROL_DEVICEEVENT)
  41. HardwareProfileChange = Cmd(windows.SERVICE_CONTROL_HARDWAREPROFILECHANGE)
  42. PowerEvent = Cmd(windows.SERVICE_CONTROL_POWEREVENT)
  43. SessionChange = Cmd(windows.SERVICE_CONTROL_SESSIONCHANGE)
  44. )
  45. // Accepted is used to describe commands accepted by the service.
  46. // Note that Interrogate is always accepted.
  47. type Accepted uint32
  48. const (
  49. AcceptStop = Accepted(windows.SERVICE_ACCEPT_STOP)
  50. AcceptShutdown = Accepted(windows.SERVICE_ACCEPT_SHUTDOWN)
  51. AcceptPauseAndContinue = Accepted(windows.SERVICE_ACCEPT_PAUSE_CONTINUE)
  52. AcceptParamChange = Accepted(windows.SERVICE_ACCEPT_PARAMCHANGE)
  53. AcceptNetBindChange = Accepted(windows.SERVICE_ACCEPT_NETBINDCHANGE)
  54. AcceptHardwareProfileChange = Accepted(windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE)
  55. AcceptPowerEvent = Accepted(windows.SERVICE_ACCEPT_POWEREVENT)
  56. AcceptSessionChange = Accepted(windows.SERVICE_ACCEPT_SESSIONCHANGE)
  57. )
  58. // Status combines State and Accepted commands to fully describe running service.
  59. type Status struct {
  60. State State
  61. Accepts Accepted
  62. CheckPoint uint32 // used to report progress during a lengthy operation
  63. WaitHint uint32 // estimated time required for a pending operation, in milliseconds
  64. }
  65. // ChangeRequest is sent to the service Handler to request service status change.
  66. type ChangeRequest struct {
  67. Cmd Cmd
  68. EventType uint32
  69. EventData uintptr
  70. CurrentStatus Status
  71. }
  72. // Handler is the interface that must be implemented to build Windows service.
  73. type Handler interface {
  74. // Execute will be called by the package code at the start of
  75. // the service, and the service will exit once Execute completes.
  76. // Inside Execute you must read service change requests from r and
  77. // act accordingly. You must keep service control manager up to date
  78. // about state of your service by writing into s as required.
  79. // args contains service name followed by argument strings passed
  80. // to the service.
  81. // You can provide service exit code in exitCode return parameter,
  82. // with 0 being "no error". You can also indicate if exit code,
  83. // if any, is service specific or not by using svcSpecificEC
  84. // parameter.
  85. Execute(args []string, r <-chan ChangeRequest, s chan<- Status) (svcSpecificEC bool, exitCode uint32)
  86. }
  87. var (
  88. // These are used by asm code.
  89. goWaitsH uintptr
  90. cWaitsH uintptr
  91. ssHandle uintptr
  92. sName *uint16
  93. sArgc uintptr
  94. sArgv **uint16
  95. ctlHandlerExProc uintptr
  96. cSetEvent uintptr
  97. cWaitForSingleObject uintptr
  98. cRegisterServiceCtrlHandlerExW uintptr
  99. )
  100. func init() {
  101. k := syscall.MustLoadDLL("kernel32.dll")
  102. cSetEvent = k.MustFindProc("SetEvent").Addr()
  103. cWaitForSingleObject = k.MustFindProc("WaitForSingleObject").Addr()
  104. a := syscall.MustLoadDLL("advapi32.dll")
  105. cRegisterServiceCtrlHandlerExW = a.MustFindProc("RegisterServiceCtrlHandlerExW").Addr()
  106. }
  107. // The HandlerEx prototype also has a context pointer but since we don't use
  108. // it at start-up time we don't have to pass it over either.
  109. type ctlEvent struct {
  110. cmd Cmd
  111. eventType uint32
  112. eventData uintptr
  113. errno uint32
  114. }
  115. // service provides access to windows service api.
  116. type service struct {
  117. name string
  118. h windows.Handle
  119. cWaits *event
  120. goWaits *event
  121. c chan ctlEvent
  122. handler Handler
  123. }
  124. func newService(name string, handler Handler) (*service, error) {
  125. var s service
  126. var err error
  127. s.name = name
  128. s.c = make(chan ctlEvent)
  129. s.handler = handler
  130. s.cWaits, err = newEvent()
  131. if err != nil {
  132. return nil, err
  133. }
  134. s.goWaits, err = newEvent()
  135. if err != nil {
  136. s.cWaits.Close()
  137. return nil, err
  138. }
  139. return &s, nil
  140. }
  141. func (s *service) close() error {
  142. s.cWaits.Close()
  143. s.goWaits.Close()
  144. return nil
  145. }
  146. type exitCode struct {
  147. isSvcSpecific bool
  148. errno uint32
  149. }
  150. func (s *service) updateStatus(status *Status, ec *exitCode) error {
  151. if s.h == 0 {
  152. return errors.New("updateStatus with no service status handle")
  153. }
  154. var t windows.SERVICE_STATUS
  155. t.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS
  156. t.CurrentState = uint32(status.State)
  157. if status.Accepts&AcceptStop != 0 {
  158. t.ControlsAccepted |= windows.SERVICE_ACCEPT_STOP
  159. }
  160. if status.Accepts&AcceptShutdown != 0 {
  161. t.ControlsAccepted |= windows.SERVICE_ACCEPT_SHUTDOWN
  162. }
  163. if status.Accepts&AcceptPauseAndContinue != 0 {
  164. t.ControlsAccepted |= windows.SERVICE_ACCEPT_PAUSE_CONTINUE
  165. }
  166. if status.Accepts&AcceptParamChange != 0 {
  167. t.ControlsAccepted |= windows.SERVICE_ACCEPT_PARAMCHANGE
  168. }
  169. if status.Accepts&AcceptNetBindChange != 0 {
  170. t.ControlsAccepted |= windows.SERVICE_ACCEPT_NETBINDCHANGE
  171. }
  172. if status.Accepts&AcceptHardwareProfileChange != 0 {
  173. t.ControlsAccepted |= windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE
  174. }
  175. if status.Accepts&AcceptPowerEvent != 0 {
  176. t.ControlsAccepted |= windows.SERVICE_ACCEPT_POWEREVENT
  177. }
  178. if status.Accepts&AcceptSessionChange != 0 {
  179. t.ControlsAccepted |= windows.SERVICE_ACCEPT_SESSIONCHANGE
  180. }
  181. if ec.errno == 0 {
  182. t.Win32ExitCode = windows.NO_ERROR
  183. t.ServiceSpecificExitCode = windows.NO_ERROR
  184. } else if ec.isSvcSpecific {
  185. t.Win32ExitCode = uint32(windows.ERROR_SERVICE_SPECIFIC_ERROR)
  186. t.ServiceSpecificExitCode = ec.errno
  187. } else {
  188. t.Win32ExitCode = ec.errno
  189. t.ServiceSpecificExitCode = windows.NO_ERROR
  190. }
  191. t.CheckPoint = status.CheckPoint
  192. t.WaitHint = status.WaitHint
  193. return windows.SetServiceStatus(s.h, &t)
  194. }
  195. const (
  196. sysErrSetServiceStatusFailed = uint32(syscall.APPLICATION_ERROR) + iota
  197. sysErrNewThreadInCallback
  198. )
  199. func (s *service) run() {
  200. s.goWaits.Wait()
  201. s.h = windows.Handle(ssHandle)
  202. argv := (*[100]*int16)(unsafe.Pointer(sArgv))[:sArgc]
  203. args := make([]string, len(argv))
  204. for i, a := range argv {
  205. args[i] = syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(a))[:])
  206. }
  207. cmdsToHandler := make(chan ChangeRequest)
  208. changesFromHandler := make(chan Status)
  209. exitFromHandler := make(chan exitCode)
  210. go func() {
  211. ss, errno := s.handler.Execute(args, cmdsToHandler, changesFromHandler)
  212. exitFromHandler <- exitCode{ss, errno}
  213. }()
  214. status := Status{State: Stopped}
  215. ec := exitCode{isSvcSpecific: true, errno: 0}
  216. var outch chan ChangeRequest
  217. inch := s.c
  218. var cmd Cmd
  219. var evtype uint32
  220. var evdata uintptr
  221. loop:
  222. for {
  223. select {
  224. case r := <-inch:
  225. if r.errno != 0 {
  226. ec.errno = r.errno
  227. break loop
  228. }
  229. inch = nil
  230. outch = cmdsToHandler
  231. cmd = r.cmd
  232. evtype = r.eventType
  233. evdata = r.eventData
  234. case outch <- ChangeRequest{cmd, evtype, evdata, status}:
  235. inch = s.c
  236. outch = nil
  237. case c := <-changesFromHandler:
  238. err := s.updateStatus(&c, &ec)
  239. if err != nil {
  240. // best suitable error number
  241. ec.errno = sysErrSetServiceStatusFailed
  242. if err2, ok := err.(syscall.Errno); ok {
  243. ec.errno = uint32(err2)
  244. }
  245. break loop
  246. }
  247. status = c
  248. case ec = <-exitFromHandler:
  249. break loop
  250. }
  251. }
  252. s.updateStatus(&Status{State: Stopped}, &ec)
  253. s.cWaits.Set()
  254. }
  255. func newCallback(fn interface{}) (cb uintptr, err error) {
  256. defer func() {
  257. r := recover()
  258. if r == nil {
  259. return
  260. }
  261. cb = 0
  262. switch v := r.(type) {
  263. case string:
  264. err = errors.New(v)
  265. case error:
  266. err = v
  267. default:
  268. err = errors.New("unexpected panic in syscall.NewCallback")
  269. }
  270. }()
  271. return syscall.NewCallback(fn), nil
  272. }
  273. // BUG(brainman): There is no mechanism to run multiple services
  274. // inside one single executable. Perhaps, it can be overcome by
  275. // using RegisterServiceCtrlHandlerEx Windows api.
  276. // Run executes service name by calling appropriate handler function.
  277. func Run(name string, handler Handler) error {
  278. runtime.LockOSThread()
  279. tid := windows.GetCurrentThreadId()
  280. s, err := newService(name, handler)
  281. if err != nil {
  282. return err
  283. }
  284. ctlHandler := func(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr {
  285. e := ctlEvent{cmd: Cmd(ctl), eventType: evtype, eventData: evdata}
  286. // We assume that this callback function is running on
  287. // the same thread as Run. Nowhere in MS documentation
  288. // I could find statement to guarantee that. So putting
  289. // check here to verify, otherwise things will go bad
  290. // quickly, if ignored.
  291. i := windows.GetCurrentThreadId()
  292. if i != tid {
  293. e.errno = sysErrNewThreadInCallback
  294. }
  295. s.c <- e
  296. // Always return NO_ERROR (0) for now.
  297. return 0
  298. }
  299. var svcmain uintptr
  300. getServiceMain(&svcmain)
  301. t := []windows.SERVICE_TABLE_ENTRY{
  302. {syscall.StringToUTF16Ptr(s.name), svcmain},
  303. {nil, 0},
  304. }
  305. goWaitsH = uintptr(s.goWaits.h)
  306. cWaitsH = uintptr(s.cWaits.h)
  307. sName = t[0].ServiceName
  308. ctlHandlerExProc, err = newCallback(ctlHandler)
  309. if err != nil {
  310. return err
  311. }
  312. go s.run()
  313. err = windows.StartServiceCtrlDispatcher(&t[0])
  314. if err != nil {
  315. return err
  316. }
  317. return nil
  318. }
  319. // StatusHandle returns service status handle. It is safe to call this function
  320. // from inside the Handler.Execute because then it is guaranteed to be set.
  321. // This code will have to change once multiple services are possible per process.
  322. func StatusHandle() windows.Handle {
  323. return windows.Handle(ssHandle)
  324. }