tap.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # -*- test-case-name: twisted.web.test.test_tap -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Support for creating a service which runs a web server.
  6. """
  7. from __future__ import absolute_import, division
  8. import os
  9. from twisted.application import internet, service, strports
  10. from twisted.internet import interfaces, reactor
  11. from twisted.python import usage, reflect, threadpool
  12. from twisted.spread import pb
  13. from twisted.web import distrib
  14. from twisted.web import server, static, script, demo, wsgi
  15. from twisted.web import twcgi
  16. class Options(usage.Options):
  17. """
  18. Define the options accepted by the I{twistd web} plugin.
  19. """
  20. synopsis = "[web options]"
  21. optParameters = [["port", "p", None, "strports description of the port to "
  22. "start the server on."],
  23. ["logfile", "l", None,
  24. "Path to web CLF (Combined Log Format) log file."],
  25. ["https", None, None,
  26. "Port to listen on for Secure HTTP."],
  27. ["certificate", "c", "server.pem",
  28. "SSL certificate to use for HTTPS. "],
  29. ["privkey", "k", "server.pem",
  30. "SSL certificate to use for HTTPS."],
  31. ]
  32. optFlags = [
  33. ["notracebacks", "n", (
  34. "Do not display tracebacks in broken web pages. Displaying "
  35. "tracebacks to users may be security risk!")],
  36. ]
  37. optFlags.append([
  38. "personal", "",
  39. "Instead of generating a webserver, generate a "
  40. "ResourcePublisher which listens on the port given by "
  41. "--port, or ~/%s " % (distrib.UserDirectory.userSocketName,) +
  42. "if --port is not specified."])
  43. compData = usage.Completions(
  44. optActions={"logfile" : usage.CompleteFiles("*.log"),
  45. "certificate" : usage.CompleteFiles("*.pem"),
  46. "privkey" : usage.CompleteFiles("*.pem")}
  47. )
  48. longdesc = """\
  49. This starts a webserver. If you specify no arguments, it will be a
  50. demo webserver that has the Test class from twisted.web.demo in it."""
  51. def __init__(self):
  52. usage.Options.__init__(self)
  53. self['indexes'] = []
  54. self['root'] = None
  55. def opt_index(self, indexName):
  56. """
  57. Add the name of a file used to check for directory indexes.
  58. [default: index, index.html]
  59. """
  60. self['indexes'].append(indexName)
  61. opt_i = opt_index
  62. def opt_user(self):
  63. """
  64. Makes a server with ~/public_html and ~/.twistd-web-pb support for
  65. users.
  66. """
  67. self['root'] = distrib.UserDirectory()
  68. opt_u = opt_user
  69. def opt_path(self, path):
  70. """
  71. <path> is either a specific file or a directory to be set as the root
  72. of the web server. Use this if you have a directory full of HTML, cgi,
  73. epy, or rpy files or any other files that you want to be served up raw.
  74. """
  75. self['root'] = static.File(os.path.abspath(path))
  76. self['root'].processors = {
  77. '.epy': script.PythonScript,
  78. '.rpy': script.ResourceScript,
  79. }
  80. self['root'].processors['.cgi'] = twcgi.CGIScript
  81. def opt_processor(self, proc):
  82. """
  83. `ext=class' where `class' is added as a Processor for files ending
  84. with `ext'.
  85. """
  86. if not isinstance(self['root'], static.File):
  87. raise usage.UsageError(
  88. "You can only use --processor after --path.")
  89. ext, klass = proc.split('=', 1)
  90. self['root'].processors[ext] = reflect.namedClass(klass)
  91. def opt_class(self, className):
  92. """
  93. Create a Resource subclass with a zero-argument constructor.
  94. """
  95. classObj = reflect.namedClass(className)
  96. self['root'] = classObj()
  97. def opt_resource_script(self, name):
  98. """
  99. An .rpy file to be used as the root resource of the webserver.
  100. """
  101. self['root'] = script.ResourceScriptWrapper(name)
  102. def opt_wsgi(self, name):
  103. """
  104. The FQPN of a WSGI application object to serve as the root resource of
  105. the webserver.
  106. """
  107. try:
  108. application = reflect.namedAny(name)
  109. except (AttributeError, ValueError):
  110. raise usage.UsageError("No such WSGI application: %r" % (name,))
  111. pool = threadpool.ThreadPool()
  112. reactor.callWhenRunning(pool.start)
  113. reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
  114. self['root'] = wsgi.WSGIResource(reactor, pool, application)
  115. def opt_mime_type(self, defaultType):
  116. """
  117. Specify the default mime-type for static files.
  118. """
  119. if not isinstance(self['root'], static.File):
  120. raise usage.UsageError(
  121. "You can only use --mime_type after --path.")
  122. self['root'].defaultType = defaultType
  123. opt_m = opt_mime_type
  124. def opt_allow_ignore_ext(self):
  125. """
  126. Specify whether or not a request for 'foo' should return 'foo.ext'
  127. """
  128. if not isinstance(self['root'], static.File):
  129. raise usage.UsageError("You can only use --allow_ignore_ext "
  130. "after --path.")
  131. self['root'].ignoreExt('*')
  132. def opt_ignore_ext(self, ext):
  133. """
  134. Specify an extension to ignore. These will be processed in order.
  135. """
  136. if not isinstance(self['root'], static.File):
  137. raise usage.UsageError("You can only use --ignore_ext "
  138. "after --path.")
  139. self['root'].ignoreExt(ext)
  140. def postOptions(self):
  141. """
  142. Set up conditional defaults and check for dependencies.
  143. If SSL is not available but an HTTPS server was configured, raise a
  144. L{UsageError} indicating that this is not possible.
  145. If no server port was supplied, select a default appropriate for the
  146. other options supplied.
  147. """
  148. if self['https']:
  149. try:
  150. reflect.namedModule('OpenSSL.SSL')
  151. except ImportError:
  152. raise usage.UsageError("SSL support not installed")
  153. if self['port'] is None:
  154. if self['personal']:
  155. path = os.path.expanduser(
  156. os.path.join('~', distrib.UserDirectory.userSocketName))
  157. self['port'] = 'unix:' + path
  158. else:
  159. self['port'] = 'tcp:8080'
  160. def makePersonalServerFactory(site):
  161. """
  162. Create and return a factory which will respond to I{distrib} requests
  163. against the given site.
  164. @type site: L{twisted.web.server.Site}
  165. @rtype: L{twisted.internet.protocol.Factory}
  166. """
  167. return pb.PBServerFactory(distrib.ResourcePublisher(site))
  168. def makeService(config):
  169. s = service.MultiService()
  170. if config['root']:
  171. root = config['root']
  172. if config['indexes']:
  173. config['root'].indexNames = config['indexes']
  174. else:
  175. # This really ought to be web.Admin or something
  176. root = demo.Test()
  177. if isinstance(root, static.File):
  178. root.registry.setComponent(interfaces.IServiceCollection, s)
  179. if config['logfile']:
  180. site = server.Site(root, logPath=config['logfile'])
  181. else:
  182. site = server.Site(root)
  183. site.displayTracebacks = not config["notracebacks"]
  184. if config['personal']:
  185. personal = strports.service(
  186. config['port'], makePersonalServerFactory(site))
  187. personal.setServiceParent(s)
  188. else:
  189. if config['https']:
  190. from twisted.internet.ssl import DefaultOpenSSLContextFactory
  191. i = internet.SSLServer(int(config['https']), site,
  192. DefaultOpenSSLContextFactory(config['privkey'],
  193. config['certificate']))
  194. i.setServiceParent(s)
  195. strports.service(config['port'], site).setServiceParent(s)
  196. return s