4
0

squid_config_splitter.py 25 KB

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