squid_config_splitter.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. import os
  2. import re
  3. import shutil
  4. import subprocess
  5. from dataclasses import dataclass
  6. from datetime import datetime
  7. from loguru import logger
  8. @dataclass(frozen=True)
  9. class Rule:
  10. filename: str
  11. patterns: list[re.Pattern]
  12. class SquidConfigSplitter:
  13. def __init__(
  14. self, input_file: str = None, output_dir: str = None, strict: bool = False
  15. ):
  16. self.input_file = input_file or "/etc/squid/squid.conf"
  17. self.output_dir = output_dir or "/etc/squid/squid.d"
  18. self.strict = strict
  19. self.unknown_file = "999_unknown.conf"
  20. self.has_auth = False
  21. self.auth_lines = []
  22. self.auth_patterns = [re.compile(r"^auth_param\b"), re.compile(r"^acl auth\b")]
  23. self.rules = self._compile_rules()
  24. def _compile_rules(self) -> list[Rule]:
  25. """
  26. Compile the directive classification rules.
  27. The order matters and is intentional.
  28. """
  29. return [
  30. Rule(
  31. "00_ports.conf",
  32. [
  33. re.compile(r"^http_port\b"),
  34. ],
  35. ),
  36. Rule(
  37. "10_misc.conf",
  38. [
  39. re.compile(r"^max_filedesc\b"),
  40. re.compile(r"^pconn_lifetime\b"),
  41. re.compile(r"^visible_hostname\b"),
  42. re.compile(r"^pid_filename\b"),
  43. re.compile(r"^client_db\b"),
  44. re.compile(r"^cache_mgr\b"),
  45. ],
  46. ),
  47. Rule(
  48. "20_security.conf",
  49. [
  50. re.compile(r"^via\b"),
  51. re.compile(r"^forwarded_for\b"),
  52. re.compile(r"^request_header_access\b"),
  53. re.compile(r"^quick_abort"),
  54. re.compile(r"^httpd_suppress_version_string\b"),
  55. re.compile(r"^reload_into_ims\b"),
  56. re.compile(r"^read_ahead_gap\b"),
  57. re.compile(r"^negative_ttl\b"),
  58. re.compile(r"^positive_dns_ttl\b"),
  59. re.compile(r"^negative_dns_ttl\b"),
  60. re.compile(r"^range_offset_limit\b"),
  61. re.compile(r"^pinger_enable\b"),
  62. re.compile(r"^server_persistent_connections\b"),
  63. re.compile(r"^client_persistent_connections\b"),
  64. re.compile(r"^check_hostnames\b"),
  65. re.compile(r"^half_closed_clients\b"),
  66. ],
  67. ),
  68. Rule(
  69. "60_logs.conf",
  70. [
  71. re.compile(r"^access_log\b"),
  72. re.compile(r"^cache_log\b"),
  73. re.compile(r"^cache_store_log\b"),
  74. re.compile(r"^cache_access_log\b"),
  75. re.compile(r"^icap_log\b"),
  76. re.compile(r"^logformat\b"),
  77. re.compile(r"^strip_query_terms\b"),
  78. re.compile(r"^coredump_dir\b"),
  79. ],
  80. ),
  81. Rule(
  82. "30_cache.conf",
  83. [
  84. re.compile(r"^cache_(?!log\b|mgr\b|store_log\b|access_log\b)"),
  85. re.compile(r"^maximum_object_"),
  86. re.compile(r"^minimum_object_"),
  87. re.compile(r"^memory_"),
  88. re.compile(r"^ipcache_"),
  89. re.compile(r"^fqdncache_"),
  90. ],
  91. ),
  92. Rule(
  93. "40_refresh_patterns.conf",
  94. [
  95. re.compile(r"^refresh_pattern\b"),
  96. ],
  97. ),
  98. Rule(
  99. "55_ssl_bump.conf",
  100. [
  101. re.compile(r"^ssl_"),
  102. re.compile(r"^sslcrtd_"),
  103. re.compile(r"^acl\s+\S+\s+at_step\b"),
  104. re.compile(r"sslproxy_"),
  105. ],
  106. ),
  107. Rule(
  108. "70_icap.conf",
  109. [
  110. re.compile(r"^icap_(?!log\b)"),
  111. re.compile(r"^adaptation_"),
  112. ],
  113. ),
  114. Rule(
  115. "80_dns.conf",
  116. [
  117. re.compile(r"^dns_"),
  118. re.compile(r"^hosts_file\b"),
  119. re.compile(r"^connect_timeout\b"),
  120. re.compile(r"^read_timeout\b"),
  121. ],
  122. ),
  123. Rule(
  124. "50_auth.conf",
  125. [
  126. re.compile(r"^auth_param\b"),
  127. re.compile(r"^authenticate_"),
  128. re.compile(r"^acl auth\b"),
  129. ],
  130. ),
  131. Rule(
  132. "100_acls.conf",
  133. [
  134. re.compile(r"^acl(?! auth\b)(?!.*\bat_step\b)"),
  135. re.compile(r"^external_acl_type\b"),
  136. ],
  137. ),
  138. Rule(
  139. "110_delay_pools.conf",
  140. [
  141. re.compile(r"^delay_"),
  142. ],
  143. ),
  144. Rule(
  145. "115_cache_control.conf",
  146. [
  147. re.compile(r"^no_cache\b"),
  148. re.compile(r"^icp_access\b"),
  149. re.compile(r"^cache_peer"),
  150. re.compile(r"^never_direct\b"),
  151. ],
  152. ),
  153. Rule(
  154. "120_http_access.conf",
  155. [
  156. re.compile(r"^http_access\b"),
  157. re.compile(r"^deny_info\b"),
  158. ],
  159. ),
  160. Rule(
  161. "90_includes.conf",
  162. [
  163. re.compile(r"^include\b"),
  164. ],
  165. ),
  166. ]
  167. def _get_load_order(self) -> list[str]:
  168. """
  169. Return the correct load order for config files.
  170. ACLs and auth must be loaded before being referenced.
  171. """
  172. return [
  173. "00_ports.conf",
  174. "10_misc.conf",
  175. "20_security.conf",
  176. "30_cache.conf",
  177. "40_refresh_patterns.conf",
  178. "50_auth.conf", # Auth defines 'auth' ACL
  179. "60_logs.conf",
  180. "80_dns.conf",
  181. "100_acls.conf", # All other ACLs defined here
  182. "70_icap.conf", # Uses 'infoaccess' ACL
  183. "110_delay_pools.conf", # Uses 'auth', 'work_time_*', 'research_files' ACLs
  184. "115_cache_control.conf",
  185. "120_http_access.conf", # Uses all ACLs
  186. "55_ssl_bump.conf", # Can go anywhere but typically after ACLs
  187. "90_includes.conf", # Additional includes
  188. self.unknown_file, # Catch-all for unclassified
  189. ]
  190. def _classify_line(self, line: str) -> str:
  191. matches = [
  192. rule.filename
  193. for rule in self.rules
  194. for pattern in rule.patterns
  195. if pattern.search(line)
  196. ]
  197. if len(matches) > 1:
  198. raise ValueError(
  199. f"Ambiguous rule match for line:\n{line}\nMatches: {matches}"
  200. )
  201. if matches:
  202. return matches[0]
  203. return self.unknown_file
  204. def split_config(self) -> dict[str, int]:
  205. # Verify that the input file exists
  206. if not os.path.exists(self.input_file):
  207. raise FileNotFoundError(f"File not found: {self.input_file}")
  208. # Create backup of squid.conf before splitting
  209. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  210. backup_file = f"{self.input_file}.bak{timestamp}"
  211. try:
  212. shutil.copy2(self.input_file, backup_file)
  213. logger.info(f"Backup created: {backup_file}")
  214. except PermissionError:
  215. logger.exception("Permission denied to create backup file: %s", backup_file)
  216. raise RuntimeError("Permission denied to create backup file")
  217. except Exception:
  218. logger.exception("Failed to create backup file: %s", backup_file)
  219. raise RuntimeError("Failed to create backup file")
  220. # Create the output directory if it doesn't exist
  221. try:
  222. if not os.path.exists(self.output_dir):
  223. os.makedirs(self.output_dir, exist_ok=True)
  224. logger.info(f"Output directory created: {self.output_dir}")
  225. else:
  226. logger.info(f"Output directory already exists: {self.output_dir}")
  227. except PermissionError as e:
  228. logger.error(f"Permission denied to create directory: {self.output_dir}")
  229. raise PermissionError(
  230. f"No permissions to create directory: {self.output_dir}"
  231. ) from e
  232. except OSError as e:
  233. logger.error(f"Failed to create output directory: {e}")
  234. raise RuntimeError(
  235. f"Failed to create output directory: {self.output_dir}"
  236. ) from e
  237. buffers: dict[str, list[str]] = {}
  238. pending_comments: list[str] = []
  239. results: dict[str, int] = {}
  240. results["_backup_file"] = backup_file
  241. try:
  242. with open(self.input_file, encoding="utf-8") as f:
  243. in_continuation = False
  244. continuation_target = None
  245. for lineno, raw_line in enumerate(f, start=1):
  246. line = raw_line.rstrip("\n")
  247. stripped = line.strip()
  248. # Handle backslash continuation lines
  249. if in_continuation:
  250. buffers.setdefault(continuation_target, [])
  251. buffers[continuation_target].extend(pending_comments)
  252. pending_comments.clear()
  253. buffers[continuation_target].append(raw_line)
  254. if not line.rstrip().endswith("\\"):
  255. in_continuation = False
  256. continuation_target = None
  257. continue
  258. # Comments and empty lines
  259. if not stripped or stripped.startswith("#"):
  260. pending_comments.append(raw_line)
  261. continue
  262. # Check for auth lines and collect them
  263. if any(p.search(stripped) for p in self.auth_patterns):
  264. self.has_auth = True
  265. self.auth_lines.append(raw_line)
  266. try:
  267. target = self._classify_line(stripped)
  268. except ValueError:
  269. logger.exception(
  270. "Error classifying line %s: %s", lineno, stripped
  271. )
  272. raise RuntimeError("Error classifying configuration line")
  273. if target == self.unknown_file and self.strict:
  274. logger.error(
  275. "Unknown directive at line %s: %s", lineno, stripped
  276. )
  277. raise RuntimeError(
  278. "Unknown directive found in strict mode. Review configuration."
  279. )
  280. buffers.setdefault(target, [])
  281. buffers[target].extend(pending_comments)
  282. pending_comments.clear()
  283. buffers[target].append(raw_line)
  284. # Start tracking continuation if line ends with backslash
  285. if line.rstrip().endswith("\\"):
  286. in_continuation = True
  287. continuation_target = target
  288. # Orphaned final comments
  289. if pending_comments:
  290. buffers.setdefault(self.unknown_file, []).extend(pending_comments)
  291. # Ensure auth file is created if auth config exists
  292. self._ensure_auth_file(buffers)
  293. # Final writing
  294. for filename, content in sorted(buffers.items()):
  295. path = os.path.join(self.output_dir, filename)
  296. try:
  297. with open(path, "w", encoding="utf-8") as f:
  298. f.writelines(content)
  299. results[filename] = len(content)
  300. logger.info(f"[OK] {path} ({len(content)} lines)")
  301. except PermissionError:
  302. logger.exception("Permission denied writing to file: %s", path)
  303. raise RuntimeError("Permission denied writing generated file")
  304. except Exception:
  305. logger.exception("Failed to write file: %s", path)
  306. raise RuntimeError("Failed to write generated file")
  307. # Generate the new main squid.conf with includes
  308. self._generate_main_config(buffers)
  309. logger.info(f"Generated new main config: {self.input_file}")
  310. # Validate Squid configuration
  311. validation_result = self._validate_squid_config()
  312. if not validation_result["success"]:
  313. error_details = validation_result.get("error_message", "Unknown error")
  314. logger.error(
  315. "Squid configuration validation failed. Rolling back changes. Error: %s",
  316. error_details,
  317. )
  318. self._rollback_changes(backup_file, list(buffers.keys()))
  319. raise RuntimeError(
  320. f"Squid configuration validation failed. Changes have been reverted.\n\nSquid output:\n{error_details}"
  321. )
  322. logger.info("Squid configuration validated successfully.")
  323. return results
  324. except Exception:
  325. logger.exception("Error splitting configuration file")
  326. raise
  327. def _validate_squid_config(self) -> dict:
  328. """
  329. Validate Squid configuration using 'squid -k parse'.
  330. First tries the system squid command; if not found, falls back to Docker.
  331. Returns dict with 'success' (bool), 'output' (str), and 'error_message' (str) if failed.
  332. """
  333. def _run_command(cmd: list[str]) -> dict:
  334. """Run a validation command and return a result dict."""
  335. try:
  336. result = subprocess.run(
  337. cmd,
  338. capture_output=True,
  339. text=True,
  340. timeout=30,
  341. )
  342. stdout_output = result.stdout.strip() if result.stdout else ""
  343. stderr_output = result.stderr.strip() if result.stderr else ""
  344. full_output = ""
  345. if stdout_output:
  346. full_output += f"STDOUT:\n{stdout_output}\n"
  347. if stderr_output:
  348. full_output += f"STDERR:\n{stderr_output}\n"
  349. if not full_output:
  350. full_output = "No output from squid command"
  351. return {
  352. "ran": True,
  353. "returncode": result.returncode,
  354. "output": full_output,
  355. }
  356. except subprocess.TimeoutExpired as e:
  357. stdout_partial = e.stdout.strip() if e.stdout else ""
  358. stderr_partial = e.stderr.strip() if e.stderr else ""
  359. partial_output = ""
  360. if stdout_partial:
  361. partial_output += f"STDOUT (partial):\n{stdout_partial}\n"
  362. if stderr_partial:
  363. partial_output += f"STDERR (partial):\n{stderr_partial}\n"
  364. return {
  365. "ran": True,
  366. "returncode": -1,
  367. "output": partial_output,
  368. "timeout": True,
  369. }
  370. except FileNotFoundError:
  371. return {"ran": False, "output": ""}
  372. except Exception as e:
  373. return {"ran": True, "returncode": -1, "output": str(e)}
  374. # --- Try system squid first ---
  375. logger.info("Validating Squid configuration with 'squid -k parse'...")
  376. res = _run_command(["squid", "-k", "parse"])
  377. if not res["ran"]:
  378. # squid binary not found on the system, try Docker
  379. logger.warning(
  380. "'squid' not found on system. Trying Docker fallback "
  381. "('docker exec squid_proxy squid -k parse')..."
  382. )
  383. res = _run_command(
  384. ["docker", "exec", "squid_proxy", "squid", "-k", "parse"]
  385. )
  386. if not res["ran"]:
  387. error_msg = (
  388. "Neither 'squid' nor 'docker' command found. "
  389. "Cannot validate configuration. "
  390. "Please ensure Squid is installed (system or Docker)."
  391. )
  392. logger.error(error_msg)
  393. return {"success": False, "error_message": error_msg}
  394. # --- Evaluate result ---
  395. if res.get("timeout"):
  396. error_msg = f"Squid configuration validation timed out after 30 seconds.\n{res['output']}"
  397. logger.error(error_msg)
  398. return {
  399. "success": False,
  400. "error_message": error_msg,
  401. "output": res["output"],
  402. }
  403. if res["returncode"] == 0:
  404. logger.info(
  405. f"Squid configuration is valid.\nCommand output:\n{res['output']}"
  406. )
  407. return {
  408. "success": True,
  409. "output": res["output"],
  410. "return_code": res["returncode"],
  411. }
  412. error_msg = (
  413. f"Validation failed with return code {res['returncode']}\n{res['output']}"
  414. )
  415. logger.error(f"Squid configuration validation failed:\n{error_msg}")
  416. return {
  417. "success": False,
  418. "error_message": error_msg,
  419. "output": res["output"],
  420. "return_code": res["returncode"],
  421. }
  422. def _rollback_changes(self, backup_file: str, generated_files: list[str]) -> None:
  423. """
  424. Rollback changes by restoring the backup and deleting generated files.
  425. """
  426. try:
  427. # Restore backup
  428. if os.path.exists(backup_file):
  429. shutil.copy2(backup_file, self.input_file)
  430. logger.info(f"Restored backup from {backup_file} to {self.input_file}")
  431. else:
  432. logger.error(f"Backup file not found: {backup_file}")
  433. # Delete generated files
  434. for filename in generated_files:
  435. file_path = os.path.join(self.output_dir, filename)
  436. if os.path.exists(file_path):
  437. os.remove(file_path)
  438. logger.info(f"Deleted generated file: {file_path}")
  439. logger.info("Rollback completed successfully.")
  440. except Exception:
  441. logger.exception("Error during rollback")
  442. raise RuntimeError("Rollback failed")
  443. def _generate_main_config(self, buffers: dict[str, list[str]]) -> None:
  444. header = [
  445. "# ============================================================\n",
  446. "# Archivo generado automáticamente por SquidStats\n",
  447. f"# Fecha: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n",
  448. "# NO EDITAR A MANO - Los cambios se perderán\n",
  449. "# ============================================================\n",
  450. "\n",
  451. ]
  452. includes = []
  453. load_order = self._get_load_order()
  454. for filename in load_order:
  455. if filename in buffers:
  456. include_path = os.path.join(self.output_dir, filename)
  457. includes.append(f"include {include_path}\n")
  458. try:
  459. with open(self.input_file, "w", encoding="utf-8") as f:
  460. f.writelines(header)
  461. f.writelines(includes)
  462. logger.info(
  463. f"Main configuration file regenerated with {len(includes)} includes in correct dependency order"
  464. )
  465. except Exception:
  466. logger.exception("Failed to generate main config")
  467. raise RuntimeError("Failed to generate main config")
  468. def _ensure_auth_file(self, buffers: dict[str, list[str]]) -> None:
  469. """
  470. Ensure that 50_auth.conf is created if there are auth-related lines in the original config.
  471. """
  472. auth_filename = "50_auth.conf"
  473. if auth_filename in buffers:
  474. return # Already exists
  475. if self.has_auth:
  476. # Create auth file content from collected lines
  477. auth_content = ["# Auth Configuration\n"] + self.auth_lines
  478. buffers[auth_filename] = auth_content
  479. logger.info(
  480. f"Created {auth_filename} with authentication configuration from original file"
  481. )
  482. def get_split_info(self) -> dict[str, str]:
  483. return {
  484. "00_ports.conf": "HTTP ports configuration",
  485. "10_misc.conf": "Miscellaneous configurations",
  486. "20_security.conf": "Security configuration",
  487. "30_cache.conf": "Cache configuration",
  488. "40_refresh_patterns.conf": "Refresh patterns",
  489. "50_auth.conf": "Authentication configuration",
  490. "55_ssl_bump.conf": "SSL Bump configuration",
  491. "60_logs.conf": "Logs configuration",
  492. "70_icap.conf": "ICAP configuration",
  493. "80_dns.conf": "DNS configuration",
  494. "100_acls.conf": "Access control lists (ACLs)",
  495. "110_delay_pools.conf": "Delay pools configuration",
  496. "115_cache_control.conf": "Cache control and peering",
  497. "120_http_access.conf": "HTTP access rules",
  498. "90_includes.conf": "Additional include directives",
  499. "999_unknown.conf": "Unclassified directives",
  500. }
  501. def check_output_dir_exists(self) -> bool:
  502. return os.path.exists(self.output_dir) and os.path.isdir(self.output_dir)
  503. def count_files_in_output_dir(self) -> int:
  504. if not self.check_output_dir_exists():
  505. return 0
  506. return len([f for f in os.listdir(self.output_dir) if f.endswith(".conf")])
  507. @staticmethod
  508. def get_split_files_info(output_dir: str = None) -> dict:
  509. if output_dir is None:
  510. output_dir = "/etc/squid/squid.d"
  511. if not os.path.exists(output_dir):
  512. return {
  513. "status": "error",
  514. "message": f"El directorio {output_dir} no existe",
  515. "code": 404,
  516. }
  517. try:
  518. files_info = []
  519. for filename in sorted(os.listdir(output_dir)):
  520. if filename.endswith(".conf"):
  521. file_path = os.path.join(output_dir, filename)
  522. try:
  523. # Get file statistics
  524. stat_info = os.stat(file_path)
  525. file_size = stat_info.st_size
  526. modified_time = datetime.fromtimestamp(
  527. stat_info.st_mtime
  528. ).strftime("%Y-%m-%d %H:%M:%S")
  529. # Count lines
  530. with open(file_path, encoding="utf-8") as f:
  531. line_count = sum(1 for _ in f)
  532. files_info.append(
  533. {
  534. "filename": filename,
  535. "size": file_size,
  536. "size_human": f"{file_size / 1024:.2f} KB"
  537. if file_size > 1024
  538. else f"{file_size} B",
  539. "lines": line_count,
  540. "modified": modified_time,
  541. }
  542. )
  543. except Exception as e:
  544. logger.error(f"Error al leer archivo {filename}: {e}")
  545. continue
  546. return {
  547. "status": "success",
  548. "data": {
  549. "output_dir": output_dir,
  550. "files": files_info,
  551. "total_files": len(files_info),
  552. },
  553. }
  554. except PermissionError as e:
  555. logger.error(f"Error de permisos al leer archivos: {e}")
  556. return {
  557. "status": "error",
  558. "message": "No se tienen permisos suficientes para leer los archivos",
  559. "code": 403,
  560. }
  561. except Exception:
  562. logger.exception("Error al obtener archivos de configuración")
  563. return {
  564. "status": "error",
  565. "message": "Error interno al obtener los archivos",
  566. "code": 500,
  567. }