httpd.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #***************************************************************************
  4. # _ _ ____ _
  5. # Project ___| | | | _ \| |
  6. # / __| | | | |_) | |
  7. # | (__| |_| | _ <| |___
  8. # \___|\___/|_| \_\_____|
  9. #
  10. # Copyright (C) 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', 'authn_file',
  42. 'authz_user', 'authz_core', 'authz_host',
  43. 'auth_basic', 'auth_digest',
  44. 'alias', 'env', 'filter', 'headers', 'mime',
  45. 'socache_shmcb',
  46. 'rewrite', 'http2', 'ssl', 'proxy', 'proxy_http', 'proxy_connect',
  47. 'mpm_event',
  48. ]
  49. COMMON_MODULES_DIRS = [
  50. '/usr/lib/apache2/modules', # debian
  51. '/usr/libexec/apache2/', # macos
  52. ]
  53. MOD_CURLTEST = None
  54. def __init__(self, env: Env, proxy_auth: bool = False):
  55. self.env = env
  56. self._cmd = env.apachectl
  57. self._apache_dir = os.path.join(env.gen_dir, 'apache')
  58. self._run_dir = os.path.join(self._apache_dir, 'run')
  59. self._lock_dir = os.path.join(self._apache_dir, 'locks')
  60. self._docs_dir = os.path.join(self._apache_dir, 'docs')
  61. self._conf_dir = os.path.join(self._apache_dir, 'conf')
  62. self._conf_file = os.path.join(self._conf_dir, 'test.conf')
  63. self._logs_dir = os.path.join(self._apache_dir, 'logs')
  64. self._error_log = os.path.join(self._logs_dir, 'error_log')
  65. self._tmp_dir = os.path.join(self._apache_dir, 'tmp')
  66. self._basic_passwords = os.path.join(self._conf_dir, 'basic.passwords')
  67. self._digest_passwords = os.path.join(self._conf_dir, 'digest.passwords')
  68. self._mods_dir = None
  69. self._auth_digest = True
  70. self._proxy_auth_basic = proxy_auth
  71. self._extra_configs = {}
  72. assert env.apxs
  73. p = subprocess.run(args=[env.apxs, '-q', 'libexecdir'],
  74. capture_output=True, text=True)
  75. if p.returncode != 0:
  76. raise Exception(f'{env.apxs} failed to query libexecdir: {p}')
  77. self._mods_dir = p.stdout.strip()
  78. if self._mods_dir is None:
  79. raise Exception(f'apache modules dir cannot be found')
  80. if not os.path.exists(self._mods_dir):
  81. raise Exception(f'apache modules dir does not exist: {self._mods_dir}')
  82. self._process = None
  83. self._rmf(self._error_log)
  84. self._init_curltest()
  85. @property
  86. def docs_dir(self):
  87. return self._docs_dir
  88. def clear_logs(self):
  89. self._rmf(self._error_log)
  90. def exists(self):
  91. return os.path.exists(self._cmd)
  92. def set_extra_config(self, domain: str, lines: Optional[Union[str, List[str]]]):
  93. if lines is None:
  94. self._extra_configs.pop(domain, None)
  95. else:
  96. self._extra_configs[domain] = lines
  97. def clear_extra_configs(self):
  98. self._extra_configs = {}
  99. def set_proxy_auth(self, active: bool):
  100. self._proxy_auth_basic = active
  101. def _run(self, args, intext=''):
  102. env = {}
  103. for key, val in os.environ.items():
  104. env[key] = val
  105. env['APACHE_RUN_DIR'] = self._run_dir
  106. env['APACHE_RUN_USER'] = os.environ['USER']
  107. env['APACHE_LOCK_DIR'] = self._lock_dir
  108. env['APACHE_CONFDIR'] = self._apache_dir
  109. p = subprocess.run(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
  110. cwd=self.env.gen_dir,
  111. input=intext.encode() if intext else None,
  112. env=env)
  113. start = datetime.now()
  114. return ExecResult(args=args, exit_code=p.returncode,
  115. stdout=p.stdout.decode().splitlines(),
  116. stderr=p.stderr.decode().splitlines(),
  117. duration=datetime.now() - start)
  118. def _apachectl(self, cmd: str):
  119. args = [self.env.apachectl,
  120. "-d", self._apache_dir,
  121. "-f", self._conf_file,
  122. "-k", cmd]
  123. return self._run(args=args)
  124. def start(self):
  125. if self._process:
  126. self.stop()
  127. self._write_config()
  128. with open(self._error_log, 'a') as fd:
  129. fd.write('start of server\n')
  130. with open(os.path.join(self._apache_dir, 'xxx'), 'a') as fd:
  131. fd.write('start of server\n')
  132. r = self._apachectl('start')
  133. if r.exit_code != 0:
  134. log.error(f'failed to start httpd: {r}')
  135. return False
  136. return self.wait_live(timeout=timedelta(seconds=5))
  137. def stop(self):
  138. r = self._apachectl('stop')
  139. if r.exit_code == 0:
  140. return self.wait_dead(timeout=timedelta(seconds=5))
  141. log.fatal(f'stopping httpd failed: {r}')
  142. return r.exit_code == 0
  143. def restart(self):
  144. self.stop()
  145. return self.start()
  146. def reload(self):
  147. self._write_config()
  148. r = self._apachectl("graceful")
  149. if r.exit_code != 0:
  150. log.error(f'failed to reload httpd: {r}')
  151. return self.wait_live(timeout=timedelta(seconds=5))
  152. def wait_dead(self, timeout: timedelta):
  153. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  154. try_until = datetime.now() + timeout
  155. while datetime.now() < try_until:
  156. r = curl.http_get(url=f'http://{self.env.domain1}:{self.env.http_port}/')
  157. if r.exit_code != 0:
  158. return True
  159. time.sleep(.1)
  160. log.debug(f"Server still responding after {timeout}")
  161. return False
  162. def wait_live(self, timeout: timedelta):
  163. curl = CurlClient(env=self.env, run_dir=self._tmp_dir,
  164. timeout=timeout.total_seconds())
  165. try_until = datetime.now() + timeout
  166. while datetime.now() < try_until:
  167. r = curl.http_get(url=f'http://{self.env.domain1}:{self.env.http_port}/')
  168. if r.exit_code == 0:
  169. return True
  170. time.sleep(.1)
  171. log.debug(f"Server still not responding after {timeout}")
  172. return False
  173. def _rmf(self, path):
  174. if os.path.exists(path):
  175. return os.remove(path)
  176. def _mkpath(self, path):
  177. if not os.path.exists(path):
  178. return os.makedirs(path)
  179. def _write_config(self):
  180. domain1 = self.env.domain1
  181. creds1 = self.env.get_credentials(domain1)
  182. domain2 = self.env.domain2
  183. creds2 = self.env.get_credentials(domain2)
  184. proxy_domain = self.env.proxy_domain
  185. proxy_creds = self.env.get_credentials(proxy_domain)
  186. self._mkpath(self._conf_dir)
  187. self._mkpath(self._logs_dir)
  188. self._mkpath(self._tmp_dir)
  189. self._mkpath(os.path.join(self._docs_dir, 'two'))
  190. with open(os.path.join(self._docs_dir, 'data.json'), 'w') as fd:
  191. data = {
  192. 'server': f'{domain1}',
  193. }
  194. fd.write(JSONEncoder().encode(data))
  195. with open(os.path.join(self._docs_dir, 'two/data.json'), 'w') as fd:
  196. data = {
  197. 'server': f'{domain2}',
  198. }
  199. fd.write(JSONEncoder().encode(data))
  200. if self._proxy_auth_basic:
  201. with open(self._basic_passwords, 'w') as fd:
  202. fd.write('proxy:$apr1$FQfeInbs$WQZbODJlVg60j0ogEIlTW/\n')
  203. if self._auth_digest:
  204. with open(self._digest_passwords, 'w') as fd:
  205. fd.write('test:restricted area:57123e269fd73d71ae0656594e938e2f\n')
  206. self._mkpath(os.path.join(self.docs_dir, 'restricted/digest'))
  207. with open(os.path.join(self.docs_dir, 'restricted/digest/data.json'), 'w') as fd:
  208. fd.write('{"area":"digest"}\n')
  209. with open(self._conf_file, 'w') as fd:
  210. for m in self.MODULES:
  211. if os.path.exists(os.path.join(self._mods_dir, f'mod_{m}.so')):
  212. fd.write(f'LoadModule {m}_module "{self._mods_dir}/mod_{m}.so"\n')
  213. if Httpd.MOD_CURLTEST is not None:
  214. fd.write(f'LoadModule curltest_module \"{Httpd.MOD_CURLTEST}\"\n')
  215. conf = [ # base server config
  216. f'ServerRoot "{self._apache_dir}"',
  217. f'DefaultRuntimeDir logs',
  218. f'PidFile httpd.pid',
  219. f'ErrorLog {self._error_log}',
  220. f'LogLevel {self._get_log_level()}',
  221. f'StartServers 4',
  222. f'H2MinWorkers 16',
  223. f'H2MaxWorkers 256',
  224. f'H2Direct on',
  225. f'Listen {self.env.http_port}',
  226. f'Listen {self.env.https_port}',
  227. f'Listen {self.env.proxy_port}',
  228. f'Listen {self.env.proxys_port}',
  229. f'TypesConfig "{self._conf_dir}/mime.types',
  230. f'SSLSessionCache "shmcb:ssl_gcache_data(32000)"',
  231. ]
  232. if 'base' in self._extra_configs:
  233. conf.extend(self._extra_configs['base'])
  234. conf.extend([ # plain http host for domain1
  235. f'<VirtualHost *:{self.env.http_port}>',
  236. f' ServerName {domain1}',
  237. f' ServerAlias localhost',
  238. f' DocumentRoot "{self._docs_dir}"',
  239. f' Protocols h2c http/1.1',
  240. ])
  241. conf.extend(self._curltest_conf(domain1))
  242. conf.extend([
  243. f'</VirtualHost>',
  244. f'',
  245. ])
  246. conf.extend([ # https host for domain1, h1 + h2
  247. f'<VirtualHost *:{self.env.https_port}>',
  248. f' ServerName {domain1}',
  249. f' ServerAlias localhost',
  250. f' Protocols h2 http/1.1',
  251. f' SSLEngine on',
  252. f' SSLCertificateFile {creds1.cert_file}',
  253. f' SSLCertificateKeyFile {creds1.pkey_file}',
  254. f' DocumentRoot "{self._docs_dir}"',
  255. ])
  256. conf.extend(self._curltest_conf(domain1))
  257. if domain1 in self._extra_configs:
  258. conf.extend(self._extra_configs[domain1])
  259. conf.extend([
  260. f'</VirtualHost>',
  261. f'',
  262. ])
  263. conf.extend([ # https host for domain2, no h2
  264. f'<VirtualHost *:{self.env.https_port}>',
  265. f' ServerName {domain2}',
  266. f' Protocols http/1.1',
  267. f' SSLEngine on',
  268. f' SSLCertificateFile {creds2.cert_file}',
  269. f' SSLCertificateKeyFile {creds2.pkey_file}',
  270. f' DocumentRoot "{self._docs_dir}/two"',
  271. ])
  272. conf.extend(self._curltest_conf(domain2))
  273. if domain2 in self._extra_configs:
  274. conf.extend(self._extra_configs[domain2])
  275. conf.extend([
  276. f'</VirtualHost>',
  277. f'',
  278. ])
  279. conf.extend([ # http forward proxy
  280. f'<VirtualHost *:{self.env.proxy_port}>',
  281. f' ServerName {proxy_domain}',
  282. f' Protocols h2c http/1.1',
  283. f' ProxyRequests On',
  284. f' H2ProxyRequests On',
  285. f' ProxyVia On',
  286. f' AllowCONNECT {self.env.http_port} {self.env.https_port}',
  287. ])
  288. conf.extend(self._get_proxy_conf())
  289. conf.extend([
  290. f'</VirtualHost>',
  291. f'',
  292. ])
  293. conf.extend([ # https forward proxy
  294. f'<VirtualHost *:{self.env.proxys_port}>',
  295. f' ServerName {proxy_domain}',
  296. f' Protocols h2 http/1.1',
  297. f' SSLEngine on',
  298. f' SSLCertificateFile {proxy_creds.cert_file}',
  299. f' SSLCertificateKeyFile {proxy_creds.pkey_file}',
  300. f' ProxyRequests On',
  301. f' H2ProxyRequests On',
  302. f' ProxyVia On',
  303. f' AllowCONNECT {self.env.http_port} {self.env.https_port}',
  304. ])
  305. conf.extend(self._get_proxy_conf())
  306. conf.extend([
  307. f'</VirtualHost>',
  308. f'',
  309. ])
  310. fd.write("\n".join(conf))
  311. with open(os.path.join(self._conf_dir, 'mime.types'), 'w') as fd:
  312. fd.write("\n".join([
  313. 'text/html html',
  314. 'application/json json',
  315. ''
  316. ]))
  317. def _get_proxy_conf(self):
  318. if self._proxy_auth_basic:
  319. return [
  320. f' <Proxy "*">',
  321. f' AuthType Basic',
  322. f' AuthName "Restricted Proxy"',
  323. f' AuthBasicProvider file',
  324. f' AuthUserFile "{self._basic_passwords}"',
  325. f' Require user proxy',
  326. f' </Proxy>',
  327. ]
  328. else:
  329. return [
  330. f' <Proxy "*">',
  331. f' Require ip 127.0.0.1',
  332. f' </Proxy>',
  333. ]
  334. def _get_log_level(self):
  335. if self.env.verbose > 3:
  336. return 'trace2'
  337. if self.env.verbose > 2:
  338. return 'trace1'
  339. if self.env.verbose > 1:
  340. return 'debug'
  341. return 'info'
  342. def _curltest_conf(self, servername) -> List[str]:
  343. lines = []
  344. if Httpd.MOD_CURLTEST is not None:
  345. lines.extend([
  346. f' Redirect 301 /curltest/echo301 /curltest/echo',
  347. f' Redirect 302 /curltest/echo302 /curltest/echo',
  348. f' Redirect 303 /curltest/echo303 /curltest/echo',
  349. f' Redirect 307 /curltest/echo307 /curltest/echo',
  350. f' <Location /curltest/echo>',
  351. f' SetHandler curltest-echo',
  352. f' </Location>',
  353. f' <Location /curltest/put>',
  354. f' SetHandler curltest-put',
  355. f' </Location>',
  356. f' <Location /curltest/tweak>',
  357. f' SetHandler curltest-tweak',
  358. f' </Location>',
  359. f' <Location /curltest/1_1>',
  360. f' SetHandler curltest-1_1-required',
  361. f' </Location>',
  362. ])
  363. if self._auth_digest:
  364. lines.extend([
  365. f' <Directory {self.docs_dir}/restricted/digest>',
  366. f' AuthType Digest',
  367. f' AuthName "restricted area"',
  368. f' AuthDigestDomain "https://{servername}"',
  369. f' AuthBasicProvider file',
  370. f' AuthUserFile "{self._digest_passwords}"',
  371. f' Require valid-user',
  372. f' </Directory>',
  373. ])
  374. return lines
  375. def _init_curltest(self):
  376. if Httpd.MOD_CURLTEST is not None:
  377. return
  378. local_dir = os.path.dirname(inspect.getfile(Httpd))
  379. p = subprocess.run([self.env.apxs, '-c', 'mod_curltest.c'],
  380. capture_output=True,
  381. cwd=os.path.join(local_dir, 'mod_curltest'))
  382. rv = p.returncode
  383. if rv != 0:
  384. log.error(f"compiling mod_curltest failed: {p.stderr}")
  385. raise Exception(f"compiling mod_curltest failed: {p.stderr}")
  386. Httpd.MOD_CURLTEST = os.path.join(
  387. local_dir, 'mod_curltest/.libs/mod_curltest.so')