httpd.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #***************************************************************************
  4. # _ _ ____ _
  5. # Project ___| | | | _ \| |
  6. # / __| | | | |_) | |
  7. # | (__| |_| | _ <| |___
  8. # \___|\___/|_| \_\_____|
  9. #
  10. # Copyright (C) 2008 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
  11. #
  12. # This software is licensed as described in the file COPYING, which
  13. # you should have received as part of this distribution. The terms
  14. # are also available at https://curl.se/docs/copyright.html.
  15. #
  16. # You may opt to use, copy, modify, merge, publish, distribute and/or sell
  17. # copies of the Software, and permit persons to whom the Software is
  18. # furnished to do so, under the terms of the COPYING file.
  19. #
  20. # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  21. # KIND, either express or implied.
  22. #
  23. # SPDX-License-Identifier: curl
  24. #
  25. ###########################################################################
  26. #
  27. import inspect
  28. import logging
  29. import os
  30. import subprocess
  31. from datetime import timedelta, datetime
  32. from json import JSONEncoder
  33. import time
  34. from typing import List
  35. from .curl import CurlClient, ExecResult
  36. from .env import Env
  37. log = logging.getLogger(__name__)
  38. class Httpd:
  39. MODULES = [
  40. 'log_config', 'logio', 'unixd', 'version', 'watchdog',
  41. 'authn_core', 'authz_user', 'authz_core',
  42. 'env', 'filter', 'headers', 'mime',
  43. 'rewrite', 'http2', 'ssl',
  44. 'mpm_event',
  45. ]
  46. COMMON_MODULES_DIRS = [
  47. '/usr/lib/apache2/modules', # debian
  48. '/usr/libexec/apache2/', # macos
  49. ]
  50. MOD_CURLTEST = None
  51. def __init__(self, env: Env):
  52. self.env = env
  53. self._cmd = env.apachectl
  54. self._apache_dir = os.path.join(env.gen_dir, 'apache')
  55. self._run_dir = os.path.join(self._apache_dir, 'run')
  56. self._lock_dir = os.path.join(self._apache_dir, 'locks')
  57. self._docs_dir = os.path.join(self._apache_dir, 'docs')
  58. self._conf_dir = os.path.join(self._apache_dir, 'conf')
  59. self._conf_file = os.path.join(self._conf_dir, 'test.conf')
  60. self._logs_dir = os.path.join(self._apache_dir, 'logs')
  61. self._error_log = os.path.join(self._logs_dir, 'error_log')
  62. self._tmp_dir = os.path.join(self._apache_dir, 'tmp')
  63. self._mods_dir = None
  64. if env.apxs is not None:
  65. p = subprocess.run(args=[env.apxs, '-q', 'libexecdir'],
  66. capture_output=True, text=True)
  67. if p.returncode != 0:
  68. raise Exception(f'{env.apxs} failed to query libexecdir: {p}')
  69. self._mods_dir = p.stdout.strip()
  70. else:
  71. for md in self.COMMON_MODULES_DIRS:
  72. if os.path.isdir(md):
  73. self._mods_dir = md
  74. if self._mods_dir is None:
  75. raise Exception(f'apache modules dir cannot be found')
  76. self._process = None
  77. self._rmf(self._error_log)
  78. self._init_curltest()
  79. def clear_logs(self):
  80. self._rmf(self._error_log)
  81. def exists(self):
  82. return os.path.exists(self._cmd)
  83. def _run(self, args, intext=''):
  84. env = {}
  85. for key, val in os.environ.items():
  86. env[key] = val
  87. env['APACHE_RUN_DIR'] = self._run_dir
  88. env['APACHE_RUN_USER'] = os.environ['USER']
  89. env['APACHE_LOCK_DIR'] = self._lock_dir
  90. env['APACHE_CONFDIR'] = self._apache_dir
  91. p = subprocess.run(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
  92. cwd=self.env.gen_dir,
  93. input=intext.encode() if intext else None,
  94. env=env)
  95. start = datetime.now()
  96. return ExecResult(args=args, exit_code=p.returncode,
  97. stdout=p.stdout.decode().splitlines(),
  98. stderr=p.stderr.decode().splitlines(),
  99. duration=datetime.now() - start)
  100. def _apachectl(self, cmd: str):
  101. args = [self.env.apachectl,
  102. "-d", self._apache_dir,
  103. "-f", self._conf_file,
  104. "-k", cmd]
  105. return self._run(args=args)
  106. def start(self):
  107. if self._process:
  108. self.stop()
  109. self._write_config()
  110. with open(self._error_log, 'a') as fd:
  111. fd.write('start of server\n')
  112. with open(os.path.join(self._apache_dir, 'xxx'), 'a') as fd:
  113. fd.write('start of server\n')
  114. r = self._apachectl('start')
  115. if r.exit_code != 0:
  116. log.error(f'failed to start httpd: {r}')
  117. return False
  118. return self.wait_live(timeout=timedelta(seconds=5))
  119. def stop(self):
  120. r = self._apachectl('stop')
  121. if r.exit_code == 0:
  122. return self.wait_dead(timeout=timedelta(seconds=5))
  123. return r.exit_code == 0
  124. def restart(self):
  125. self.stop()
  126. return self.start()
  127. def reload(self):
  128. r = self._apachectl("graceful")
  129. if r.exit_code != 0:
  130. log.error(f'failed to reload httpd: {r}')
  131. return self.wait_live(timeout=timedelta(seconds=5))
  132. def wait_dead(self, timeout: timedelta):
  133. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  134. try_until = datetime.now() + timeout
  135. while datetime.now() < try_until:
  136. r = curl.http_get(url=f'http://{self.env.domain1}:{self.env.http_port}/')
  137. if r.exit_code != 0:
  138. return True
  139. time.sleep(.1)
  140. log.debug(f"Server still responding after {timeout}")
  141. return False
  142. def wait_live(self, timeout: timedelta):
  143. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  144. try_until = datetime.now() + timeout
  145. while datetime.now() < try_until:
  146. r = curl.http_get(url=f'http://{self.env.domain1}:{self.env.http_port}/')
  147. if r.exit_code == 0:
  148. return True
  149. time.sleep(.1)
  150. log.debug(f"Server still not responding after {timeout}")
  151. return False
  152. def _rmf(self, path):
  153. if os.path.exists(path):
  154. return os.remove(path)
  155. def _mkpath(self, path):
  156. if not os.path.exists(path):
  157. return os.makedirs(path)
  158. def _write_config(self):
  159. domain1 = self.env.domain1
  160. creds1 = self.env.get_credentials(domain1)
  161. domain2 = self.env.domain2
  162. creds2 = self.env.get_credentials(domain2)
  163. self._mkpath(self._conf_dir)
  164. self._mkpath(self._logs_dir)
  165. self._mkpath(self._tmp_dir)
  166. self._mkpath(os.path.join(self._docs_dir, 'two'))
  167. with open(os.path.join(self._docs_dir, 'data.json'), 'w') as fd:
  168. data = {
  169. 'server': f'{domain1}',
  170. }
  171. fd.write(JSONEncoder().encode(data))
  172. with open(os.path.join(self._docs_dir, 'two/data.json'), 'w') as fd:
  173. data = {
  174. 'server': f'{domain2}',
  175. }
  176. fd.write(JSONEncoder().encode(data))
  177. with open(self._conf_file, 'w') as fd:
  178. for m in self.MODULES:
  179. if os.path.exists(os.path.join(self._mods_dir, f'mod_{m}.so')):
  180. fd.write(f'LoadModule {m}_module "{self._mods_dir}/mod_{m}.so"\n')
  181. if Httpd.MOD_CURLTEST is not None:
  182. fd.write(f'LoadModule curltest_module \"{Httpd.MOD_CURLTEST}\"\n')
  183. conf = [ # base server config
  184. f'ServerRoot "{self._apache_dir}"',
  185. f'DefaultRuntimeDir logs',
  186. f'PidFile httpd.pid',
  187. f'ErrorLog {self._error_log}',
  188. f'LogLevel {self._get_log_level()}',
  189. f'LogLevel http:trace4',
  190. f'H2MinWorkers 16',
  191. f'H2MaxWorkers 128',
  192. f'Listen {self.env.http_port}',
  193. f'Listen {self.env.https_port}',
  194. f'TypesConfig "{self._conf_dir}/mime.types',
  195. # we want the quest string in a response header, so we
  196. # can check responses more easily
  197. f'Header set rquery "%{{QUERY_STRING}}s"',
  198. ]
  199. conf.extend([ # plain http host for domain1
  200. f'<VirtualHost *:{self.env.http_port}>',
  201. f' ServerName {domain1}',
  202. f' DocumentRoot "{self._docs_dir}"',
  203. ])
  204. conf.extend(self._curltest_conf())
  205. conf.extend([
  206. f'</VirtualHost>',
  207. f'',
  208. ])
  209. conf.extend([ # https host for domain1, h1 + h2
  210. f'<VirtualHost *:{self.env.https_port}>',
  211. f' ServerName {domain1}',
  212. f' Protocols h2 http/1.1',
  213. f' SSLEngine on',
  214. f' SSLCertificateFile {creds1.cert_file}',
  215. f' SSLCertificateKeyFile {creds1.pkey_file}',
  216. f' DocumentRoot "{self._docs_dir}"',
  217. ])
  218. conf.extend(self._curltest_conf())
  219. conf.extend([
  220. f'</VirtualHost>',
  221. f'',
  222. ])
  223. conf.extend([ # https host for domain2, no h2
  224. f'<VirtualHost *:{self.env.https_port}>',
  225. f' ServerName {domain2}',
  226. f' Protocols http/1.1',
  227. f' SSLEngine on',
  228. f' SSLCertificateFile {creds2.cert_file}',
  229. f' SSLCertificateKeyFile {creds2.pkey_file}',
  230. f' DocumentRoot "{self._docs_dir}/two"',
  231. ])
  232. conf.extend(self._curltest_conf())
  233. conf.extend([
  234. f'</VirtualHost>',
  235. f'',
  236. ])
  237. fd.write("\n".join(conf))
  238. with open(os.path.join(self._conf_dir, 'mime.types'), 'w') as fd:
  239. fd.write("\n".join([
  240. 'text/html html',
  241. 'application/json json',
  242. ''
  243. ]))
  244. def _get_log_level(self):
  245. if self.env.verbose > 3:
  246. return 'trace2'
  247. if self.env.verbose > 2:
  248. return 'trace1'
  249. if self.env.verbose > 1:
  250. return 'debug'
  251. return 'info'
  252. def _curltest_conf(self) -> List[str]:
  253. if Httpd.MOD_CURLTEST is not None:
  254. return [
  255. f' <Location /curltest/echo>',
  256. f' SetHandler curltest-echo',
  257. f' </Location>',
  258. f' <Location /curltest/tweak>',
  259. f' SetHandler curltest-tweak',
  260. f' </Location>',
  261. ]
  262. return []
  263. def _init_curltest(self):
  264. if Httpd.MOD_CURLTEST is not None:
  265. return
  266. local_dir = os.path.dirname(inspect.getfile(Httpd))
  267. p = subprocess.run([self.env.apxs, '-c', 'mod_curltest.c'],
  268. capture_output=True,
  269. cwd=os.path.join(local_dir, 'mod_curltest'))
  270. rv = p.returncode
  271. if rv != 0:
  272. log.error(f"compiling mod_curltest failed: {p.stderr}")
  273. raise Exception(f"compiling mod_curltest failed: {p.stderr}")
  274. Httpd.MOD_CURLTEST = os.path.join(
  275. local_dir, 'mod_curltest/.libs/mod_curltest.so')