vsftpd.py 6.3 KB

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