http_access_service.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. from loguru import logger
  2. def _find_http_lines(lines):
  3. return [
  4. i
  5. for i, line in enumerate(lines)
  6. if line.strip().startswith("http_access ") and not line.strip().startswith("#")
  7. ]
  8. def delete_http_access(rule_index: int, config_manager) -> tuple[bool, str]:
  9. try:
  10. if config_manager.is_modular:
  11. http_content = config_manager.read_modular_config("120_http_access.conf")
  12. if http_content is not None:
  13. lines = http_content.split("\n")
  14. http_lines_indices = _find_http_lines(lines)
  15. if rule_index >= len(http_lines_indices):
  16. return False, "Índice de regla inválido"
  17. # remove the line
  18. del lines[http_lines_indices[rule_index]]
  19. new_content = "\n".join(lines)
  20. if config_manager.save_modular_config(
  21. "120_http_access.conf", new_content
  22. ):
  23. return True, "Regla HTTP Access eliminada exitosamente"
  24. else:
  25. return False, "Error al eliminar la regla modular"
  26. # Fallback to main config
  27. lines = config_manager.config_content.split("\n")
  28. http_lines_indices = _find_http_lines(lines)
  29. if rule_index >= len(http_lines_indices):
  30. return False, "Índice de regla inválido"
  31. del lines[http_lines_indices[rule_index]]
  32. new_content = "\n".join(lines)
  33. config_manager.save_config(new_content)
  34. return True, "Regla HTTP Access eliminada exitosamente"
  35. except Exception:
  36. logger.exception("Error eliminando http_access")
  37. return False, "Error interno al eliminar regla http_access"
  38. def edit_http_access(
  39. rule_index: int, action: str, acls: list, description: str, config_manager
  40. ) -> tuple[bool, str]:
  41. try:
  42. acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
  43. if not acl_string:
  44. return False, "Debe especificar al menos una ACL"
  45. new_rule = f"http_access {action} {acl_string}"
  46. if config_manager.is_modular:
  47. http_content = config_manager.read_modular_config("120_http_access.conf")
  48. if http_content is not None:
  49. lines = http_content.split("\n")
  50. http_lines_indices = _find_http_lines(lines)
  51. if rule_index >= len(http_lines_indices):
  52. return False, "Índice de regla inválido"
  53. i = http_lines_indices[rule_index]
  54. if description:
  55. if i > 0 and lines[i - 1].strip().startswith("#"):
  56. lines[i - 1] = f"# {description}"
  57. else:
  58. lines.insert(i, f"# {description}")
  59. i += 1
  60. lines[i] = new_rule
  61. new_content = "\n".join(lines)
  62. if config_manager.save_modular_config(
  63. "120_http_access.conf", new_content
  64. ):
  65. return True, "Regla HTTP Access actualizada exitosamente"
  66. else:
  67. return False, "Error al guardar regla modular"
  68. # Fallback to main config
  69. lines = config_manager.config_content.split("\n")
  70. http_lines_indices = _find_http_lines(lines)
  71. if rule_index >= len(http_lines_indices):
  72. return False, "Índice de regla inválido"
  73. i = http_lines_indices[rule_index]
  74. if description:
  75. if i > 0 and lines[i - 1].strip().startswith("#"):
  76. lines[i - 1] = f"# {description}"
  77. else:
  78. lines.insert(i, f"# {description}")
  79. i += 1
  80. lines[i] = new_rule
  81. new_content = "\n".join(lines)
  82. config_manager.save_config(new_content)
  83. return True, "Regla HTTP Access actualizada exitosamente"
  84. except Exception:
  85. logger.exception("Error actualizando http_access")
  86. return False, "Error interno al actualizar regla http_access"
  87. def add_http_access(
  88. action: str, acls: list, description: str, config_manager
  89. ) -> tuple[bool, str]:
  90. try:
  91. acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
  92. if not acl_string:
  93. return False, "Debe especificar al menos una ACL"
  94. new_rule = f"http_access {action} {acl_string}"
  95. lines_to_add = []
  96. if description:
  97. lines_to_add.append(f"# {description}")
  98. lines_to_add.append(new_rule)
  99. if config_manager.is_modular:
  100. http_content = config_manager.read_modular_config("120_http_access.conf")
  101. if http_content is not None:
  102. lines = http_content.split("\n")
  103. lines.extend(lines_to_add)
  104. new_content = "\n".join(lines)
  105. if config_manager.save_modular_config(
  106. "120_http_access.conf", new_content
  107. ):
  108. return True, "Regla HTTP Access agregada exitosamente"
  109. else:
  110. return False, "Error al guardar regla modular"
  111. lines = config_manager.config_content.split("\n")
  112. lines.extend(lines_to_add)
  113. new_content = "\n".join(lines)
  114. config_manager.save_config(new_content)
  115. return True, "Regla HTTP Access agregada exitosamente"
  116. except Exception:
  117. logger.exception("Error agregando http_access")
  118. return False, "Error interno al agregar regla http_access"
  119. def add_http_deny_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
  120. """Add an ``http_access deny <acl_name>`` rule for the blocklist.
  121. The deny rule is inserted **before** the first ``http_access allow`` rule
  122. so that blocked domains are rejected before any allow rule can match.
  123. If a deny rule for this ACL already exists, it is not duplicated.
  124. Args:
  125. acl_name: Name of the blocklist ACL (must match the ACL created by
  126. :func:`add_acl_blocklist`).
  127. config_manager: A :class:`SquidConfigManager` instance.
  128. Returns:
  129. ``(success, message)`` tuple.
  130. """
  131. if not acl_name:
  132. return False, "Debe proporcionar el nombre de la ACL de blocklist"
  133. deny_rule = f"http_access deny {acl_name}"
  134. comment = f"# Deny blocklist gestionada por SquidStats ({acl_name})"
  135. try:
  136. if config_manager.is_modular:
  137. http_content = config_manager.read_modular_config("120_http_access.conf")
  138. if http_content is not None:
  139. lines = http_content.split("\n")
  140. # Check if the deny rule already exists
  141. for line in lines:
  142. if line.strip() == deny_rule:
  143. return True, f"La regla deny para '{acl_name}' ya existe"
  144. # Find the first http_access allow to insert before it
  145. insert_idx = len(lines)
  146. for i, line in enumerate(lines):
  147. stripped = line.strip()
  148. if stripped.startswith("http_access allow"):
  149. insert_idx = i
  150. break
  151. lines.insert(insert_idx, comment)
  152. lines.insert(insert_idx + 1, deny_rule)
  153. new_content = "\n".join(lines)
  154. if config_manager.save_modular_config(
  155. "120_http_access.conf", new_content
  156. ):
  157. return (
  158. True,
  159. f"Regla 'http_access deny {acl_name}' agregada exitosamente",
  160. )
  161. else:
  162. return False, "Error al guardar regla deny modular"
  163. # Fallback to main config
  164. lines = config_manager.config_content.split("\n")
  165. for line in lines:
  166. if line.strip() == deny_rule:
  167. return True, f"La regla deny para '{acl_name}' ya existe"
  168. insert_idx = len(lines)
  169. for i, line in enumerate(lines):
  170. stripped = line.strip()
  171. if stripped.startswith("http_access allow"):
  172. insert_idx = i
  173. break
  174. lines.insert(insert_idx, comment)
  175. lines.insert(insert_idx + 1, deny_rule)
  176. new_content = "\n".join(lines)
  177. config_manager.save_config(new_content)
  178. return (
  179. True,
  180. f"Regla 'http_access deny {acl_name}' agregada exitosamente",
  181. )
  182. except Exception:
  183. logger.exception("Error agregando http_access deny para blocklist")
  184. return False, "Error interno al agregar regla http_access deny"
  185. def remove_http_deny_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
  186. """Remove the ``http_access deny <acl_name>`` rule and its comment.
  187. Supports both modular (``120_http_access.conf``) and monolithic config.
  188. Args:
  189. acl_name: Name of the blocklist ACL whose deny rule should be removed.
  190. config_manager: A :class:`SquidConfigManager` instance.
  191. Returns:
  192. ``(success, message)`` tuple.
  193. """
  194. if not acl_name:
  195. return False, "Debe proporcionar el nombre de la ACL de blocklist"
  196. deny_rule = f"http_access deny {acl_name}"
  197. def _strip_deny(lines: list[str]) -> list[str]:
  198. """Return lines without the deny rule and its preceding comment."""
  199. result: list[str] = []
  200. # skip_next = False
  201. i = 0
  202. while i < len(lines):
  203. stripped = lines[i].strip()
  204. # Check if this is our deny rule
  205. if stripped == deny_rule:
  206. # Also remove the comment immediately above if it belongs to us
  207. if result and result[-1].strip().startswith(
  208. "# Deny blocklist gestionada por SquidStats"
  209. ):
  210. result.pop()
  211. i += 1
  212. continue
  213. result.append(lines[i])
  214. i += 1
  215. return result
  216. try:
  217. removed = False
  218. if config_manager.is_modular:
  219. http_content = config_manager.read_modular_config("120_http_access.conf")
  220. if http_content is not None:
  221. lines = http_content.split("\n")
  222. cleaned = _strip_deny(lines)
  223. if len(cleaned) != len(lines):
  224. removed = True
  225. new_content = "\n".join(cleaned)
  226. if not config_manager.save_modular_config(
  227. "120_http_access.conf", new_content
  228. ):
  229. return False, "Error guardando config modular de http_access"
  230. # Also clean main config
  231. lines = config_manager.config_content.split("\n")
  232. cleaned = _strip_deny(lines)
  233. if len(cleaned) != len(lines):
  234. removed = True
  235. new_content = "\n".join(cleaned)
  236. config_manager.save_config(new_content)
  237. if removed:
  238. return (
  239. True,
  240. f"Regla 'http_access deny {acl_name}' eliminada exitosamente",
  241. )
  242. return True, f"No se encontró regla deny para '{acl_name}' (ya eliminada)"
  243. except Exception:
  244. logger.exception("Error eliminando http_access deny para blocklist")
  245. return False, "Error interno al eliminar regla http_access deny"
  246. def move_http_access(
  247. rule_index: int, direction: str, config_manager
  248. ) -> tuple[bool, str]:
  249. try:
  250. if config_manager.is_modular:
  251. http_content = config_manager.read_modular_config("120_http_access.conf")
  252. if http_content is not None:
  253. lines = http_content.split("\n")
  254. http_lines_indices = _find_http_lines(lines)
  255. if rule_index >= len(http_lines_indices):
  256. return False, "Índice de regla inválido"
  257. current = http_lines_indices[rule_index]
  258. if direction == "up" and rule_index > 0:
  259. target = http_lines_indices[rule_index - 1]
  260. lines[current], lines[target] = lines[target], lines[current]
  261. elif direction == "down" and rule_index < len(http_lines_indices) - 1:
  262. target = http_lines_indices[rule_index + 1]
  263. lines[current], lines[target] = lines[target], lines[current]
  264. new_content = "\n".join(lines)
  265. config_manager.save_modular_config("120_http_access.conf", new_content)
  266. return True, "Regla movida exitosamente"
  267. lines = config_manager.config_content.split("\n")
  268. http_lines_indices = _find_http_lines(lines)
  269. if rule_index >= len(http_lines_indices):
  270. return False, "Índice de regla inválido"
  271. current = http_lines_indices[rule_index]
  272. if direction == "up" and rule_index > 0:
  273. target = http_lines_indices[rule_index - 1]
  274. lines[current], lines[target] = lines[target], lines[current]
  275. elif direction == "down" and rule_index < len(http_lines_indices) - 1:
  276. target = http_lines_indices[rule_index + 1]
  277. lines[current], lines[target] = lines[target], lines[current]
  278. new_content = "\n".join(lines)
  279. config_manager.save_config(new_content)
  280. return True, "Regla movida exitosamente"
  281. except Exception:
  282. logger.exception("Error moviendo http_access")
  283. return False, "Error interno al mover regla http_access"