httpd.py 18 KB

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