squid_config_splitter.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. import glob
  2. import os
  3. import re
  4. from dataclasses import dataclass
  5. from datetime import datetime
  6. from pathlib import Path
  7. from flask_babel import gettext as _
  8. from loguru import logger
  9. from utils.admin import SquidConfigManager, squid_config_write_lock
  10. _KERBEROS_MANAGED_MARKERS = (
  11. "# BEGIN SquidStats Kerberos authentication",
  12. "# END SquidStats Kerberos authentication",
  13. "# BEGIN SquidStats Kerberos access rule",
  14. "# END SquidStats Kerberos access rule",
  15. "# SQUIDSTATS KERBEROS AUTH START",
  16. "# SQUIDSTATS KERBEROS AUTH END",
  17. )
  18. _NEGOTIATE_AUTH_RE = re.compile(r"^\s*auth_param\s+negotiate\b", re.I | re.M)
  19. _INCLUDE_RE = re.compile(r"^\s*include\s+(.+?)\s*$", re.I)
  20. @dataclass(frozen=True)
  21. class Rule:
  22. filename: str
  23. patterns: list[re.Pattern]
  24. @dataclass
  25. class _FileSnapshot:
  26. """Original state of one output file in a split transaction."""
  27. path: str
  28. resolved_path: str
  29. existed: bool
  30. content: str | None
  31. written_content: str | None = None
  32. class SquidConfigSplitter:
  33. def __init__(
  34. self, input_file: str = None, output_dir: str = None, strict: bool = False
  35. ):
  36. self.input_file = input_file or "/etc/squid/squid.conf"
  37. self.output_dir = output_dir or "/etc/squid/squid.d"
  38. self.strict = strict
  39. self.unknown_file = "999_unknown.conf"
  40. self.has_auth = False
  41. self.auth_lines = []
  42. self.auth_patterns = [
  43. re.compile(r"^auth_param\b"),
  44. # Authentication ACLs need to be loaded after auth_param and
  45. # before rules in 120_http_access.conf. Kerberos names its ACL
  46. # explicitly (for example, `kerberos_auth`), not just `auth`.
  47. re.compile(r"^acl\s+\S+(?:\s+-\S+)*\s+proxy_auth\b"),
  48. ]
  49. self.rules = self._compile_rules()
  50. def _compile_rules(self) -> list[Rule]:
  51. """
  52. Compile the directive classification rules.
  53. The order matters and is intentional.
  54. """
  55. return [
  56. Rule(
  57. "00_ports.conf",
  58. [
  59. re.compile(r"^http_port\b"),
  60. ],
  61. ),
  62. Rule(
  63. "10_misc.conf",
  64. [
  65. re.compile(r"^max_filedesc\b"),
  66. re.compile(r"^pconn_lifetime\b"),
  67. re.compile(r"^visible_hostname\b"),
  68. re.compile(r"^pid_filename\b"),
  69. re.compile(r"^client_db\b"),
  70. re.compile(r"^cache_mgr\b"),
  71. ],
  72. ),
  73. Rule(
  74. "20_security.conf",
  75. [
  76. re.compile(r"^via\b"),
  77. re.compile(r"^forwarded_for\b"),
  78. re.compile(r"^request_header_access\b"),
  79. re.compile(r"^quick_abort"),
  80. re.compile(r"^httpd_suppress_version_string\b"),
  81. re.compile(r"^reload_into_ims\b"),
  82. re.compile(r"^read_ahead_gap\b"),
  83. re.compile(r"^negative_ttl\b"),
  84. re.compile(r"^positive_dns_ttl\b"),
  85. re.compile(r"^negative_dns_ttl\b"),
  86. re.compile(r"^range_offset_limit\b"),
  87. re.compile(r"^pinger_enable\b"),
  88. re.compile(r"^server_persistent_connections\b"),
  89. re.compile(r"^client_persistent_connections\b"),
  90. re.compile(r"^check_hostnames\b"),
  91. re.compile(r"^half_closed_clients\b"),
  92. ],
  93. ),
  94. Rule(
  95. "60_logs.conf",
  96. [
  97. re.compile(r"^access_log\b"),
  98. re.compile(r"^cache_log\b"),
  99. re.compile(r"^cache_store_log\b"),
  100. re.compile(r"^cache_access_log\b"),
  101. re.compile(r"^icap_log\b"),
  102. re.compile(r"^logformat\b"),
  103. re.compile(r"^strip_query_terms\b"),
  104. re.compile(r"^coredump_dir\b"),
  105. ],
  106. ),
  107. Rule(
  108. "30_cache.conf",
  109. [
  110. re.compile(
  111. r"^cache_(?!log\b|mgr\b|store_log\b|access_log\b|peer(?:\b|_))"
  112. ),
  113. re.compile(r"^maximum_object_"),
  114. re.compile(r"^minimum_object_"),
  115. re.compile(r"^memory_"),
  116. re.compile(r"^ipcache_"),
  117. re.compile(r"^fqdncache_"),
  118. ],
  119. ),
  120. Rule(
  121. "40_refresh_patterns.conf",
  122. [
  123. re.compile(r"^refresh_pattern\b"),
  124. ],
  125. ),
  126. Rule(
  127. "55_ssl_bump.conf",
  128. [
  129. re.compile(r"^ssl_"),
  130. re.compile(r"^sslcrtd_"),
  131. re.compile(r"^acl\s+\S+\s+at_step\b"),
  132. re.compile(r"sslproxy_"),
  133. ],
  134. ),
  135. Rule(
  136. "70_icap.conf",
  137. [
  138. re.compile(r"^icap_(?!log\b)"),
  139. re.compile(r"^adaptation_"),
  140. ],
  141. ),
  142. Rule(
  143. "80_dns.conf",
  144. [
  145. re.compile(r"^dns_"),
  146. re.compile(r"^hosts_file\b"),
  147. re.compile(r"^connect_timeout\b"),
  148. re.compile(r"^read_timeout\b"),
  149. ],
  150. ),
  151. Rule(
  152. "50_auth.conf",
  153. [
  154. *self.auth_patterns,
  155. re.compile(r"^authenticate_"),
  156. ],
  157. ),
  158. Rule(
  159. "100_acls.conf",
  160. [
  161. re.compile(
  162. r"^acl(?!\s+auth\b)(?!.*\bat_step\b)(?!.*\bproxy_auth\b)"
  163. ),
  164. re.compile(r"^external_acl_type\b"),
  165. ],
  166. ),
  167. Rule(
  168. "110_delay_pools.conf",
  169. [
  170. re.compile(r"^delay_"),
  171. ],
  172. ),
  173. Rule(
  174. "115_cache_control.conf",
  175. [
  176. re.compile(r"^no_cache\b"),
  177. re.compile(r"^icp_access\b"),
  178. re.compile(r"^cache_peer"),
  179. re.compile(r"^never_direct\b"),
  180. ],
  181. ),
  182. Rule(
  183. "120_http_access.conf",
  184. [
  185. re.compile(r"^http_access\b"),
  186. re.compile(r"^deny_info\b"),
  187. ],
  188. ),
  189. Rule(
  190. "90_includes.conf",
  191. [
  192. re.compile(r"^include\b"),
  193. ],
  194. ),
  195. ]
  196. def _get_load_order(self) -> list[str]:
  197. """
  198. Return the correct load order for config files.
  199. ACLs and auth must be loaded before being referenced.
  200. """
  201. return [
  202. "00_ports.conf",
  203. "10_misc.conf",
  204. "20_security.conf",
  205. "30_cache.conf",
  206. "40_refresh_patterns.conf",
  207. "50_auth.conf", # Auth defines 'auth' ACL
  208. "60_logs.conf",
  209. "80_dns.conf",
  210. "90_includes.conf", # Includes may define ACLs (e.g. usuarios_bloqueados)
  211. "100_acls.conf", # All other ACLs defined here
  212. "70_icap.conf", # Uses 'infoaccess' ACL
  213. "110_delay_pools.conf", # Uses 'auth', 'work_time_*', 'research_files' ACLs
  214. "115_cache_control.conf",
  215. "120_http_access.conf", # Uses all ACLs
  216. "55_ssl_bump.conf", # Can go anywhere but typically after ACLs
  217. self.unknown_file, # Catch-all for unclassified
  218. ]
  219. def _classify_line(self, line: str) -> str:
  220. matches = [
  221. rule.filename
  222. for rule in self.rules
  223. for pattern in rule.patterns
  224. if pattern.search(line)
  225. ]
  226. if len(matches) > 1:
  227. raise ValueError(
  228. f"Ambiguous rule match for line:\n{line}\nMatches: {matches}"
  229. )
  230. if matches:
  231. return matches[0]
  232. return self.unknown_file
  233. @staticmethod
  234. def _contains_kerberos_configuration(content: str) -> bool:
  235. """Whether a source contains managed or manually configured Negotiate.
  236. Splitting moves generic include directives into a normalized load order.
  237. That cannot preserve the position of a Kerberos challenge relative to
  238. arbitrary nested policy fragments, so the safe path is to refuse a
  239. split until the administrator has removed or migrated it deliberately.
  240. """
  241. # Squid permits directives to continue on the next physical line.
  242. # Test the logical directive as well; otherwise a split
  243. # ``auth_param`` / ``negotiate`` directive evades this guard and can
  244. # reorder a live Kerberos policy.
  245. logical_content = re.sub(r"\\[ \t]*\r?\n[ \t]*", " ", content)
  246. return _NEGOTIATE_AUTH_RE.search(logical_content) is not None or any(
  247. marker in content for marker in _KERBEROS_MANAGED_MARKERS
  248. )
  249. def _has_existing_kerberos_configuration(self, input_content: str) -> bool:
  250. """Inspect direct and recursively active sources before splitting."""
  251. seen = {os.path.realpath(self.input_file)}
  252. def logical_lines(content: str) -> list[str]:
  253. result: list[str] = []
  254. pending = ""
  255. for raw_line in content.splitlines():
  256. line = raw_line.split("#", 1)[0].strip()
  257. if not line:
  258. continue
  259. if pending:
  260. line = f"{pending} {line.lstrip()}"
  261. if line.rstrip().endswith("\\"):
  262. pending = line.rstrip()[:-1].rstrip()
  263. continue
  264. result.append(line)
  265. pending = ""
  266. if pending:
  267. result.append(pending)
  268. return result
  269. def visit(content: str, directory: str, depth: int = 0) -> bool:
  270. if self._contains_kerberos_configuration(content):
  271. return True
  272. if depth >= 8:
  273. # A deeper active config could contain a challenge whose
  274. # order this splitter cannot preserve.
  275. return any(
  276. _INCLUDE_RE.fullmatch(line) for line in logical_lines(content)
  277. )
  278. for line in logical_lines(content):
  279. match = _INCLUDE_RE.fullmatch(line)
  280. if not match:
  281. continue
  282. include_path = os.path.expanduser(match.group(1).strip().strip('"'))
  283. pattern = os.path.abspath(
  284. include_path
  285. if os.path.isabs(include_path)
  286. else os.path.join(directory, include_path)
  287. )
  288. try:
  289. candidates = sorted(glob.glob(pattern))
  290. except OSError:
  291. return True
  292. for candidate in candidates:
  293. real_candidate = os.path.realpath(candidate)
  294. if real_candidate in seen or not os.path.isfile(real_candidate):
  295. continue
  296. seen.add(real_candidate)
  297. try:
  298. with open(real_candidate, encoding="utf-8") as included:
  299. included_content = included.read()
  300. except (OSError, UnicodeDecodeError):
  301. # Do not rewrite an ordered configuration whose
  302. # active source cannot be inspected.
  303. return True
  304. if visit(
  305. included_content, os.path.dirname(real_candidate), depth + 1
  306. ):
  307. return True
  308. return False
  309. if visit(input_content, os.path.dirname(os.path.abspath(self.input_file))):
  310. return True
  311. if not os.path.isdir(self.output_dir):
  312. return False
  313. for filename in ("50_auth.conf", "120_http_access.conf"):
  314. path = os.path.join(self.output_dir, filename)
  315. try:
  316. with open(path, encoding="utf-8") as module:
  317. if self._contains_kerberos_configuration(module.read()):
  318. return True
  319. except FileNotFoundError:
  320. continue
  321. except (OSError, UnicodeDecodeError):
  322. # An unreadable conventional module must not be overwritten
  323. # by the splitter while its policy state is unknown.
  324. return True
  325. return False
  326. @staticmethod
  327. def _atomic_write(path: str, content: str, encoding: str = "utf-8") -> None:
  328. """Use the shared metadata-preserving Squid configuration writer.
  329. Splitting must retain a package's owner, mode, extended ACLs, and
  330. symbolic main-config link just like all other configuration editors.
  331. """
  332. SquidConfigManager._atomic_write(path, content, encoding)
  333. @staticmethod
  334. def _snapshot_file(path: str) -> _FileSnapshot:
  335. """Read an output target before replacing it, without following it later.
  336. The resolved path is retained so rollback can refuse to overwrite a
  337. target that another process has moved or changed while this transaction
  338. was in progress.
  339. """
  340. resolved_path = os.path.realpath(os.path.abspath(path))
  341. try:
  342. with open(resolved_path, encoding="utf-8") as existing:
  343. return _FileSnapshot(
  344. path=path,
  345. resolved_path=resolved_path,
  346. existed=True,
  347. content=existing.read(),
  348. )
  349. except FileNotFoundError:
  350. return _FileSnapshot(
  351. path=path,
  352. resolved_path=resolved_path,
  353. existed=False,
  354. content=None,
  355. )
  356. except (OSError, UnicodeDecodeError) as exc:
  357. raise RuntimeError(
  358. f"No se pudo respaldar el módulo de salida {os.path.basename(path)}."
  359. ) from exc
  360. @staticmethod
  361. def _assert_snapshot_is_current(snapshot: _FileSnapshot) -> None:
  362. """Refuse to replace a target changed after its transaction snapshot.
  363. The common flock protects cooperative SquidStats writers. This
  364. additional compare immediately before replacement protects against a
  365. manually edited or otherwise non-cooperating file between the initial
  366. transaction snapshot and the final write. A regular file system
  367. cannot provide a perfect CAS against a process that deliberately
  368. ignores locks, but this prevents the normal stale-write path and
  369. leaves its newer content untouched on failure.
  370. """
  371. current_path = os.path.realpath(os.path.abspath(snapshot.path))
  372. if current_path != snapshot.resolved_path:
  373. raise RuntimeError(
  374. f"La ruta de {os.path.basename(snapshot.path)} cambió durante la operación."
  375. )
  376. try:
  377. with open(snapshot.resolved_path, encoding="utf-8") as current:
  378. current_content: str | None = current.read()
  379. except FileNotFoundError:
  380. current_content = None
  381. except (OSError, UnicodeDecodeError) as exc:
  382. raise RuntimeError(
  383. f"No se pudo verificar {os.path.basename(snapshot.path)} antes de escribir."
  384. ) from exc
  385. if current_content != snapshot.content:
  386. raise RuntimeError(
  387. f"{os.path.basename(snapshot.path)} cambió durante la operación; no se sobrescribió."
  388. )
  389. def _restore_output_snapshot(self, snapshot: _FileSnapshot) -> str | None:
  390. """Restore one changed output file, avoiding an out-of-band overwrite."""
  391. if snapshot.written_content is None:
  392. return None
  393. if os.path.realpath(os.path.abspath(snapshot.path)) != snapshot.resolved_path:
  394. return f"{os.path.basename(snapshot.path)} (la ruta cambió durante la operación)"
  395. try:
  396. try:
  397. with open(snapshot.resolved_path, encoding="utf-8") as current:
  398. current_content: str | None = current.read()
  399. except FileNotFoundError:
  400. current_content = None
  401. if current_content != snapshot.written_content:
  402. return (
  403. f"{os.path.basename(snapshot.path)} (cambió durante la operación)"
  404. )
  405. if snapshot.existed:
  406. self._atomic_write(snapshot.path, snapshot.content or "")
  407. elif current_content is not None:
  408. os.unlink(snapshot.resolved_path)
  409. except OSError:
  410. logger.exception(
  411. "Could not restore generated split module %s", snapshot.path
  412. )
  413. return os.path.basename(snapshot.path)
  414. return None
  415. def _rollback_split_transaction(
  416. self,
  417. output_snapshots: list[_FileSnapshot],
  418. *,
  419. main_content: str,
  420. main_resolved_path: str,
  421. generated_main_content: str | None,
  422. created_output_dir: bool,
  423. ) -> list[str]:
  424. """Restore all changed files and return any incomplete rollback targets."""
  425. failures: list[str] = []
  426. if generated_main_content is not None:
  427. try:
  428. if (
  429. os.path.realpath(os.path.abspath(self.input_file))
  430. != main_resolved_path
  431. ):
  432. failures.append("squid.conf (la ruta cambió durante la operación)")
  433. else:
  434. with open(main_resolved_path, encoding="utf-8") as current:
  435. current_content = current.read()
  436. if current_content != generated_main_content:
  437. failures.append("squid.conf (cambió durante la operación)")
  438. else:
  439. self._atomic_write(self.input_file, main_content)
  440. except (OSError, UnicodeDecodeError):
  441. logger.exception("Rollback of squid.conf failed")
  442. failures.append("squid.conf")
  443. for snapshot in reversed(output_snapshots):
  444. failure = self._restore_output_snapshot(snapshot)
  445. if failure:
  446. failures.append(failure)
  447. if created_output_dir:
  448. try:
  449. os.rmdir(self.output_dir)
  450. except FileNotFoundError:
  451. pass
  452. except OSError:
  453. # It is safe to leave an empty/new directory behind. Do not
  454. # remove a directory that acquired an external file while the
  455. # transaction was running.
  456. logger.warning(
  457. "Could not remove newly-created output directory %s",
  458. self.output_dir,
  459. )
  460. return failures
  461. def split_config(self) -> dict[str, int]:
  462. """Split under the same inter-process lock as all config writers."""
  463. with squid_config_write_lock(self.input_file):
  464. return self._split_config_locked()
  465. def _split_config_locked(self) -> dict[str, int]:
  466. # Capture the input before creating output files. This snapshot is
  467. # also compared just before the generated main config replaces it.
  468. main_snapshot = self._snapshot_file(self.input_file)
  469. if not main_snapshot.existed:
  470. raise FileNotFoundError(f"File not found: {self.input_file}")
  471. # Read before creating output files. A split normalizes include order,
  472. # which can move a previously safe Kerberos challenge behind an allow
  473. # rule or separate its managed markers. Do not alter such a setup.
  474. _original_content = main_snapshot.content or ""
  475. if self._has_existing_kerberos_configuration(_original_content):
  476. raise RuntimeError(
  477. "No se puede dividir una configuración que contiene Kerberos/Negotiate "
  478. "o un include activo que no se pudo verificar. Migra o deshabilita "
  479. "Kerberos desde su pantalla dedicada y revisa los includes antes de "
  480. "dividir squid.conf."
  481. )
  482. # Create the output directory if it doesn't exist. Track ownership so
  483. # a failed transaction can remove only the empty directory it created.
  484. created_output_dir = not os.path.exists(self.output_dir)
  485. try:
  486. if not os.path.exists(self.output_dir):
  487. os.makedirs(self.output_dir, exist_ok=True)
  488. logger.info(f"Output directory created: {self.output_dir}")
  489. else:
  490. logger.info(f"Output directory already exists: {self.output_dir}")
  491. except PermissionError as e:
  492. logger.error(f"Permission denied to create directory: {self.output_dir}")
  493. raise PermissionError(
  494. f"No permissions to create directory: {self.output_dir}"
  495. ) from e
  496. except OSError as e:
  497. logger.error(f"Failed to create output directory: {e}")
  498. raise RuntimeError(
  499. f"Failed to create output directory: {self.output_dir}"
  500. ) from e
  501. buffers: dict[str, list[str]] = {}
  502. pending_comments: list[str] = []
  503. results: dict[str, int] = {}
  504. output_snapshots: list[_FileSnapshot] = []
  505. main_resolved_path = main_snapshot.resolved_path
  506. generated_main_content: str | None = None
  507. validation_error: str | None = None
  508. # A splitter instance may be reused by a caller; auth collection is a
  509. # property of this input transaction, not of the instance lifetime.
  510. self.has_auth = False
  511. self.auth_lines = []
  512. try:
  513. with open(self.input_file, encoding="utf-8") as f:
  514. in_continuation = False
  515. continuation_target = None
  516. for lineno, raw_line in enumerate(f, start=1):
  517. line = raw_line.rstrip("\n")
  518. stripped = line.strip()
  519. # Handle backslash continuation lines
  520. if in_continuation:
  521. buffers.setdefault(continuation_target, [])
  522. buffers[continuation_target].extend(pending_comments)
  523. pending_comments.clear()
  524. buffers[continuation_target].append(raw_line)
  525. if not line.rstrip().endswith("\\"):
  526. in_continuation = False
  527. continuation_target = None
  528. continue
  529. # Comments and empty lines
  530. if not stripped or stripped.startswith("#"):
  531. pending_comments.append(raw_line)
  532. continue
  533. # Check for auth lines and collect them
  534. if any(p.search(stripped) for p in self.auth_patterns):
  535. self.has_auth = True
  536. self.auth_lines.append(raw_line)
  537. try:
  538. target = self._classify_line(stripped)
  539. except ValueError:
  540. logger.exception(
  541. "Error classifying line %s: %s", lineno, stripped
  542. )
  543. raise RuntimeError("Error classifying configuration line")
  544. if target == self.unknown_file and self.strict:
  545. logger.error(
  546. "Unknown directive at line %s: %s", lineno, stripped
  547. )
  548. raise RuntimeError(
  549. "Unknown directive found in strict mode. Review configuration."
  550. )
  551. buffers.setdefault(target, [])
  552. buffers[target].extend(pending_comments)
  553. pending_comments.clear()
  554. buffers[target].append(raw_line)
  555. # Start tracking continuation if line ends with backslash
  556. if line.rstrip().endswith("\\"):
  557. in_continuation = True
  558. continuation_target = target
  559. # Orphaned final comments
  560. if pending_comments:
  561. buffers.setdefault(self.unknown_file, []).extend(pending_comments)
  562. # Ensure auth file is created if auth config exists
  563. self._ensure_auth_file(buffers)
  564. # Snapshot every output before any write. This makes an invalid
  565. # generated main file fully reversible even when it already
  566. # included this directory through a wildcard before the split.
  567. seen_output_targets: set[str] = set()
  568. snapshots_by_path: dict[str, _FileSnapshot] = {}
  569. for filename in sorted(buffers):
  570. path = os.path.join(self.output_dir, filename)
  571. snapshot = self._snapshot_file(path)
  572. if snapshot.resolved_path in seen_output_targets:
  573. raise RuntimeError(
  574. "Dos módulos de salida resuelven al mismo archivo; no es seguro dividir la configuración."
  575. )
  576. seen_output_targets.add(snapshot.resolved_path)
  577. output_snapshots.append(snapshot)
  578. snapshots_by_path[path] = snapshot
  579. # Final writing
  580. for filename, content in sorted(buffers.items()):
  581. path = os.path.join(self.output_dir, filename)
  582. rendered_content = "".join(content)
  583. snapshot = snapshots_by_path[path]
  584. try:
  585. self._assert_snapshot_is_current(snapshot)
  586. if not (snapshot.existed and snapshot.content == rendered_content):
  587. self._atomic_write(path, rendered_content)
  588. snapshot.written_content = rendered_content
  589. results[filename] = len(content)
  590. logger.info(f"[OK] {path} ({len(content)} lines)")
  591. except PermissionError:
  592. logger.exception("Permission denied writing to file: %s", path)
  593. raise RuntimeError("Permission denied writing generated file")
  594. except RuntimeError:
  595. # Keep a stale-snapshot error actionable. The outer
  596. # transaction handler will roll back only files it wrote,
  597. # preserving the external change that caused this abort.
  598. raise
  599. except Exception:
  600. logger.exception("Failed to write file: %s", path)
  601. raise RuntimeError("Failed to write generated file")
  602. # Generate the new main squid.conf with includes
  603. self._assert_snapshot_is_current(main_snapshot)
  604. generated_main_content = self._generate_main_config(buffers)
  605. logger.info(f"Generated new main config: {self.input_file}")
  606. # Validate Squid configuration
  607. validation_result = self._validate_squid_config()
  608. if not validation_result["success"]:
  609. validation_error = validation_result.get(
  610. "error_message", "Unknown error"
  611. )
  612. logger.error(
  613. "Squid configuration validation failed. Rolling back changes. Error: %s",
  614. validation_error,
  615. )
  616. raise RuntimeError("Squid configuration validation failed.")
  617. logger.info("Squid configuration validated successfully.")
  618. return results
  619. except Exception as exc:
  620. rollback_failures = self._rollback_split_transaction(
  621. output_snapshots,
  622. main_content=_original_content,
  623. main_resolved_path=main_resolved_path,
  624. generated_main_content=generated_main_content,
  625. created_output_dir=created_output_dir,
  626. )
  627. if rollback_failures:
  628. details = ", ".join(dict.fromkeys(rollback_failures))
  629. raise RuntimeError(
  630. "No se pudo dividir squid.conf y la restauración quedó incompleta "
  631. f"({details}). Revisa los archivos antes de recargar Squid."
  632. ) from exc
  633. if validation_error is not None:
  634. raise RuntimeError(
  635. "Squid configuration validation failed. Changes have been reverted.\n\n"
  636. f"Squid output:\n{validation_error}"
  637. ) from exc
  638. logger.exception("Error splitting configuration file")
  639. raise
  640. def _validate_squid_config(self) -> dict:
  641. """Validate the exact local or Docker runtime selected for Squid.
  642. Reuse the Kerberos runtime selection so an installed host binary never
  643. masks a Docker deployment, and so Docker receives its configured
  644. ``-f`` path rather than whatever its image happens to default to.
  645. """
  646. # Imported lazily to keep this generic splitter independent at module
  647. # load time while sharing one authoritative runtime policy.
  648. from services.squid.kerberos_config_service import ( # noqa: PLC0415
  649. _docker_config_mount_status,
  650. _docker_mounts,
  651. _find_squid_runtime,
  652. _runtime_selection_error,
  653. validate_squid_configuration,
  654. )
  655. runtime = _find_squid_runtime()
  656. if runtime is None:
  657. message = _runtime_selection_error() or (
  658. "No se encontró el runtime Squid configurado para validar la división."
  659. )
  660. logger.error(message)
  661. return {"success": False, "error_message": message}
  662. if runtime.kind == "docker":
  663. if not runtime.container_config_path:
  664. message = (
  665. "SQUID_CONTAINER_CONFIG_PATH no es una ruta absoluta segura "
  666. "dentro del contenedor Docker."
  667. )
  668. logger.error(message)
  669. return {"success": False, "error_message": message}
  670. mount_status = _docker_config_mount_status(
  671. runtime,
  672. Path(self.input_file),
  673. mounts=_docker_mounts(runtime),
  674. mounts_checked=True,
  675. )
  676. if mount_status.get("mapped") is not True:
  677. message = (
  678. "No se pudo comprobar que el squid.conf a dividir sea el archivo "
  679. "cargado por el contenedor Docker configurado."
  680. )
  681. logger.error(message)
  682. return {"success": False, "error_message": message}
  683. result = validate_squid_configuration(self.input_file, runtime)
  684. if result.get("available") and result.get("valid"):
  685. logger.info("Squid configuration validated successfully.")
  686. return {"success": True, "output": result.get("message", "")}
  687. message = result.get("message") or "Squid rechazó la configuración."
  688. logger.error("Squid configuration validation failed: %s", message)
  689. return {"success": False, "error_message": message}
  690. def _generate_main_config(self, buffers: dict[str, list[str]]) -> str:
  691. header = [
  692. "# ============================================================\n",
  693. "# Archivo generado automáticamente por SquidStats\n",
  694. f"# Fecha: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n",
  695. "# NO EDITAR A MANO - Los cambios se perderán\n",
  696. "# ============================================================\n",
  697. "\n",
  698. ]
  699. includes = []
  700. load_order = self._get_load_order()
  701. for filename in load_order:
  702. if filename in buffers:
  703. include_path = os.path.join(self.output_dir, filename)
  704. includes.append(f"include {include_path}\n")
  705. generated_content = "".join(header) + "".join(includes)
  706. try:
  707. self._atomic_write(self.input_file, generated_content)
  708. logger.info(
  709. f"Main configuration file regenerated with {len(includes)} includes in correct dependency order"
  710. )
  711. return generated_content
  712. except Exception:
  713. logger.exception("Failed to generate main config")
  714. raise RuntimeError("Failed to generate main config")
  715. def _ensure_auth_file(self, buffers: dict[str, list[str]]) -> None:
  716. """
  717. Ensure that 50_auth.conf is created if there are auth-related lines in the original config.
  718. """
  719. auth_filename = "50_auth.conf"
  720. if auth_filename in buffers:
  721. return # Already exists
  722. if self.has_auth:
  723. # Create auth file content from collected lines
  724. auth_content = ["# Auth Configuration\n"] + self.auth_lines
  725. buffers[auth_filename] = auth_content
  726. logger.info(
  727. f"Created {auth_filename} with authentication configuration from original file"
  728. )
  729. def get_split_info(self) -> dict[str, str]:
  730. return {
  731. "00_ports.conf": "HTTP ports configuration",
  732. "10_misc.conf": "Miscellaneous configurations",
  733. "20_security.conf": "Security configuration",
  734. "30_cache.conf": "Cache configuration",
  735. "40_refresh_patterns.conf": "Refresh patterns",
  736. "50_auth.conf": "Authentication configuration",
  737. "55_ssl_bump.conf": "SSL Bump configuration",
  738. "60_logs.conf": "Logs configuration",
  739. "70_icap.conf": "ICAP configuration",
  740. "80_dns.conf": "DNS configuration",
  741. "100_acls.conf": "Access control lists (ACLs)",
  742. "110_delay_pools.conf": "Delay pools configuration",
  743. "115_cache_control.conf": "Cache control and peering",
  744. "120_http_access.conf": "HTTP access rules",
  745. "90_includes.conf": "Additional include directives",
  746. "999_unknown.conf": "Unclassified directives",
  747. }
  748. def check_output_dir_exists(self) -> bool:
  749. return os.path.exists(self.output_dir) and os.path.isdir(self.output_dir)
  750. def count_files_in_output_dir(self) -> int:
  751. if not self.check_output_dir_exists():
  752. return 0
  753. return len([f for f in os.listdir(self.output_dir) if f.endswith(".conf")])
  754. @staticmethod
  755. def get_split_files_info(output_dir: str = None) -> dict:
  756. if output_dir is None:
  757. output_dir = "/etc/squid/squid.d"
  758. if not os.path.exists(output_dir):
  759. return {
  760. "status": "error",
  761. "message": f"El directorio {output_dir} no existe",
  762. "code": 404,
  763. }
  764. try:
  765. files_info = []
  766. for filename in sorted(os.listdir(output_dir)):
  767. if filename.endswith(".conf"):
  768. file_path = os.path.join(output_dir, filename)
  769. try:
  770. # Get file statistics
  771. stat_info = os.stat(file_path)
  772. file_size = stat_info.st_size
  773. modified_time = datetime.fromtimestamp(
  774. stat_info.st_mtime
  775. ).strftime("%Y-%m-%d %H:%M:%S")
  776. # Count lines
  777. with open(file_path, encoding="utf-8") as f:
  778. line_count = sum(1 for _ in f)
  779. files_info.append(
  780. {
  781. "filename": filename,
  782. "size": file_size,
  783. "size_human": f"{file_size / 1024:.2f} KB"
  784. if file_size > 1024
  785. else f"{file_size} B",
  786. "lines": line_count,
  787. "modified": modified_time,
  788. }
  789. )
  790. except Exception as e:
  791. logger.error(f"Error al leer archivo {filename}: {e}")
  792. continue
  793. return {
  794. "status": "success",
  795. "data": {
  796. "output_dir": output_dir,
  797. "files": files_info,
  798. "total_files": len(files_info),
  799. },
  800. }
  801. except PermissionError as e:
  802. logger.error(f"Error de permisos al leer archivos: {e}")
  803. return {
  804. "status": "error",
  805. "message": _(
  806. "No se tienen permisos suficientes para leer los archivos"
  807. ),
  808. "code": 403,
  809. }
  810. except Exception:
  811. logger.exception("Error al obtener archivos de configuración")
  812. return {
  813. "status": "error",
  814. "message": _("Error interno al obtener los archivos"),
  815. "code": 500,
  816. }