vsftpd.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 VsFTPD:
  39. def __init__(self, env: Env, with_ssl=False):
  40. self.env = env
  41. self._cmd = env.vsftpd
  42. self._scheme = 'ftp'
  43. self._with_ssl = with_ssl
  44. if self._with_ssl:
  45. self._port = self.env.ftps_port
  46. name = 'vsftpds'
  47. else:
  48. self._port = self.env.ftp_port
  49. name = 'vsftpd'
  50. self._vsftpd_dir = os.path.join(env.gen_dir, name)
  51. self._run_dir = os.path.join(self._vsftpd_dir, 'run')
  52. self._docs_dir = os.path.join(self._vsftpd_dir, 'docs')
  53. self._tmp_dir = os.path.join(self._vsftpd_dir, 'tmp')
  54. self._conf_file = os.path.join(self._vsftpd_dir, 'test.conf')
  55. self._pid_file = os.path.join(self._vsftpd_dir, 'vsftpd.pid')
  56. self._error_log = os.path.join(self._vsftpd_dir, 'vsftpd.log')
  57. self._process = None
  58. self.clear_logs()
  59. @property
  60. def domain(self):
  61. return self.env.ftp_domain
  62. @property
  63. def docs_dir(self):
  64. return self._docs_dir
  65. @property
  66. def port(self) -> str:
  67. return self._port
  68. def clear_logs(self):
  69. self._rmf(self._error_log)
  70. def exists(self):
  71. return os.path.exists(self._cmd)
  72. def is_running(self):
  73. if self._process:
  74. self._process.poll()
  75. return self._process.returncode is None
  76. return False
  77. def start_if_needed(self):
  78. if not self.is_running():
  79. return self.start()
  80. return True
  81. def start(self, wait_live=True):
  82. pass
  83. def stop_if_running(self):
  84. if self.is_running():
  85. return self.stop()
  86. return True
  87. def stop(self, wait_dead=True):
  88. self._mkpath(self._tmp_dir)
  89. if self._process:
  90. self._process.terminate()
  91. self._process.wait(timeout=2)
  92. self._process = None
  93. return not wait_dead or self.wait_dead(timeout=timedelta(seconds=5))
  94. return True
  95. def restart(self):
  96. self.stop()
  97. return self.start()
  98. def start(self, wait_live=True):
  99. self._mkpath(self._tmp_dir)
  100. if self._process:
  101. self.stop()
  102. self._write_config()
  103. args = [
  104. self._cmd,
  105. f'{self._conf_file}',
  106. ]
  107. procerr = open(self._error_log, 'a')
  108. self._process = subprocess.Popen(args=args, stderr=procerr)
  109. if self._process.returncode is not None:
  110. return False
  111. return not wait_live or self.wait_live(timeout=timedelta(seconds=5))
  112. def wait_dead(self, timeout: timedelta):
  113. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  114. try_until = datetime.now() + timeout
  115. while datetime.now() < try_until:
  116. check_url = f'{self._scheme}://{self.domain}:{self.port}/'
  117. r = curl.ftp_get(urls=[check_url], extra_args=['-v'])
  118. if r.exit_code != 0:
  119. return True
  120. log.debug(f'waiting for vsftpd to stop responding: {r}')
  121. time.sleep(.1)
  122. log.debug(f"Server still responding after {timeout}")
  123. return False
  124. def wait_live(self, timeout: timedelta):
  125. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  126. try_until = datetime.now() + timeout
  127. while datetime.now() < try_until:
  128. check_url = f'{self._scheme}://{self.domain}:{self.port}/'
  129. r = curl.ftp_get(urls=[check_url], extra_args=[
  130. '--trace', 'curl-start.trace', '--trace-time'
  131. ])
  132. if r.exit_code == 0:
  133. return True
  134. log.debug(f'waiting for vsftpd to become responsive: {r}')
  135. time.sleep(.1)
  136. log.error(f"Server still not responding after {timeout}")
  137. return False
  138. def _run(self, args, intext=''):
  139. env = {}
  140. for key, val in os.environ.items():
  141. env[key] = val
  142. with open(self._error_log, 'w') as cerr:
  143. self._process = subprocess.run(args, stderr=cerr, stdout=cerr,
  144. cwd=self._vsftpd_dir,
  145. input=intext.encode() if intext else None,
  146. env=env)
  147. start = datetime.now()
  148. return ExecResult(args=args, exit_code=self._process.returncode,
  149. duration=datetime.now() - start)
  150. def _rmf(self, path):
  151. if os.path.exists(path):
  152. return os.remove(path)
  153. def _mkpath(self, path):
  154. if not os.path.exists(path):
  155. return os.makedirs(path)
  156. def _write_config(self):
  157. self._mkpath(self._docs_dir)
  158. self._mkpath(self._tmp_dir)
  159. conf = [ # base server config
  160. f'listen=YES',
  161. f'run_as_launching_user=YES',
  162. f'#listen_address=127.0.0.1',
  163. f'listen_port={self.port}',
  164. f'local_enable=NO',
  165. f'anonymous_enable=YES',
  166. f'anon_root={self._docs_dir}',
  167. f'dirmessage_enable=YES',
  168. f'write_enable=YES',
  169. f'anon_upload_enable=YES',
  170. f'log_ftp_protocol=YES',
  171. f'xferlog_enable=YES',
  172. f'xferlog_std_format=NO',
  173. f'vsftpd_log_file={self._error_log}',
  174. f'\n',
  175. ]
  176. if self._with_ssl:
  177. creds = self.env.get_credentials(self.domain)
  178. conf.extend([
  179. f'ssl_enable=YES',
  180. f'debug_ssl=YES',
  181. f'allow_anon_ssl=YES',
  182. f'rsa_cert_file={creds.cert_file}',
  183. f'rsa_private_key_file={creds.pkey_file}',
  184. # require_ssl_reuse=YES means ctrl and data connection need to use the same session
  185. f'require_ssl_reuse=NO',
  186. ])
  187. with open(self._conf_file, 'w') as fd:
  188. fd.write("\n".join(conf))