Debian Codegraph @

cvdupdate/__main__.py

raw
1 #!/usr/bin/env python3
2
3 """
4 CVD-Update: ClamAV Database Updater
5 """
6
7 _description = """
8 A tool to download and update clamav databases and database patch files
9 for the purposes of hosting your own database mirror.
10 """
11
12 _copyright = """
13 Copyright (C) 2021-2025 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
14 """
15
16 """
17 Author: Micah Snyder
18
19 Licensed under the Apache License, Version 2.0 (the "License");
20 you may not use this file except in compliance with the License.
21 You may obtain a copy of the License at
22
23 http://www.apache.org/licenses/LICENSE-2.0
24
25 Unless required by applicable law or agreed to in writing, software
26 distributed under the License is distributed on an "AS IS" BASIS,
27 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28 See the License for the specific language governing permissions and
29 limitations under the License.
30 """
31
32 import logging
33 import os
34 import sys
35 from pathlib import Path
36
37 import click
38 import colorlog
39 try:
40 from importlib.metadata import PackageNotFoundError, version as _get_version
41 except ImportError: # pragma: no cover - backport for older Pythons
42 from importlib_metadata import PackageNotFoundError, version as _get_version
43 from http.server import HTTPServer
44 from RangeHTTPServer import RangeRequestHandler
45
46 from cvdupdate import auto_updater
47 from cvdupdate.cvdupdate import CVDUpdate
48
49 handler = colorlog.StreamHandler()
50 handler.setFormatter(
51 colorlog.ColoredFormatter(
52 "%(log_color)s%(asctime)s %(name)s %(levelname)s %(message)s"
53 )
54 )
55 logging.basicConfig(level=logging.DEBUG, handlers=[handler])
56 module_logger = logging.getLogger("cvdupdate")
57 module_logger.setLevel(logging.DEBUG)
58
59 from colorama import Fore, Back, Style
60
61
62 def _package_version() -> str:
63 try:
64 return _get_version('cvdupdate')
65 except PackageNotFoundError:
66 return '0.0'
67
68 #
69 # CLI Interface
70 #
71 @click.group(
72 epilog=Fore.BLUE
73 + __doc__ + "\n"
74 + Fore.GREEN
75 + _description + "\n"
76 + f"\nVersion {_package_version()}\n"
77 + Style.RESET_ALL
78 + _copyright,
79 )
80 def cli():
81 pass
82
83
84 @cli.command("list")
85 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
86 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
87 def db_list(config: str, verbose: bool):
88 """
89 List the DBs found in the database directory.
90 """
91 m = CVDUpdate(config=config, verbose=verbose)
92 m.db_list()
93
94 @cli.command("show")
95 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
96 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
97 @click.argument("db", required=True)
98 def db_show(config: str, verbose: bool, db: str):
99 """
100 Show details about a specific database.
101 """
102 m = CVDUpdate(config=config, verbose=verbose)
103 if not m.db_show(db):
104 sys.exit(1)
105
106 @cli.command("update")
107 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
108 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
109 @click.option("--debug-mode", "-D", is_flag=True, default=False, help="Print out HTTP headers for debugging purposes. [optional]")
110 @click.argument("db", required=False, default="")
111 def db_update(config: str, verbose: bool, db: str, debug_mode: bool):
112 """
113 Update the DBs from the internet. Will update all DBs if DB not specified.
114 """
115 m = CVDUpdate(config=config, verbose=verbose)
116 errors = m.db_update(db, debug_mode)
117 if errors > 0:
118 sys.exit(errors)
119
120 @cli.command("add")
121 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
122 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
123 @click.argument("db", required=True)
124 @click.argument("url", required=True)
125 def db_add(config: str, verbose: bool, db: str, url: str):
126 """
127 Add a db to the list of known DBs.
128 """
129 m = CVDUpdate(config=config, verbose=verbose)
130 if not m.config_add_db(db, url=url):
131 sys.exit(1)
132
133 @cli.command("remove")
134 @click.option("--config", "-c", type=str, required=False, default="")
135 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
136 @click.argument("db", required=True)
137 def db_remove(config: str, verbose: bool, db: str):
138 """
139 Remove a db from the list of known DBs and delete local copies of the DB.
140 """
141 m = CVDUpdate(config=config, verbose=verbose)
142 if not m.config_remove_db(db):
143 sys.exit(1)
144
145
146 @cli.group(help="Commands to configure.")
147 def config():
148 pass
149
150 @config.command("set")
151 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
152 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
153 @click.option("--logdir", "-l", type=click.Path(), required=False, default="", help="Set a custom log directory. [optional]")
154 @click.option("--dbdir", "-d", type=click.Path(), required=False, default="", help="Set a custom database directory. [optional]")
155 @click.option("--nameserver", "-n", type=click.STRING, required=False, default="", help="Set a custom DNS nameserver. [optional]")
156 def config_set(config: str, verbose: bool, logdir: str, dbdir: str, nameserver: str):
157 """
158 Set up first time configuration.
159
160 The default directories will be in ~/.cvdupdate
161 """
162 CVDUpdate(
163 config=config,
164 verbose=verbose,
165 log_dir=logdir,
166 db_dir=dbdir,
167 nameserver=nameserver)
168
169 @config.command("show")
170 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
171 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
172 def config_show(config: str, verbose: bool):
173 """
174 Print out the current configuration.
175 """
176 m = CVDUpdate(config=config, verbose=verbose)
177 m.config_show()
178
179
180 @cli.group(help="Commands to clean up.")
181 def clean():
182 pass
183
184 @clean.command("dbs")
185 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
186 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
187 def clean_dbs(config: str, verbose: bool):
188 """
189 Delete all files in the database directory.
190 """
191 m = CVDUpdate(config=config, verbose=verbose)
192 m.clean_dbs()
193
194 @clean.command("logs")
195 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
196 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
197 def clean_logs(config: str, verbose: bool):
198 """
199 Delete all files in the logs directory
200 """
201 m = CVDUpdate(config=config, verbose=verbose)
202 m.clean_logs()
203
204 @clean.command("all")
205 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
206 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
207 def clean_all(config: str, verbose: bool):
208 """
209 Delete the logs, databases, and config file.
210 """
211 m = CVDUpdate(config=config, verbose=verbose)
212 m.clean_all()
213
214
215 @cli.command("serve")
216 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
217 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
218 @click.option("--update-interval-seconds", "-U", type=click.INT, required=False, default=0, help="Time in seconds before the next database update")
219 @click.argument("port", type=int, required=False, default=8000)
220 def serve(port: int, config: str, verbose: bool, update_interval_seconds: int):
221 """
222 Serve up the database directory. Not a production quality server.
223 Intended for testing purposes.
224 """
225 m = CVDUpdate(config=config, verbose=verbose)
226 os.chdir(str(m.db_dir))
227 m.logger.info(f"Serving up {m.db_dir} on localhost:{port}...")
228 auto_updater.start(update_interval_seconds)
229
230 RangeRequestHandler.protocol_version = 'HTTP/1.0'
231 # TODO(danvk): pick a random, available port
232 httpd = HTTPServer(('', port), RangeRequestHandler)
233 httpd.serve_forever()
234
235
236 #
237 # Command Aliases
238 #
239 @cli.command("list")
240 @click.pass_context
241 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
242 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
243 def list_alias(ctx, config: str, verbose: bool):
244 """
245 List the DBs found in the database directory.
246
247 This is just an alias for `db list`.
248 """
249 ctx.forward(db_list)
250
251 @cli.command("show")
252 @click.pass_context
253 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
254 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
255 @click.argument("db", required=True)
256 def show_alias(ctx, config: str, verbose: bool, db: str):
257 """
258 Show details about a specific database.
259
260 This is just an alias for `db show`.
261 """
262 ctx.forward(db_show)
263
264 @cli.command("update")
265 @click.pass_context
266 @click.option("--config", "-c", type=click.Path(), required=False, default="", help="Config path. [optional]")
267 @click.option("--verbose", "-V", is_flag=True, default=False, help="Verbose output. [optional]")
268 @click.option("--debug-mode", "-D", is_flag=True, default=False, help="Print out HTTP headers for debugging purposes. [optional]")
269 @click.argument("db", required=False, default="")
270 def update_alias(ctx, config: str, verbose: bool, db: str, debug_mode: bool):
271 """
272 Update local copy of DBs.
273
274 This is just an alias for `db show`.
275 """
276 ctx.forward(db_update)
277
278
279 if __name__ == "__main__":
280 sys.argv[0] = "cvdupdate"
281 cli(sys.argv[1:])