admin.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. import os
  2. import shutil
  3. from datetime import datetime
  4. from dotenv import load_dotenv
  5. from loguru import logger
  6. load_dotenv()
  7. # SQUID_CONFIG_PATH = os.getenv("SQUID_CONFIG_PATH", "/etc/squid/squid.conf")
  8. # ACL_FILES_DIR = os.getenv("ACL_FILES_DIR", "/etc/squid/acls")
  9. SQUID_CONFIG_PATH = "/etc/squid/squid.conf"
  10. ACL_FILES_DIR = "/etc/squid/squid.d/"
  11. def validate_paths():
  12. errors = []
  13. cfg = os.path.abspath(os.path.expanduser(SQUID_CONFIG_PATH))
  14. if os.path.isdir(cfg):
  15. squid_conf = os.path.join(cfg, "squid.conf")
  16. if not os.path.exists(squid_conf):
  17. errors.append(f"'squid.conf' not found in directory: {cfg}")
  18. else:
  19. if not os.path.isfile(squid_conf):
  20. errors.append(f"Found but not a regular file: {squid_conf}")
  21. else:
  22. if not os.access(squid_conf, os.R_OK):
  23. errors.append(f"No read permissions for: {squid_conf}")
  24. if not os.access(squid_conf, os.W_OK):
  25. errors.append(f"No write permissions for: {squid_conf}")
  26. else:
  27. squid_conf = cfg
  28. if not os.path.exists(squid_conf):
  29. errors.append(f"Configuration file not found: {squid_conf}")
  30. else:
  31. if not os.path.isfile(squid_conf):
  32. errors.append(f"Not a regular file: {squid_conf}")
  33. if os.path.basename(squid_conf) != "squid.conf":
  34. errors.append(
  35. f"Expected file named 'squid.conf', got: {os.path.basename(squid_conf)}"
  36. )
  37. if os.path.isfile(squid_conf):
  38. if not os.access(squid_conf, os.R_OK):
  39. errors.append(f"No read permissions for: {squid_conf}")
  40. if not os.access(squid_conf, os.W_OK):
  41. errors.append(f"No write permissions for: {squid_conf}")
  42. acl_dir = os.path.abspath(os.path.expanduser(ACL_FILES_DIR))
  43. if not os.path.exists(acl_dir):
  44. errors.append(f"ACL directory not found: {acl_dir}")
  45. elif not os.path.isdir(acl_dir):
  46. errors.append(f"ACL path is not a directory: {acl_dir}")
  47. elif not os.access(acl_dir, os.W_OK):
  48. errors.append(f"No write permissions in ACL directory: {acl_dir}")
  49. return errors
  50. class SquidConfigManager:
  51. def __init__(self, config_path=SQUID_CONFIG_PATH, config_dir=ACL_FILES_DIR):
  52. self.config_path = config_path
  53. self.config_dir = config_dir
  54. self.config_content = ""
  55. self.is_valid = False
  56. self.errors = []
  57. self.is_modular = False # Flag to check if using modular configs
  58. self._validate_environment()
  59. if self.is_valid:
  60. self.load_config()
  61. self._check_modular_config()
  62. def _validate_environment(self):
  63. self.errors = validate_paths()
  64. if self.errors:
  65. for error in self.errors:
  66. logger.error(error)
  67. self.is_valid = False
  68. logger.error(
  69. "SquidConfigManager cannot be initialized due to configuration errors"
  70. )
  71. else:
  72. self.is_valid = True
  73. logger.info("SquidConfigManager initialized successfully")
  74. def load_config(self):
  75. if not self.is_valid:
  76. logger.error("Cannot load configuration: invalid environment")
  77. return False
  78. try:
  79. with open(self.config_path, encoding="utf-8") as f:
  80. self.config_content = f.read()
  81. logger.debug(f"Configuration loaded from: {self.config_path}")
  82. return True
  83. except FileNotFoundError:
  84. logger.error(f"Configuration file not found: {self.config_path}")
  85. self.config_content = ""
  86. return False
  87. except PermissionError:
  88. logger.error(f"No read permissions for: {self.config_path}")
  89. self.config_content = ""
  90. return False
  91. except UnicodeDecodeError as e:
  92. logger.error(f"File encoding error: {e}")
  93. self.config_content = ""
  94. return False
  95. except Exception as e:
  96. logger.error(f"Unexpected error loading configuration: {e}")
  97. self.config_content = ""
  98. return False
  99. def save_config(self, content):
  100. if not self.is_valid:
  101. logger.error("Cannot save configuration: invalid environment")
  102. return False
  103. try:
  104. backup_created = self.create_backup()
  105. if not backup_created:
  106. logger.warning("Could not create backup, but continuing with save...")
  107. with open(self.config_path, "w", encoding="utf-8") as f:
  108. f.write(content)
  109. self.config_content = content
  110. logger.info(f"Configuration saved successfully to: {self.config_path}")
  111. return True
  112. except PermissionError:
  113. logger.error(f"No write permissions for: {self.config_path}")
  114. return False
  115. except OSError as e:
  116. logger.error(f"System error saving configuration: {e}")
  117. return False
  118. except Exception as e:
  119. logger.error(f"Unexpected error saving configuration: {e}")
  120. return False
  121. def create_backup(self):
  122. if not self.is_valid:
  123. logger.error("Cannot create backup: invalid environment")
  124. return False
  125. def get_acls(self):
  126. """
  127. Parse ACL definitions with enhanced information.
  128. Returns a list of ACL dictionaries with full details.
  129. Format:
  130. {
  131. 'id': 0,
  132. 'name': 'localnet',
  133. 'type': 'src',
  134. 'options': ['-i'], # ACL options like -i, -n, -m
  135. 'values': ['10.0.0.0/8', '192.168.0.0/16'], # List of values
  136. 'value_string': '10.0.0.0/8 192.168.0.0/16', # Original value string
  137. 'is_predefined': False, # True for Squid predefined ACLs
  138. 'is_slow': False, # True for slow ACL types
  139. 'category': 'network', # Category: network, time, auth, content, ssl, etc.
  140. 'description': 'RFC 1918 private networks', # Human-readable description
  141. 'line_number': 5
  142. }
  143. """
  144. if not self.is_valid:
  145. logger.error("Cannot get ACLs: invalid environment")
  146. return []
  147. # If using modular config, read from the ACLs specific file
  148. if self.is_modular:
  149. acl_content = self.read_modular_config("100_acls.conf")
  150. if not acl_content:
  151. logger.warning(
  152. "Could not read modular ACL config, falling back to main config"
  153. )
  154. config_to_parse = self.config_content
  155. else:
  156. config_to_parse = acl_content
  157. else:
  158. if not self.config_content:
  159. logger.warning("No configuration content available")
  160. return []
  161. config_to_parse = self.config_content
  162. try:
  163. acls = []
  164. lines = config_to_parse.split("\n")
  165. acl_index = 0
  166. # Predefined ACLs in Squid
  167. predefined_acls = [
  168. "all",
  169. "manager",
  170. "localhost",
  171. "to_localhost",
  172. "to_linklocal",
  173. "CONNECT",
  174. ]
  175. # ACL type metadata
  176. acl_types_info = {
  177. # Network ACLs
  178. "src": {
  179. "category": "network",
  180. "slow": False,
  181. "desc": "Source IP address",
  182. },
  183. "dst": {
  184. "category": "network",
  185. "slow": True,
  186. "desc": "Destination IP address",
  187. },
  188. "localip": {
  189. "category": "network",
  190. "slow": False,
  191. "desc": "Local IP client connected to",
  192. },
  193. "arp": {
  194. "category": "network",
  195. "slow": False,
  196. "desc": "MAC address (EUI-48)",
  197. },
  198. "eui64": {
  199. "category": "network",
  200. "slow": False,
  201. "desc": "EUI-64 address",
  202. },
  203. "client_connection_mark": {
  204. "category": "network",
  205. "slow": False,
  206. "desc": "CONNMARK of connection",
  207. },
  208. # Domain ACLs
  209. "srcdomain": {
  210. "category": "domain",
  211. "slow": True,
  212. "desc": "Reverse DNS lookup of client IP",
  213. },
  214. "dstdomain": {
  215. "category": "domain",
  216. "slow": False,
  217. "desc": "Destination domain from URL",
  218. },
  219. "srcdom_regex": {
  220. "category": "domain",
  221. "slow": True,
  222. "desc": "Regex match on client name",
  223. },
  224. "dstdom_regex": {
  225. "category": "domain",
  226. "slow": False,
  227. "desc": "Regex match on server domain",
  228. },
  229. # AS Number ACLs
  230. "src_as": {
  231. "category": "network",
  232. "slow": False,
  233. "desc": "Source Autonomous System number",
  234. },
  235. "dst_as": {
  236. "category": "network",
  237. "slow": False,
  238. "desc": "Destination AS number",
  239. },
  240. # Time ACLs
  241. "time": {
  242. "category": "time",
  243. "slow": False,
  244. "desc": "Time of day and day of week",
  245. },
  246. # URL ACLs
  247. "url_regex": {
  248. "category": "url",
  249. "slow": False,
  250. "desc": "Regex match on full URL",
  251. },
  252. "urllogin": {
  253. "category": "url",
  254. "slow": False,
  255. "desc": "Regex match on URL login field",
  256. },
  257. "urlpath_regex": {
  258. "category": "url",
  259. "slow": False,
  260. "desc": "Regex match on URL path",
  261. },
  262. # Port ACLs
  263. "port": {
  264. "category": "port",
  265. "slow": False,
  266. "desc": "Destination TCP port",
  267. },
  268. "localport": {
  269. "category": "port",
  270. "slow": False,
  271. "desc": "TCP port client connected to",
  272. },
  273. "myportname": {
  274. "category": "port",
  275. "slow": False,
  276. "desc": "Port name from *_port directive",
  277. },
  278. # Protocol & Method ACLs
  279. "proto": {
  280. "category": "protocol",
  281. "slow": False,
  282. "desc": "Request protocol (HTTP, FTP, etc)",
  283. },
  284. "method": {
  285. "category": "protocol",
  286. "slow": False,
  287. "desc": "HTTP request method",
  288. },
  289. "http_status": {
  290. "category": "protocol",
  291. "slow": False,
  292. "desc": "HTTP status code in reply",
  293. },
  294. # Header ACLs
  295. "browser": {
  296. "category": "content",
  297. "slow": False,
  298. "desc": "User-Agent header pattern",
  299. },
  300. "referer_regex": {
  301. "category": "content",
  302. "slow": False,
  303. "desc": "Referer header pattern",
  304. },
  305. "req_header": {
  306. "category": "content",
  307. "slow": False,
  308. "desc": "Request header pattern",
  309. },
  310. "rep_header": {
  311. "category": "content",
  312. "slow": False,
  313. "desc": "Reply header pattern",
  314. },
  315. # Authentication ACLs
  316. "proxy_auth": {
  317. "category": "auth",
  318. "slow": True,
  319. "desc": "Proxy authentication username",
  320. },
  321. "proxy_auth_regex": {
  322. "category": "auth",
  323. "slow": True,
  324. "desc": "Proxy auth username regex",
  325. },
  326. "ext_user": {
  327. "category": "auth",
  328. "slow": True,
  329. "desc": "External ACL helper username",
  330. },
  331. "ext_user_regex": {
  332. "category": "auth",
  333. "slow": True,
  334. "desc": "External ACL helper username regex",
  335. },
  336. # MIME Type ACLs
  337. "req_mime_type": {
  338. "category": "content",
  339. "slow": False,
  340. "desc": "Request MIME type",
  341. },
  342. "rep_mime_type": {
  343. "category": "content",
  344. "slow": False,
  345. "desc": "Reply MIME type",
  346. },
  347. # Connection ACLs
  348. "maxconn": {
  349. "category": "connection",
  350. "slow": False,
  351. "desc": "Max TCP connections from IP",
  352. },
  353. "max_user_ip": {
  354. "category": "connection",
  355. "slow": False,
  356. "desc": "Max IPs per user",
  357. },
  358. # SSL/TLS ACLs
  359. "ssl_error": {
  360. "category": "ssl",
  361. "slow": False,
  362. "desc": "SSL certificate validation error",
  363. },
  364. "server_cert_fingerprint": {
  365. "category": "ssl",
  366. "slow": False,
  367. "desc": "Server cert fingerprint",
  368. },
  369. "ssl::server_name": {
  370. "category": "ssl",
  371. "slow": False,
  372. "desc": "TLS SNI server name",
  373. },
  374. "ssl::server_name_regex": {
  375. "category": "ssl",
  376. "slow": False,
  377. "desc": "TLS SNI regex match",
  378. },
  379. "connections_encrypted": {
  380. "category": "ssl",
  381. "slow": False,
  382. "desc": "All connections over TLS",
  383. },
  384. # Advanced ACLs
  385. "external": {
  386. "category": "advanced",
  387. "slow": True,
  388. "desc": "External ACL helper lookup",
  389. },
  390. "random": {
  391. "category": "advanced",
  392. "slow": False,
  393. "desc": "Random probability match",
  394. },
  395. "note": {
  396. "category": "advanced",
  397. "slow": False,
  398. "desc": "Transaction annotation",
  399. },
  400. "annotate_transaction": {
  401. "category": "advanced",
  402. "slow": False,
  403. "desc": "Add transaction annotation",
  404. },
  405. "annotate_client": {
  406. "category": "advanced",
  407. "slow": False,
  408. "desc": "Add client annotation",
  409. },
  410. "peername": {
  411. "category": "advanced",
  412. "slow": False,
  413. "desc": "Cache peer name",
  414. },
  415. "peername_regex": {
  416. "category": "advanced",
  417. "slow": False,
  418. "desc": "Cache peer name regex",
  419. },
  420. "hier_code": {
  421. "category": "advanced",
  422. "slow": False,
  423. "desc": "Squid hierarchy code",
  424. },
  425. # Group ACLs
  426. "any-of": {
  427. "category": "group",
  428. "slow": False,
  429. "desc": "Match any of the ACLs",
  430. },
  431. "all-of": {
  432. "category": "group",
  433. "slow": False,
  434. "desc": "Match all of the ACLs",
  435. },
  436. }
  437. last_comment = ""
  438. for line_num, line in enumerate(lines, 1):
  439. try:
  440. stripped = line.strip()
  441. # Track comments for context
  442. if stripped.startswith("#"):
  443. last_comment = stripped[1:].strip()
  444. continue
  445. if stripped.startswith("acl "):
  446. parts = stripped.split()
  447. if len(parts) >= 3:
  448. acl_name = parts[1]
  449. # Parse options and type
  450. options = []
  451. type_index = 2
  452. while type_index < len(parts) and parts[
  453. type_index
  454. ].startswith("-"):
  455. options.append(parts[type_index])
  456. type_index += 1
  457. if type_index >= len(parts):
  458. continue
  459. acl_type = parts[type_index]
  460. values = (
  461. parts[type_index + 1 :]
  462. if len(parts) > type_index + 1
  463. else []
  464. )
  465. value_string = " ".join(values)
  466. # Get type metadata
  467. type_info = acl_types_info.get(
  468. acl_type,
  469. {
  470. "category": "other",
  471. "slow": False,
  472. "desc": "Custom ACL type",
  473. },
  474. )
  475. # Check if predefined
  476. is_predefined = acl_name in predefined_acls
  477. acls.append(
  478. {
  479. "id": acl_index,
  480. "name": acl_name,
  481. "type": acl_type,
  482. "options": options,
  483. "value_list": values,
  484. "value_string": value_string,
  485. "is_predefined": is_predefined,
  486. "is_slow": type_info.get("slow", False),
  487. "category": type_info.get("category", "other"),
  488. "type_description": type_info.get("desc", ""),
  489. "comment": last_comment if last_comment else "",
  490. "line_number": line_num,
  491. "full_line": stripped,
  492. }
  493. )
  494. acl_index += 1
  495. last_comment = ""
  496. except Exception as e:
  497. logger.warning(f"Error processing ACL at line {line_num}: {e}")
  498. continue
  499. logger.debug(f"Found {len(acls)} ACLs")
  500. return acls
  501. except Exception as e:
  502. logger.error(f"Unexpected error extracting ACLs: {e}")
  503. return []
  504. def get_delay_pools(self):
  505. """
  506. Parse delay pools configuration and group by pool number.
  507. Returns a list of pool dictionaries with all related directives.
  508. Format:
  509. {
  510. 'pool_number': '1',
  511. 'class': '3',
  512. 'parameters': '8192/131072 1024/65536 256/32768',
  513. 'access_rules': [{'action': 'allow', 'acl': 'students'}]
  514. }
  515. """
  516. if not self.is_valid:
  517. logger.error("Cannot get delay pools: invalid environment")
  518. return []
  519. # If using modular config, read from the delay pools specific file
  520. if self.is_modular:
  521. delay_content = self.read_modular_config("110_delay_pools.conf")
  522. if not delay_content:
  523. logger.warning(
  524. "Could not read modular delay pools config, falling back to main config"
  525. )
  526. config_to_parse = self.config_content
  527. else:
  528. config_to_parse = delay_content
  529. else:
  530. if not self.config_content:
  531. logger.warning("No configuration content available")
  532. return []
  533. config_to_parse = self.config_content
  534. try:
  535. pools_dict = {} # Dictionary to group by pool number
  536. total_pools = 0
  537. lines = config_to_parse.split("\n")
  538. for line_num, line in enumerate(lines, 1):
  539. try:
  540. line = line.strip()
  541. if line.startswith("delay_pools "):
  542. parts = line.split()
  543. if len(parts) >= 2:
  544. total_pools = int(parts[1])
  545. elif line.startswith("delay_class "):
  546. parts = line.split()
  547. if len(parts) >= 3:
  548. pool_num = parts[1]
  549. if pool_num not in pools_dict:
  550. pools_dict[pool_num] = {
  551. "pool_number": pool_num,
  552. "class": parts[2],
  553. "parameters": None,
  554. "access_rules": [],
  555. }
  556. else:
  557. pools_dict[pool_num]["class"] = parts[2]
  558. elif line.startswith("delay_parameters "):
  559. parts = line.split()
  560. if len(parts) >= 3:
  561. pool_num = parts[1]
  562. if pool_num not in pools_dict:
  563. pools_dict[pool_num] = {
  564. "pool_number": pool_num,
  565. "class": None,
  566. "parameters": " ".join(parts[2:]),
  567. "access_rules": [],
  568. }
  569. else:
  570. pools_dict[pool_num]["parameters"] = " ".join(parts[2:])
  571. elif line.startswith("delay_access "):
  572. parts = line.split()
  573. if len(parts) >= 4:
  574. pool_num = parts[1]
  575. if pool_num not in pools_dict:
  576. pools_dict[pool_num] = {
  577. "pool_number": pool_num,
  578. "class": None,
  579. "parameters": None,
  580. "access_rules": [],
  581. }
  582. pools_dict[pool_num]["access_rules"].append(
  583. {"action": parts[2], "acl": " ".join(parts[3:])}
  584. )
  585. except Exception as e:
  586. logger.warning(
  587. f"Error processing delay pool at line {line_num}: {e}"
  588. )
  589. continue
  590. # Convert dictionary to sorted list
  591. delay_pools = [
  592. pools_dict[key] for key in sorted(pools_dict.keys(), key=int)
  593. ]
  594. logger.debug(
  595. f"Found {len(delay_pools)} delay pool configurations (total_pools={total_pools})"
  596. )
  597. return delay_pools
  598. except Exception as e:
  599. logger.error(f"Unexpected error extracting delay pools: {e}")
  600. return []
  601. def get_http_access_rules(self):
  602. """
  603. Parse http_access rules with enhanced information.
  604. Returns a list of rule dictionaries with action, acls (list), and metadata.
  605. Format:
  606. {
  607. 'action': 'allow',
  608. 'acls': ['!Safe_ports'], # List of ACLs including negations
  609. 'acl_string': '!Safe_ports', # Original ACL string
  610. 'is_negative': True, # If it contains negation
  611. 'line_number': 5, # Original line number
  612. 'description': '' # Optional description from comments
  613. }
  614. """
  615. if not self.is_valid:
  616. logger.error("Cannot get HTTP rules: invalid environment")
  617. return []
  618. # If using modular config, read from the http_access specific file
  619. if self.is_modular:
  620. http_content = self.read_modular_config("120_http_access.conf")
  621. if not http_content:
  622. logger.warning(
  623. "Could not read modular http_access config, falling back to main config"
  624. )
  625. config_to_parse = self.config_content
  626. else:
  627. config_to_parse = http_content
  628. else:
  629. if not self.config_content:
  630. logger.warning("No configuration content available")
  631. return []
  632. config_to_parse = self.config_content
  633. try:
  634. rules = []
  635. lines = config_to_parse.split("\n")
  636. last_comment = ""
  637. for line_num, line in enumerate(lines, 1):
  638. try:
  639. stripped = line.strip()
  640. # Track comments for context
  641. if stripped.startswith("#"):
  642. last_comment = stripped[1:].strip()
  643. continue
  644. if stripped.startswith("http_access "):
  645. parts = stripped.split()
  646. if len(parts) >= 3:
  647. action = parts[1]
  648. acl_string = " ".join(parts[2:])
  649. acls = parts[2:]
  650. # Check if any ACL has negation
  651. is_negative = any(acl.startswith("!") for acl in acls)
  652. # Identify special/common ACLs
  653. special_acls = []
  654. if "localhost" in acls:
  655. special_acls.append("localhost")
  656. if "manager" in acls:
  657. special_acls.append("manager")
  658. if any("Safe_ports" in acl for acl in acls):
  659. special_acls.append("Safe_ports")
  660. if any("SSL_ports" in acl for acl in acls):
  661. special_acls.append("SSL_ports")
  662. if "CONNECT" in acls:
  663. special_acls.append("CONNECT")
  664. rules.append(
  665. {
  666. "action": action,
  667. "acls": acls,
  668. "acl_string": acl_string,
  669. "is_negative": is_negative,
  670. "line_number": line_num,
  671. "description": last_comment if last_comment else "",
  672. "special_acls": special_acls,
  673. }
  674. )
  675. last_comment = "" # Reset comment
  676. except Exception as e:
  677. logger.warning(
  678. f"Error processing HTTP rule at line {line_num}: {e}"
  679. )
  680. continue
  681. logger.debug(f"Found {len(rules)} HTTP access rules")
  682. return rules
  683. except Exception as e:
  684. logger.error(f"Unexpected error extracting HTTP rules: {e}")
  685. return []
  686. def _check_modular_config(self):
  687. """Check if the main config file uses modular includes."""
  688. if not self.config_content:
  689. return
  690. # Check if config contains include directives pointing to squid.d
  691. self.is_modular = (
  692. "include" in self.config_content.lower()
  693. and "squid.d" in self.config_content
  694. )
  695. if self.is_modular:
  696. logger.info("Modular configuration detected")
  697. def list_modular_configs(self) -> list[dict[str, str]]:
  698. """List all modular configuration files in squid.d directory."""
  699. if not os.path.exists(self.config_dir):
  700. logger.warning(f"Config directory not found: {self.config_dir}")
  701. return []
  702. try:
  703. configs = []
  704. for filename in sorted(os.listdir(self.config_dir)):
  705. if filename.endswith(".conf"):
  706. filepath = os.path.join(self.config_dir, filename)
  707. if os.path.isfile(filepath):
  708. try:
  709. stat = os.stat(filepath)
  710. configs.append(
  711. {
  712. "filename": filename,
  713. "filepath": filepath,
  714. "size": stat.st_size,
  715. "modified": datetime.fromtimestamp(
  716. stat.st_mtime
  717. ).strftime("%Y-%m-%d %H:%M:%S"),
  718. "readable": os.access(filepath, os.R_OK),
  719. "writable": os.access(filepath, os.W_OK),
  720. }
  721. )
  722. except Exception as e:
  723. logger.warning(
  724. f"Error reading file info for {filename}: {e}"
  725. )
  726. return configs
  727. except Exception as e:
  728. logger.error(f"Error listing modular configs: {e}")
  729. return []
  730. def read_modular_config(self, filename: str) -> str | None:
  731. """Read a specific modular configuration file."""
  732. filepath = os.path.join(self.config_dir, filename)
  733. if not os.path.exists(filepath):
  734. logger.error(f"Config file not found: {filepath}")
  735. return None
  736. if not filepath.endswith(".conf"):
  737. logger.error(f"Invalid file extension: {filename}")
  738. return None
  739. try:
  740. with open(filepath, encoding="utf-8") as f:
  741. content = f.read()
  742. logger.debug(f"Read modular config: {filename}")
  743. return content
  744. except Exception as e:
  745. logger.error(f"Error reading modular config {filename}: {e}")
  746. return None
  747. def save_modular_config(self, filename: str, content: str) -> bool:
  748. """Save content to a specific modular configuration file."""
  749. filepath = os.path.join(self.config_dir, filename)
  750. if not filename.endswith(".conf"):
  751. logger.error(f"Invalid file extension: {filename}")
  752. return False
  753. # Validate filename to prevent directory traversal
  754. if "/" in filename or "\\" in filename or ".." in filename:
  755. logger.error(f"Invalid filename (potential path traversal): {filename}")
  756. return False
  757. try:
  758. # Create backup before saving
  759. if os.path.exists(filepath):
  760. backup_path = (
  761. f"{filepath}.bak{datetime.now().strftime('%Y%m%d_%H%M%S')}"
  762. )
  763. try:
  764. shutil.copy2(filepath, backup_path)
  765. logger.info(f"Backup created: {backup_path}")
  766. except Exception as e:
  767. logger.warning(f"Could not create backup: {e}")
  768. with open(filepath, "w", encoding="utf-8") as f:
  769. f.write(content)
  770. logger.info(f"Saved modular config: {filename}")
  771. return True
  772. except Exception as e:
  773. logger.error(f"Error saving modular config {filename}: {e}")
  774. return False
  775. def delete_modular_config(self, filename: str) -> bool:
  776. """Delete a specific modular configuration file."""
  777. filepath = os.path.join(self.config_dir, filename)
  778. if not os.path.exists(filepath):
  779. logger.error(f"Config file not found: {filepath}")
  780. return False
  781. if not filename.endswith(".conf"):
  782. logger.error(f"Invalid file extension: {filename}")
  783. return False
  784. # Validate filename to prevent directory traversal
  785. if "/" in filename or "\\" in filename or ".." in filename:
  786. logger.error(f"Invalid filename (potential path traversal): {filename}")
  787. return False
  788. try:
  789. # Create backup before deleting
  790. backup_path = (
  791. f"{filepath}.deleted{datetime.now().strftime('%Y%m%d_%H%M%S')}"
  792. )
  793. try:
  794. shutil.move(filepath, backup_path)
  795. logger.info(f"File moved to: {backup_path}")
  796. return True
  797. except Exception as e:
  798. logger.error(f"Error deleting file {filename}: {e}")
  799. return False
  800. except Exception as e:
  801. logger.error(f"Error handling file deletion {filename}: {e}")
  802. return False
  803. def get_modular_config_info(self) -> dict:
  804. """Get information about the modular configuration setup."""
  805. return {
  806. "is_modular": self.is_modular,
  807. "config_dir": self.config_dir,
  808. "config_dir_exists": os.path.exists(self.config_dir),
  809. "config_files_count": len(self.list_modular_configs()),
  810. "main_config_path": self.config_path,
  811. }
  812. def get_status(self):
  813. return {
  814. "is_valid": self.is_valid,
  815. "errors": self.errors,
  816. "config_loaded": bool(self.config_content),
  817. "config_path": self.config_path,
  818. "config_dir": self.config_dir,
  819. "is_modular": self.is_modular,
  820. "acl_files_dir": ACL_FILES_DIR,
  821. }