httpd.py 18 KB

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