httpd.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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, Union, Optional
  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', 'authz_host',
  42. 'env', 'filter', 'headers', 'mime',
  43. 'rewrite', 'http2', 'ssl', 'proxy', 'proxy_http', 'proxy_connect',
  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. self._extra_configs = {}
  65. assert env.apxs
  66. p = subprocess.run(args=[env.apxs, '-q', 'libexecdir'],
  67. capture_output=True, text=True)
  68. if p.returncode != 0:
  69. raise Exception(f'{env.apxs} failed to query libexecdir: {p}')
  70. self._mods_dir = p.stdout.strip()
  71. if self._mods_dir is None:
  72. raise Exception(f'apache modules dir cannot be found')
  73. if not os.path.exists(self._mods_dir):
  74. raise Exception(f'apache modules dir does not exist: {self._mods_dir}')
  75. self._process = None
  76. self._rmf(self._error_log)
  77. self._init_curltest()
  78. @property
  79. def docs_dir(self):
  80. return self._docs_dir
  81. def clear_logs(self):
  82. self._rmf(self._error_log)
  83. def exists(self):
  84. return os.path.exists(self._cmd)
  85. def set_extra_config(self, domain: str, lines: Optional[Union[str, List[str]]]):
  86. if lines is None:
  87. self._extra_configs.pop(domain, None)
  88. else:
  89. self._extra_configs[domain] = lines
  90. def _run(self, args, intext=''):
  91. env = {}
  92. for key, val in os.environ.items():
  93. env[key] = val
  94. env['APACHE_RUN_DIR'] = self._run_dir
  95. env['APACHE_RUN_USER'] = os.environ['USER']
  96. env['APACHE_LOCK_DIR'] = self._lock_dir
  97. env['APACHE_CONFDIR'] = self._apache_dir
  98. p = subprocess.run(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
  99. cwd=self.env.gen_dir,
  100. input=intext.encode() if intext else None,
  101. env=env)
  102. start = datetime.now()
  103. return ExecResult(args=args, exit_code=p.returncode,
  104. stdout=p.stdout.decode().splitlines(),
  105. stderr=p.stderr.decode().splitlines(),
  106. duration=datetime.now() - start)
  107. def _apachectl(self, cmd: str):
  108. args = [self.env.apachectl,
  109. "-d", self._apache_dir,
  110. "-f", self._conf_file,
  111. "-k", cmd]
  112. return self._run(args=args)
  113. def start(self):
  114. if self._process:
  115. self.stop()
  116. self._write_config()
  117. with open(self._error_log, 'a') as fd:
  118. fd.write('start of server\n')
  119. with open(os.path.join(self._apache_dir, 'xxx'), 'a') as fd:
  120. fd.write('start of server\n')
  121. r = self._apachectl('start')
  122. if r.exit_code != 0:
  123. log.error(f'failed to start httpd: {r}')
  124. return False
  125. return self.wait_live(timeout=timedelta(seconds=5))
  126. def stop(self):
  127. r = self._apachectl('stop')
  128. if r.exit_code == 0:
  129. return self.wait_dead(timeout=timedelta(seconds=5))
  130. return r.exit_code == 0
  131. def restart(self):
  132. self.stop()
  133. return self.start()
  134. def reload(self):
  135. self._write_config()
  136. r = self._apachectl("graceful")
  137. if r.exit_code != 0:
  138. log.error(f'failed to reload httpd: {r}')
  139. return self.wait_live(timeout=timedelta(seconds=5))
  140. def wait_dead(self, timeout: timedelta):
  141. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  142. try_until = datetime.now() + timeout
  143. while datetime.now() < try_until:
  144. r = curl.http_get(url=f'http://{self.env.domain1}:{self.env.http_port}/')
  145. if r.exit_code != 0:
  146. return True
  147. time.sleep(.1)
  148. log.debug(f"Server still responding after {timeout}")
  149. return False
  150. def wait_live(self, timeout: timedelta):
  151. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  152. try_until = datetime.now() + timeout
  153. while datetime.now() < try_until:
  154. r = curl.http_get(url=f'http://{self.env.domain1}:{self.env.http_port}/')
  155. if r.exit_code == 0:
  156. return True
  157. time.sleep(.1)
  158. log.debug(f"Server still not responding after {timeout}")
  159. return False
  160. def _rmf(self, path):
  161. if os.path.exists(path):
  162. return os.remove(path)
  163. def _mkpath(self, path):
  164. if not os.path.exists(path):
  165. return os.makedirs(path)
  166. def _write_config(self):
  167. domain1 = self.env.domain1
  168. creds1 = self.env.get_credentials(domain1)
  169. domain2 = self.env.domain2
  170. creds2 = self.env.get_credentials(domain2)
  171. proxy_domain = self.env.proxy_domain
  172. proxy_creds = self.env.get_credentials(proxy_domain)
  173. self._mkpath(self._conf_dir)
  174. self._mkpath(self._logs_dir)
  175. self._mkpath(self._tmp_dir)
  176. self._mkpath(os.path.join(self._docs_dir, 'two'))
  177. with open(os.path.join(self._docs_dir, 'data.json'), 'w') as fd:
  178. data = {
  179. 'server': f'{domain1}',
  180. }
  181. fd.write(JSONEncoder().encode(data))
  182. with open(os.path.join(self._docs_dir, 'two/data.json'), 'w') as fd:
  183. data = {
  184. 'server': f'{domain2}',
  185. }
  186. fd.write(JSONEncoder().encode(data))
  187. with open(self._conf_file, 'w') as fd:
  188. for m in self.MODULES:
  189. if os.path.exists(os.path.join(self._mods_dir, f'mod_{m}.so')):
  190. fd.write(f'LoadModule {m}_module "{self._mods_dir}/mod_{m}.so"\n')
  191. if Httpd.MOD_CURLTEST is not None:
  192. fd.write(f'LoadModule curltest_module \"{Httpd.MOD_CURLTEST}\"\n')
  193. conf = [ # base server config
  194. f'ServerRoot "{self._apache_dir}"',
  195. f'DefaultRuntimeDir logs',
  196. f'PidFile httpd.pid',
  197. f'ErrorLog {self._error_log}',
  198. f'LogLevel {self._get_log_level()}',
  199. f'LogLevel http:trace4',
  200. f'LogLevel proxy:trace4',
  201. f'LogLevel proxy_http:trace4',
  202. f'H2MinWorkers 16',
  203. f'H2MaxWorkers 128',
  204. f'H2Direct on',
  205. f'Listen {self.env.http_port}',
  206. f'Listen {self.env.https_port}',
  207. f'Listen {self.env.proxy_port}',
  208. f'Listen {self.env.proxys_port}',
  209. f'TypesConfig "{self._conf_dir}/mime.types',
  210. ]
  211. conf.extend([ # plain http host for domain1
  212. f'<VirtualHost *:{self.env.http_port}>',
  213. f' ServerName {domain1}',
  214. f' ServerAlias localhost',
  215. f' DocumentRoot "{self._docs_dir}"',
  216. f' Protocols h2c http/1.1',
  217. ])
  218. conf.extend(self._curltest_conf())
  219. conf.extend([
  220. f'</VirtualHost>',
  221. f'',
  222. ])
  223. conf.extend([ # https host for domain1, h1 + h2
  224. f'<VirtualHost *:{self.env.https_port}>',
  225. f' ServerName {domain1}',
  226. f' Protocols h2 http/1.1',
  227. f' SSLEngine on',
  228. f' SSLCertificateFile {creds1.cert_file}',
  229. f' SSLCertificateKeyFile {creds1.pkey_file}',
  230. f' DocumentRoot "{self._docs_dir}"',
  231. ])
  232. conf.extend(self._curltest_conf())
  233. if domain1 in self._extra_configs:
  234. conf.extend(self._extra_configs[domain1])
  235. conf.extend([
  236. f'</VirtualHost>',
  237. f'',
  238. ])
  239. conf.extend([ # https host for domain2, no h2
  240. f'<VirtualHost *:{self.env.https_port}>',
  241. f' ServerName {domain2}',
  242. f' Protocols http/1.1',
  243. f' SSLEngine on',
  244. f' SSLCertificateFile {creds2.cert_file}',
  245. f' SSLCertificateKeyFile {creds2.pkey_file}',
  246. f' DocumentRoot "{self._docs_dir}/two"',
  247. ])
  248. conf.extend(self._curltest_conf())
  249. if domain2 in self._extra_configs:
  250. conf.extend(self._extra_configs[domain2])
  251. conf.extend([
  252. f'</VirtualHost>',
  253. f'',
  254. ])
  255. conf.extend([ # http forward proxy
  256. f'<VirtualHost *:{self.env.proxy_port}>',
  257. f' ServerName {proxy_domain}',
  258. f' Protocols h2c, http/1.1',
  259. f' ProxyRequests On',
  260. f' ProxyVia On',
  261. f' AllowCONNECT {self.env.http_port} {self.env.https_port}',
  262. f' <Proxy "*">',
  263. f' Require ip 127.0.0.1',
  264. f' </Proxy>',
  265. f'</VirtualHost>',
  266. ])
  267. conf.extend([ # https forward proxy
  268. f'<VirtualHost *:{self.env.proxys_port}>',
  269. f' ServerName {proxy_domain}',
  270. f' Protocols h2, http/1.1',
  271. f' SSLEngine on',
  272. f' SSLCertificateFile {proxy_creds.cert_file}',
  273. f' SSLCertificateKeyFile {proxy_creds.pkey_file}',
  274. f' ProxyRequests On',
  275. f' ProxyVia On',
  276. f' AllowCONNECT {self.env.http_port} {self.env.https_port}',
  277. f' <Proxy "*">',
  278. f' Require ip 127.0.0.1',
  279. f' </Proxy>',
  280. f'</VirtualHost>',
  281. ])
  282. fd.write("\n".join(conf))
  283. with open(os.path.join(self._conf_dir, 'mime.types'), 'w') as fd:
  284. fd.write("\n".join([
  285. 'text/html html',
  286. 'application/json json',
  287. ''
  288. ]))
  289. def _get_log_level(self):
  290. #if self.env.verbose > 3:
  291. # return 'trace2'
  292. #if self.env.verbose > 2:
  293. # return 'trace1'
  294. #if self.env.verbose > 1:
  295. # return 'debug'
  296. return 'info'
  297. def _curltest_conf(self) -> List[str]:
  298. if Httpd.MOD_CURLTEST is not None:
  299. return [
  300. f' <Location /curltest/echo>',
  301. f' SetHandler curltest-echo',
  302. f' </Location>',
  303. f' <Location /curltest/put>',
  304. f' SetHandler curltest-put',
  305. f' </Location>',
  306. f' <Location /curltest/tweak>',
  307. f' SetHandler curltest-tweak',
  308. f' </Location>',
  309. ]
  310. return []
  311. def _init_curltest(self):
  312. if Httpd.MOD_CURLTEST is not None:
  313. return
  314. local_dir = os.path.dirname(inspect.getfile(Httpd))
  315. p = subprocess.run([self.env.apxs, '-c', 'mod_curltest.c'],
  316. capture_output=True,
  317. cwd=os.path.join(local_dir, 'mod_curltest'))
  318. rv = p.returncode
  319. if rv != 0:
  320. log.error(f"compiling mod_curltest failed: {p.stderr}")
  321. raise Exception(f"compiling mod_curltest failed: {p.stderr}")
  322. Httpd.MOD_CURLTEST = os.path.join(
  323. local_dir, 'mod_curltest/.libs/mod_curltest.so')