Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

_dumbwin32proc.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. # -*- test-case-name: twisted.test.test_process -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Windows Process Management, used with reactor.spawnProcess
  6. """
  7. import os
  8. import sys
  9. from zope.interface import implementer
  10. import pywintypes # type: ignore[import]
  11. # Win32 imports
  12. import win32api # type: ignore[import]
  13. import win32con # type: ignore[import]
  14. import win32event # type: ignore[import]
  15. import win32file # type: ignore[import]
  16. import win32pipe # type: ignore[import]
  17. import win32process # type: ignore[import]
  18. import win32security # type: ignore[import]
  19. from twisted.internet import _pollingfile, error
  20. from twisted.internet._baseprocess import BaseProcess
  21. from twisted.internet.interfaces import IConsumer, IProcessTransport, IProducer
  22. from twisted.python.win32 import quoteArguments
  23. # Security attributes for pipes
  24. PIPE_ATTRS_INHERITABLE = win32security.SECURITY_ATTRIBUTES()
  25. PIPE_ATTRS_INHERITABLE.bInheritHandle = 1
  26. def debug(msg):
  27. print(msg)
  28. sys.stdout.flush()
  29. class _Reaper(_pollingfile._PollableResource):
  30. def __init__(self, proc):
  31. self.proc = proc
  32. def checkWork(self):
  33. if (
  34. win32event.WaitForSingleObject(self.proc.hProcess, 0)
  35. != win32event.WAIT_OBJECT_0
  36. ):
  37. return 0
  38. exitCode = win32process.GetExitCodeProcess(self.proc.hProcess)
  39. self.deactivate()
  40. self.proc.processEnded(exitCode)
  41. return 0
  42. def _findShebang(filename):
  43. """
  44. Look for a #! line, and return the value following the #! if one exists, or
  45. None if this file is not a script.
  46. I don't know if there are any conventions for quoting in Windows shebang
  47. lines, so this doesn't support any; therefore, you may not pass any
  48. arguments to scripts invoked as filters. That's probably wrong, so if
  49. somebody knows more about the cultural expectations on Windows, please feel
  50. free to fix.
  51. This shebang line support was added in support of the CGI tests;
  52. appropriately enough, I determined that shebang lines are culturally
  53. accepted in the Windows world through this page::
  54. http://www.cgi101.com/learn/connect/winxp.html
  55. @param filename: str representing a filename
  56. @return: a str representing another filename.
  57. """
  58. with open(filename) as f:
  59. if f.read(2) == "#!":
  60. exe = f.readline(1024).strip("\n")
  61. return exe
  62. def _invalidWin32App(pywinerr):
  63. """
  64. Determine if a pywintypes.error is telling us that the given process is
  65. 'not a valid win32 application', i.e. not a PE format executable.
  66. @param pywinerr: a pywintypes.error instance raised by CreateProcess
  67. @return: a boolean
  68. """
  69. # Let's do this better in the future, but I have no idea what this error
  70. # is; MSDN doesn't mention it, and there is no symbolic constant in
  71. # win32process module that represents 193.
  72. return pywinerr.args[0] == 193
  73. @implementer(IProcessTransport, IConsumer, IProducer)
  74. class Process(_pollingfile._PollingTimer, BaseProcess):
  75. """
  76. A process that integrates with the Twisted event loop.
  77. If your subprocess is a python program, you need to:
  78. - Run python.exe with the '-u' command line option - this turns on
  79. unbuffered I/O. Buffering stdout/err/in can cause problems, see e.g.
  80. http://support.microsoft.com/default.aspx?scid=kb;EN-US;q1903
  81. - If you don't want Windows messing with data passed over
  82. stdin/out/err, set the pipes to be in binary mode::
  83. import os, sys, mscvrt
  84. msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
  85. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  86. msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
  87. """
  88. closedNotifies = 0
  89. def __init__(self, reactor, protocol, command, args, environment, path):
  90. """
  91. Create a new child process.
  92. """
  93. _pollingfile._PollingTimer.__init__(self, reactor)
  94. BaseProcess.__init__(self, protocol)
  95. # security attributes for pipes
  96. sAttrs = win32security.SECURITY_ATTRIBUTES()
  97. sAttrs.bInheritHandle = 1
  98. # create the pipes which will connect to the secondary process
  99. self.hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0)
  100. self.hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0)
  101. hStdinR, self.hStdinW = win32pipe.CreatePipe(sAttrs, 0)
  102. win32pipe.SetNamedPipeHandleState(
  103. self.hStdinW, win32pipe.PIPE_NOWAIT, None, None
  104. )
  105. # set the info structure for the new process.
  106. StartupInfo = win32process.STARTUPINFO()
  107. StartupInfo.hStdOutput = hStdoutW
  108. StartupInfo.hStdError = hStderrW
  109. StartupInfo.hStdInput = hStdinR
  110. StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES
  111. # Create new handles whose inheritance property is false
  112. currentPid = win32api.GetCurrentProcess()
  113. tmp = win32api.DuplicateHandle(
  114. currentPid, self.hStdoutR, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS
  115. )
  116. win32file.CloseHandle(self.hStdoutR)
  117. self.hStdoutR = tmp
  118. tmp = win32api.DuplicateHandle(
  119. currentPid, self.hStderrR, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS
  120. )
  121. win32file.CloseHandle(self.hStderrR)
  122. self.hStderrR = tmp
  123. tmp = win32api.DuplicateHandle(
  124. currentPid, self.hStdinW, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS
  125. )
  126. win32file.CloseHandle(self.hStdinW)
  127. self.hStdinW = tmp
  128. # Add the specified environment to the current environment - this is
  129. # necessary because certain operations are only supported on Windows
  130. # if certain environment variables are present.
  131. env = os.environ.copy()
  132. env.update(environment or {})
  133. env = {os.fsdecode(key): os.fsdecode(value) for key, value in env.items()}
  134. # Make sure all the arguments are Unicode.
  135. args = [os.fsdecode(x) for x in args]
  136. cmdline = quoteArguments(args)
  137. # The command, too, needs to be Unicode, if it is a value.
  138. command = os.fsdecode(command) if command else command
  139. path = os.fsdecode(path) if path else path
  140. # TODO: error detection here. See #2787 and #4184.
  141. def doCreate():
  142. flags = win32con.CREATE_NO_WINDOW
  143. self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess(
  144. command, cmdline, None, None, 1, flags, env, path, StartupInfo
  145. )
  146. try:
  147. doCreate()
  148. except pywintypes.error as pwte:
  149. if not _invalidWin32App(pwte):
  150. # This behavior isn't _really_ documented, but let's make it
  151. # consistent with the behavior that is documented.
  152. raise OSError(pwte)
  153. else:
  154. # look for a shebang line. Insert the original 'command'
  155. # (actually a script) into the new arguments list.
  156. sheb = _findShebang(command)
  157. if sheb is None:
  158. raise OSError(
  159. "%r is neither a Windows executable, "
  160. "nor a script with a shebang line" % command
  161. )
  162. else:
  163. args = list(args)
  164. args.insert(0, command)
  165. cmdline = quoteArguments(args)
  166. origcmd = command
  167. command = sheb
  168. try:
  169. # Let's try again.
  170. doCreate()
  171. except pywintypes.error as pwte2:
  172. # d'oh, failed again!
  173. if _invalidWin32App(pwte2):
  174. raise OSError(
  175. "%r has an invalid shebang line: "
  176. "%r is not a valid executable" % (origcmd, sheb)
  177. )
  178. raise OSError(pwte2)
  179. # close handles which only the child will use
  180. win32file.CloseHandle(hStderrW)
  181. win32file.CloseHandle(hStdoutW)
  182. win32file.CloseHandle(hStdinR)
  183. # set up everything
  184. self.stdout = _pollingfile._PollableReadPipe(
  185. self.hStdoutR,
  186. lambda data: self.proto.childDataReceived(1, data),
  187. self.outConnectionLost,
  188. )
  189. self.stderr = _pollingfile._PollableReadPipe(
  190. self.hStderrR,
  191. lambda data: self.proto.childDataReceived(2, data),
  192. self.errConnectionLost,
  193. )
  194. self.stdin = _pollingfile._PollableWritePipe(
  195. self.hStdinW, self.inConnectionLost
  196. )
  197. for pipewatcher in self.stdout, self.stderr, self.stdin:
  198. self._addPollableResource(pipewatcher)
  199. # notify protocol
  200. self.proto.makeConnection(self)
  201. self._addPollableResource(_Reaper(self))
  202. def signalProcess(self, signalID):
  203. if self.pid is None:
  204. raise error.ProcessExitedAlready()
  205. if signalID in ("INT", "TERM", "KILL"):
  206. win32process.TerminateProcess(self.hProcess, 1)
  207. def _getReason(self, status):
  208. if status == 0:
  209. return error.ProcessDone(status)
  210. return error.ProcessTerminated(status)
  211. def write(self, data):
  212. """
  213. Write data to the process' stdin.
  214. @type data: C{bytes}
  215. """
  216. self.stdin.write(data)
  217. def writeSequence(self, seq):
  218. """
  219. Write data to the process' stdin.
  220. @type seq: C{list} of C{bytes}
  221. """
  222. self.stdin.writeSequence(seq)
  223. def writeToChild(self, fd, data):
  224. """
  225. Similar to L{ITransport.write} but also allows the file descriptor in
  226. the child process which will receive the bytes to be specified.
  227. This implementation is limited to writing to the child's standard input.
  228. @param fd: The file descriptor to which to write. Only stdin (C{0}) is
  229. supported.
  230. @type fd: C{int}
  231. @param data: The bytes to write.
  232. @type data: C{bytes}
  233. @return: L{None}
  234. @raise KeyError: If C{fd} is anything other than the stdin file
  235. descriptor (C{0}).
  236. """
  237. if fd == 0:
  238. self.stdin.write(data)
  239. else:
  240. raise KeyError(fd)
  241. def closeChildFD(self, fd):
  242. if fd == 0:
  243. self.closeStdin()
  244. elif fd == 1:
  245. self.closeStdout()
  246. elif fd == 2:
  247. self.closeStderr()
  248. else:
  249. raise NotImplementedError(
  250. "Only standard-IO file descriptors available on win32"
  251. )
  252. def closeStdin(self):
  253. """Close the process' stdin."""
  254. self.stdin.close()
  255. def closeStderr(self):
  256. self.stderr.close()
  257. def closeStdout(self):
  258. self.stdout.close()
  259. def loseConnection(self):
  260. """
  261. Close the process' stdout, in and err.
  262. """
  263. self.closeStdin()
  264. self.closeStdout()
  265. self.closeStderr()
  266. def outConnectionLost(self):
  267. self.proto.childConnectionLost(1)
  268. self.connectionLostNotify()
  269. def errConnectionLost(self):
  270. self.proto.childConnectionLost(2)
  271. self.connectionLostNotify()
  272. def inConnectionLost(self):
  273. self.proto.childConnectionLost(0)
  274. self.connectionLostNotify()
  275. def connectionLostNotify(self):
  276. """
  277. Will be called 3 times, by stdout/err threads and process handle.
  278. """
  279. self.closedNotifies += 1
  280. self.maybeCallProcessEnded()
  281. def maybeCallProcessEnded(self):
  282. if self.closedNotifies == 3 and self.lostProcess:
  283. win32file.CloseHandle(self.hProcess)
  284. win32file.CloseHandle(self.hThread)
  285. self.hProcess = None
  286. self.hThread = None
  287. BaseProcess.maybeCallProcessEnded(self)
  288. # IConsumer
  289. def registerProducer(self, producer, streaming):
  290. self.stdin.registerProducer(producer, streaming)
  291. def unregisterProducer(self):
  292. self.stdin.unregisterProducer()
  293. # IProducer
  294. def pauseProducing(self):
  295. self._pause()
  296. def resumeProducing(self):
  297. self._unpause()
  298. def stopProducing(self):
  299. self.loseConnection()
  300. def getHost(self):
  301. # ITransport.getHost
  302. raise NotImplementedError("Unimplemented: Process.getHost")
  303. def getPeer(self):
  304. # ITransport.getPeer
  305. raise NotImplementedError("Unimplemented: Process.getPeer")
  306. def __repr__(self) -> str:
  307. """
  308. Return a string representation of the process.
  309. """
  310. return f"<{self.__class__.__name__} pid={self.pid}>"