admin.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import logging
  2. import os
  3. from dotenv import load_dotenv
  4. logger = logging.getLogger(__name__)
  5. load_dotenv()
  6. SQUID_CONFIG_PATH = os.getenv("SQUID_CONFIG_PATH", "/etc/squid/squid.conf")
  7. ACL_FILES_DIR = os.getenv("ACL_FILES_DIR", "/etc/squid/acls")
  8. def validate_paths():
  9. errors = []
  10. cfg = os.path.abspath(os.path.expanduser(SQUID_CONFIG_PATH))
  11. if os.path.isdir(cfg):
  12. squid_conf = os.path.join(cfg, "squid.conf")
  13. if not os.path.exists(squid_conf):
  14. errors.append(f"'squid.conf' not found in directory: {cfg}")
  15. else:
  16. if not os.path.isfile(squid_conf):
  17. errors.append(f"Found but not a regular file: {squid_conf}")
  18. else:
  19. if not os.access(squid_conf, os.R_OK):
  20. errors.append(f"No read permissions for: {squid_conf}")
  21. if not os.access(squid_conf, os.W_OK):
  22. errors.append(f"No write permissions for: {squid_conf}")
  23. else:
  24. squid_conf = cfg
  25. if not os.path.exists(squid_conf):
  26. errors.append(f"Configuration file not found: {squid_conf}")
  27. else:
  28. if not os.path.isfile(squid_conf):
  29. errors.append(f"Not a regular file: {squid_conf}")
  30. if os.path.basename(squid_conf) != "squid.conf":
  31. errors.append(
  32. f"Expected file named 'squid.conf', got: {os.path.basename(squid_conf)}"
  33. )
  34. if os.path.isfile(squid_conf):
  35. if not os.access(squid_conf, os.R_OK):
  36. errors.append(f"No read permissions for: {squid_conf}")
  37. if not os.access(squid_conf, os.W_OK):
  38. errors.append(f"No write permissions for: {squid_conf}")
  39. acl_dir = os.path.abspath(os.path.expanduser(ACL_FILES_DIR))
  40. if not os.path.exists(acl_dir):
  41. errors.append(f"ACL directory not found: {acl_dir}")
  42. elif not os.path.isdir(acl_dir):
  43. errors.append(f"ACL path is not a directory: {acl_dir}")
  44. elif not os.access(acl_dir, os.W_OK):
  45. errors.append(f"No write permissions in ACL directory: {acl_dir}")
  46. return errors
  47. class SquidConfigManager:
  48. def __init__(self, config_path=SQUID_CONFIG_PATH):
  49. self.config_path = config_path
  50. self.config_content = ""
  51. self.is_valid = False
  52. self.errors = []
  53. self._validate_environment()
  54. if self.is_valid:
  55. self.load_config()
  56. def _validate_environment(self):
  57. self.errors = validate_paths()
  58. if self.errors:
  59. for error in self.errors:
  60. logger.error(error)
  61. self.is_valid = False
  62. logger.error(
  63. "SquidConfigManager cannot be initialized due to configuration errors"
  64. )
  65. else:
  66. self.is_valid = True
  67. logger.info("SquidConfigManager initialized successfully")
  68. def load_config(self):
  69. if not self.is_valid:
  70. logger.error("Cannot load configuration: invalid environment")
  71. return False
  72. try:
  73. with open(self.config_path, encoding="utf-8") as f:
  74. self.config_content = f.read()
  75. logger.debug(f"Configuration loaded from: {self.config_path}")
  76. return True
  77. except FileNotFoundError:
  78. logger.error(f"Configuration file not found: {self.config_path}")
  79. self.config_content = ""
  80. return False
  81. except PermissionError:
  82. logger.error(f"No read permissions for: {self.config_path}")
  83. self.config_content = ""
  84. return False
  85. except UnicodeDecodeError as e:
  86. logger.error(f"File encoding error: {e}")
  87. self.config_content = ""
  88. return False
  89. except Exception as e:
  90. logger.error(f"Unexpected error loading configuration: {e}")
  91. self.config_content = ""
  92. return False
  93. def save_config(self, content):
  94. if not self.is_valid:
  95. logger.error("Cannot save configuration: invalid environment")
  96. return False
  97. try:
  98. backup_created = self.create_backup()
  99. if not backup_created:
  100. logger.warning("Could not create backup, but continuing with save...")
  101. with open(self.config_path, "w", encoding="utf-8") as f:
  102. f.write(content)
  103. self.config_content = content
  104. logger.info(f"Configuration saved successfully to: {self.config_path}")
  105. return True
  106. except PermissionError:
  107. logger.error(f"No write permissions for: {self.config_path}")
  108. return False
  109. except OSError as e:
  110. logger.error(f"System error saving configuration: {e}")
  111. return False
  112. except Exception as e:
  113. logger.error(f"Unexpected error saving configuration: {e}")
  114. return False
  115. def create_backup(self):
  116. if not self.is_valid:
  117. logger.error("Cannot create backup: invalid environment")
  118. return False
  119. """ try:
  120. if not os.path.exists(BACKUP_DIR):
  121. logger.error(f"Backup directory does not exist: {BACKUP_DIR}")
  122. return False
  123. if not os.access(BACKUP_DIR, os.W_OK):
  124. logger.error(f"No write permissions in backup directory: {BACKUP_DIR}")
  125. return False
  126. if not os.path.exists(self.config_path):
  127. logger.warning("No configuration file exists to backup")
  128. return False
  129. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  130. backup_filename = f"squid.conf.backup_{timestamp}"
  131. backup_path = os.path.join(BACKUP_DIR, backup_filename)
  132. shutil.copy2(self.config_path, backup_path)
  133. logger.info(f"Backup created: {backup_path}")
  134. return True
  135. except PermissionError:
  136. logger.error(f"No permissions to create backup in: {BACKUP_DIR}")
  137. return False
  138. except OSError as e:
  139. logger.error(f"System error creating backup: {e}")
  140. return False
  141. except Exception as e:
  142. logger.error(f"Unexpected error creating backup: {e}")
  143. return False """
  144. def get_acls(self):
  145. if not self.is_valid:
  146. logger.error("Cannot get ACLs: invalid environment")
  147. return []
  148. if not self.config_content:
  149. logger.warning("No configuration content available")
  150. return []
  151. try:
  152. acls = []
  153. lines = self.config_content.split("\n")
  154. acl_index = 0
  155. for line_num, line in enumerate(lines, 1):
  156. try:
  157. line = line.strip()
  158. if line.startswith("acl ") and not line.startswith("#"):
  159. parts = line.split()
  160. if len(parts) >= 3:
  161. acl_name = parts[1]
  162. acl_type = parts[2]
  163. acl_value = " ".join(parts[3:]) if len(parts) > 3 else ""
  164. acls.append(
  165. {
  166. "id": acl_index,
  167. "name": acl_name,
  168. "type": acl_type,
  169. "value": acl_value,
  170. "full_line": line,
  171. }
  172. )
  173. acl_index += 1
  174. except Exception as e:
  175. logger.warning(f"Error processing ACL at line {line_num}: {e}")
  176. continue
  177. logger.debug(f"Found {len(acls)} ACLs")
  178. return acls
  179. except Exception as e:
  180. logger.error(f"Unexpected error extracting ACLs: {e}")
  181. return []
  182. def get_delay_pools(self):
  183. if not self.is_valid:
  184. logger.error("Cannot get delay pools: invalid environment")
  185. return []
  186. if not self.config_content:
  187. logger.warning("No configuration content available")
  188. return []
  189. try:
  190. delay_pools = []
  191. lines = self.config_content.split("\n")
  192. for line_num, line in enumerate(lines, 1):
  193. try:
  194. line = line.strip()
  195. if line.startswith("delay_pools "):
  196. parts = line.split()
  197. if len(parts) >= 2:
  198. delay_pools.append(
  199. {"directive": "delay_pools", "value": parts[1]}
  200. )
  201. elif line.startswith("delay_class "):
  202. parts = line.split()
  203. if len(parts) >= 3:
  204. delay_pools.append(
  205. {
  206. "directive": "delay_class",
  207. "pool": parts[1],
  208. "class": parts[2],
  209. }
  210. )
  211. elif line.startswith("delay_parameters "):
  212. parts = line.split()
  213. if len(parts) >= 3:
  214. delay_pools.append(
  215. {
  216. "directive": "delay_parameters",
  217. "pool": parts[1],
  218. "parameters": " ".join(parts[2:]),
  219. }
  220. )
  221. elif line.startswith("delay_access "):
  222. parts = line.split()
  223. if len(parts) >= 4:
  224. delay_pools.append(
  225. {
  226. "directive": "delay_access",
  227. "pool": parts[1],
  228. "action": parts[2],
  229. "acl": " ".join(parts[3:]),
  230. }
  231. )
  232. except Exception as e:
  233. logger.warning(
  234. f"Error processing delay pool at line {line_num}: {e}"
  235. )
  236. continue
  237. logger.debug(f"Found {len(delay_pools)} delay pool configurations")
  238. return delay_pools
  239. except Exception as e:
  240. logger.error(f"Unexpected error extracting delay pools: {e}")
  241. return []
  242. def get_http_access_rules(self):
  243. if not self.is_valid:
  244. logger.error("Cannot get HTTP rules: invalid environment")
  245. return []
  246. if not self.config_content:
  247. logger.warning("No configuration content available")
  248. return []
  249. try:
  250. rules = []
  251. lines = self.config_content.split("\n")
  252. for line_num, line in enumerate(lines, 1):
  253. try:
  254. line = line.strip()
  255. if line.startswith("http_access ") and not line.startswith("#"):
  256. parts = line.split()
  257. if len(parts) >= 3:
  258. rules.append(
  259. {"action": parts[1], "acl": " ".join(parts[2:])}
  260. )
  261. except Exception as e:
  262. logger.warning(
  263. f"Error processing HTTP rule at line {line_num}: {e}"
  264. )
  265. continue
  266. logger.debug(f"Found {len(rules)} HTTP access rules")
  267. return rules
  268. except Exception as e:
  269. logger.error(f"Unexpected error extracting HTTP rules: {e}")
  270. return []
  271. def get_status(self):
  272. return {
  273. "is_valid": self.is_valid,
  274. "errors": self.errors,
  275. "config_loaded": bool(self.config_content),
  276. "config_path": self.config_path,
  277. # "backup_dir": BACKUP_DIR,
  278. "acl_files_dir": ACL_FILES_DIR,
  279. }