Просмотр исходного кода

Merge pull request #54 from kaelthasmanu/EditingConfigFile

🔧 New functionality: Squid configuration splitting service and modal UI for ACLs.
Kaelthas 10 месяцев назад
Родитель
Сommit
727c6b09f1

+ 716 - 42
routes/admin_routes.py

@@ -15,6 +15,7 @@ from sqlalchemy import MetaData, Table, func, inspect, select, text
 from config import Config, logger
 from database.database import get_engine, get_session
 from services.auth_service import AuthService, admin_required, api_auth_required
+from services.squid_config_splitter import SquidConfigSplitter
 from utils.admin import SquidConfigManager
 
 admin_bp = Blueprint("admin", __name__)
@@ -157,67 +158,169 @@ def save_env():
 @admin_bp.route("/acls")
 @admin_required
 def manage_acls():
+    """Display ACLs management interface with categorization and metadata."""
     acls = config_manager.get_acls()
-    return render_template("admin/acls.html", acls=acls)
+    return render_template("admin/acls_new.html", acls=acls)
 
 
 @admin_bp.route("/acls/add", methods=["POST"])
 @admin_required
 def add_acl():
-    name = request.form["name"]
-    acl_type = request.form["type"]
-    value = request.form["value"]
-    new_acl = f"acl {name} {acl_type} {value}"
-
-    # Add the new ACL at the end of the ACLs section
+    """Add a new ACL with options, multiple values, and comment."""
+    name = request.form.get("name")
+    acl_type = request.form.get("type")
+    values = request.form.getlist("values[]")
+    options = request.form.getlist("options[]")
+    comment = request.form.get("comment", "").strip()
+    
+    if not name or not acl_type or not values:
+        flash("Debe proporcionar nombre, tipo y al menos un valor para la ACL", "error")
+        return redirect(url_for("admin.manage_acls"))
+    
+    # Build ACL line: acl name [options] type values...
+    acl_parts = ["acl", name]
+    if options:
+        acl_parts.extend(options)
+    acl_parts.append(acl_type)
+    acl_parts.extend(values)
+    new_acl = " ".join(acl_parts)
+    
+    # Check if using modular configuration
+    if config_manager.is_modular:
+        acl_content = config_manager.read_modular_config("100_acls.conf")
+        if acl_content is not None:
+            lines = acl_content.split("\n")
+            
+            # Add comment if provided
+            if comment:
+                lines.append(f"# {comment}")
+            
+            # Add the new ACL
+            lines.append(new_acl)
+            
+            new_content = "\n".join(lines)
+            if config_manager.save_modular_config("100_acls.conf", new_content):
+                flash(f"ACL '{name}' agregada exitosamente", "success")
+            else:
+                flash("Error al guardar la ACL", "error")
+            return redirect(url_for("admin.manage_acls"))
+    
+    # Fallback to main config
     lines = config_manager.config_content.split("\n")
     acl_section_end = -1
     for i, line in enumerate(lines):
         if line.strip().startswith("acl "):
             acl_section_end = i
+    
     if acl_section_end != -1:
-        lines.insert(acl_section_end + 1, new_acl)
+        if comment:
+            lines.insert(acl_section_end + 1, f"# {comment}")
+            lines.insert(acl_section_end + 2, new_acl)
+        else:
+            lines.insert(acl_section_end + 1, new_acl)
     else:
+        if comment:
+            lines.append(f"# {comment}")
         lines.append(new_acl)
 
     new_content = "\n".join(lines)
     config_manager.save_config(new_content)
-    flash("ACL agregada exitosamente", "success")
+    flash(f"ACL '{name}' agregada exitosamente", "success")
     return redirect(url_for("admin.manage_acls"))
 
 
 @admin_bp.route("/acls/edit", methods=["POST"])
 @admin_required
 def edit_acl():
-    acl_id = request.form["id"]
-    new_name = request.form["name"]
-    new_type = request.form["type"]
-    new_value = request.form["value"]
-
+    """Edit an existing ACL using line number for precise targeting."""
+    acl_id = request.form.get("id")
+    new_name = request.form.get("name")
+    acl_type = request.form.get("type")
+    values = request.form.getlist("values[]")
+    options = request.form.getlist("options[]")
+    comment = request.form.get("comment", "").strip()
+    
+    if not acl_id or not new_name or not acl_type or not values:
+        flash("Datos incompletos para editar la ACL", "error")
+        return redirect(url_for("admin.manage_acls"))
+    
     try:
         acl_index = int(acl_id)
         acls = config_manager.get_acls()
 
         if 0 <= acl_index < len(acls):
-            new_acl_line = f"acl {new_name} {new_type} {new_value}"
-
-            # Replace the line in the content
+            target_acl = acls[acl_index]
+            # line_number from parser is 1-based, convert to 0-based index
+            target_line = target_acl['line_number'] - 1
+            
+            # Build new ACL line
+            acl_parts = ["acl", new_name]
+            if options:
+                acl_parts.extend(options)
+            acl_parts.append(acl_type)
+            acl_parts.extend(values)
+            new_acl_line = " ".join(acl_parts)
+
+            # Check if using modular configuration
+            if config_manager.is_modular:
+                acl_content = config_manager.read_modular_config("100_acls.conf")
+                if acl_content is not None:
+                    lines = acl_content.split("\n")
+                    
+                    # Replace the ACL line (line_number is 1-based, list index is 0-based)
+                    if 0 <= target_line < len(lines):
+                        # Check if there's a comment before this ACL
+                        has_comment = target_line > 0 and lines[target_line - 1].strip().startswith("#")
+                        
+                        # Replace the ACL line
+                        lines[target_line] = new_acl_line
+                        
+                        # Handle comment
+                        if has_comment:
+                            if comment:
+                                # Update existing comment
+                                lines[target_line - 1] = f"# {comment}"
+                            else:
+                                # Remove existing comment
+                                lines.pop(target_line - 1)
+                        else:
+                            if comment:
+                                # Insert new comment before the ACL
+                                lines.insert(target_line, f"# {comment}")
+                        
+                        new_content = "\n".join(lines)
+                        if config_manager.save_modular_config("100_acls.conf", new_content):
+                            flash(f"ACL '{new_name}' actualizada exitosamente", "success")
+                        else:
+                            flash("Error al guardar la ACL", "error")
+                    else:
+                        flash("Línea de ACL no encontrada", "error")
+                    return redirect(url_for("admin.manage_acls"))
+            
+            # Fallback to main config
             lines = config_manager.config_content.split("\n")
-            acl_count = 0
-            for i, line in enumerate(lines):
-                if line.strip().startswith("acl ") and not line.strip().startswith("#"):
-                    if acl_count == acl_index:
-                        lines[i] = new_acl_line
-                        break
-                    acl_count += 1
-
-            new_content = "\n".join(lines)
-            config_manager.save_config(new_content)
-            flash("ACL actualizada exitosamente", "success")
+            if 0 <= target_line < len(lines):
+                lines[target_line] = new_acl_line
+                
+                # Handle comment
+                if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
+                    if comment:
+                        lines[target_line - 1] = f"# {comment}"
+                    else:
+                        lines.pop(target_line - 1)
+                else:
+                    if comment:
+                        lines.insert(target_line, f"# {comment}")
+                
+                new_content = "\n".join(lines)
+                config_manager.save_config(new_content)
+                flash(f"ACL '{new_name}' actualizada exitosamente", "success")
+            else:
+                flash("Línea de ACL no encontrada", "error")
         else:
             flash("ACL no encontrada", "error")
-    except (ValueError, IndexError):
-        flash("Error al actualizar la ACL", "error")
+    except (ValueError, IndexError) as e:
+        flash(f"Error al actualizar la ACL: {str(e)}", "error")
 
     return redirect(url_for("admin.manage_acls"))
 
@@ -225,7 +328,8 @@ def edit_acl():
 @admin_bp.route("/acls/delete", methods=["POST"])
 @admin_required
 def delete_acl():
-    acl_id = request.form["id"]
+    """Delete an ACL using its ID (index) and line number."""
+    acl_id = request.form.get("id")
 
     try:
         acl_index = int(acl_id)
@@ -233,19 +337,51 @@ def delete_acl():
 
         if 0 <= acl_index < len(acls):
             acl_to_delete = acls[acl_index]
-
-            # Remove the line from the content
+            # line_number from parser is 1-based, convert to 0-based index
+            target_line = acl_to_delete['line_number'] - 1
+
+            # Check if using modular configuration
+            if config_manager.is_modular:
+                acl_content = config_manager.read_modular_config("100_acls.conf")
+                if acl_content is not None:
+                    lines = acl_content.split("\n")
+                    
+                    # Check if there's a comment before this ACL (line_number is 1-based, we need 0-based)
+                    comment_to_remove = None
+                    if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
+                        comment_to_remove = target_line - 1
+                    
+                    # Remove lines (comment + ACL or just ACL)
+                    new_lines = []
+                    for i, line in enumerate(lines):
+                        if i == target_line:
+                            continue  # Skip the ACL line
+                        if comment_to_remove is not None and i == comment_to_remove:
+                            continue  # Skip the comment line
+                        new_lines.append(line)
+
+                    new_content = "\n".join(new_lines)
+                    if config_manager.save_modular_config("100_acls.conf", new_content):
+                        flash(f"ACL '{acl_to_delete['name']}' eliminada exitosamente", "success")
+                    else:
+                        flash("Error al eliminar la ACL", "error")
+                    return redirect(url_for("admin.manage_acls"))
+            
+            # Fallback to main config
             lines = config_manager.config_content.split("\n")
+            
+            # Check if there's a comment before this ACL (convert to 0-based index)
+            comment_to_remove = None
+            if target_line > 0 and lines[target_line - 1].strip().startswith("#"):
+                comment_to_remove = target_line - 1
+            
+            # Remove lines (comment + ACL or just ACL)
             new_lines = []
-            acl_count = 0
-
-            for line in lines:
-                if line.strip().startswith("acl ") and not line.strip().startswith("#"):
-                    if acl_count == acl_index:
-                        # Skip this line (delete it)
-                        acl_count += 1
-                        continue
-                    acl_count += 1
+            for i, line in enumerate(lines):
+                if i == target_line:
+                    continue  # Skip the ACL line
+                if comment_to_remove is not None and i == comment_to_remove:
+                    continue  # Skip the comment line
                 new_lines.append(line)
 
             new_content = "\n".join(new_lines)
@@ -273,6 +409,455 @@ def manage_http_access():
     return render_template("admin/http_access.html", rules=rules)
 
 
+@admin_bp.route("/http-access/delete", methods=["POST"])
+@admin_required
+def delete_http_access():
+    index = request.form.get("index")
+    
+    try:
+        rule_index = int(index)
+        
+        # Check if using modular configuration
+        if config_manager.is_modular:
+            http_content = config_manager.read_modular_config("120_http_access.conf")
+            if http_content is not None:
+                lines = http_content.split("\n")
+                new_lines = []
+                http_count = 0
+                
+                for line in lines:
+                    if line.strip().startswith("http_access ") and not line.strip().startswith("#"):
+                        if http_count == rule_index:
+                            # Skip this line (delete it)
+                            http_count += 1
+                            continue
+                        http_count += 1
+                    new_lines.append(line)
+                
+                new_content = "\n".join(new_lines)
+                if config_manager.save_modular_config("120_http_access.conf", new_content):
+                    flash("Regla HTTP Access eliminada exitosamente", "success")
+                else:
+                    flash("Error al eliminar la regla", "error")
+                return redirect(url_for("admin.manage_http_access"))
+        
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        new_lines = []
+        http_count = 0
+        
+        for line in lines:
+            if line.strip().startswith("http_access ") and not line.strip().startswith("#"):
+                if http_count == rule_index:
+                    http_count += 1
+                    continue
+                http_count += 1
+            new_lines.append(line)
+        
+        new_content = "\n".join(new_lines)
+        config_manager.save_config(new_content)
+        flash("Regla HTTP Access eliminada exitosamente", "success")
+        
+    except (ValueError, IndexError) as e:
+        flash(f"Error al eliminar la regla: {str(e)}", "error")
+    
+    return redirect(url_for("admin.manage_http_access"))
+
+
+@admin_bp.route("/http-access/edit", methods=["POST"])
+@admin_required
+def edit_http_access():
+    """Edit an http_access rule with support for multiple ACLs and description"""
+    index = request.form.get("index")
+    action = request.form.get("action")
+    acls = request.form.getlist("acls[]")
+    description = request.form.get("description", "").strip()
+    
+    try:
+        rule_index = int(index)
+        acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
+        
+        if not acl_string:
+            flash("Debe especificar al menos una ACL", "error")
+            return redirect(url_for("admin.manage_http_access"))
+        
+        new_rule = f"http_access {action} {acl_string}"
+        
+        # Check if using modular configuration
+        if config_manager.is_modular:
+            http_content = config_manager.read_modular_config("120_http_access.conf")
+            if http_content is not None:
+                lines = http_content.split("\n")
+                http_count = 0
+                
+                for i, line in enumerate(lines):
+                    if line.strip().startswith("http_access ") and not line.strip().startswith("#"):
+                        if http_count == rule_index:
+                            # Replace the rule, optionally with a comment above
+                            if description:
+                                # Check if there's already a comment above this line
+                                if i > 0 and lines[i-1].strip().startswith("#"):
+                                    lines[i-1] = f"# {description}"
+                                else:
+                                    lines.insert(i, f"# {description}")
+                                    i += 1
+                            lines[i] = new_rule
+                            break
+                        http_count += 1
+                
+                new_content = "\n".join(lines)
+                if config_manager.save_modular_config("120_http_access.conf", new_content):
+                    flash("Regla HTTP Access actualizada exitosamente", "success")
+                else:
+                    flash("Error al actualizar la regla", "error")
+                return redirect(url_for("admin.manage_http_access"))
+        
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        http_count = 0
+        
+        for i, line in enumerate(lines):
+            if line.strip().startswith("http_access ") and not line.strip().startswith("#"):
+                if http_count == rule_index:
+                    if description:
+                        if i > 0 and lines[i-1].strip().startswith("#"):
+                            lines[i-1] = f"# {description}"
+                        else:
+                            lines.insert(i, f"# {description}")
+                            i += 1
+                    lines[i] = new_rule
+                    break
+                http_count += 1
+        
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        flash("Regla HTTP Access actualizada exitosamente", "success")
+        
+    except (ValueError, IndexError) as e:
+        flash(f"Error al actualizar la regla: {str(e)}", "error")
+    
+    return redirect(url_for("admin.manage_http_access"))
+
+
+@admin_bp.route("/http-access/add", methods=["POST"])
+@admin_required
+def add_http_access():
+    """Add a new http_access rule"""
+    action = request.form.get("action")
+    acls = request.form.getlist("acls[]")
+    description = request.form.get("description", "").strip()
+    
+    try:
+        acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
+        
+        if not acl_string:
+            flash("Debe especificar al menos una ACL", "error")
+            return redirect(url_for("admin.manage_http_access"))
+        
+        new_rule = f"http_access {action} {acl_string}"
+        lines_to_add = []
+        
+        if description:
+            lines_to_add.append(f"# {description}")
+        lines_to_add.append(new_rule)
+        
+        # Check if using modular configuration
+        if config_manager.is_modular:
+            http_content = config_manager.read_modular_config("120_http_access.conf")
+            if http_content is not None:
+                lines = http_content.split("\n")
+                # Add at the end (before final "deny all" if it exists)
+                lines.extend(lines_to_add)
+                
+                new_content = "\n".join(lines)
+                if config_manager.save_modular_config("120_http_access.conf", new_content):
+                    flash("Regla HTTP Access agregada exitosamente", "success")
+                else:
+                    flash("Error al agregar la regla", "error")
+                return redirect(url_for("admin.manage_http_access"))
+        
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        lines.extend(lines_to_add)
+        
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        flash("Regla HTTP Access agregada exitosamente", "success")
+        
+    except Exception as e:
+        flash(f"Error al agregar la regla: {str(e)}", "error")
+    
+    return redirect(url_for("admin.manage_http_access"))
+
+
+@admin_bp.route("/http-access/move", methods=["POST"])
+@admin_required
+def move_http_access():
+    """Move an http_access rule up or down"""
+    index = request.form.get("index")
+    direction = request.form.get("direction")  # 'up' or 'down'
+    
+    try:
+        rule_index = int(index)
+        
+        # Check if using modular configuration
+        if config_manager.is_modular:
+            http_content = config_manager.read_modular_config("120_http_access.conf")
+            if http_content is not None:
+                lines = http_content.split("\n")
+                http_lines_indices = []
+                
+                # Find all http_access lines
+                for i, line in enumerate(lines):
+                    if line.strip().startswith("http_access ") and not line.strip().startswith("#"):
+                        http_lines_indices.append(i)
+                
+                if rule_index >= len(http_lines_indices):
+                    flash("Índice de regla inválido", "error")
+                    return redirect(url_for("admin.manage_http_access"))
+                
+                current_line_index = http_lines_indices[rule_index]
+                
+                if direction == 'up' and rule_index > 0:
+                    target_line_index = http_lines_indices[rule_index - 1]
+                    # Swap lines
+                    lines[current_line_index], lines[target_line_index] = lines[target_line_index], lines[current_line_index]
+                elif direction == 'down' and rule_index < len(http_lines_indices) - 1:
+                    target_line_index = http_lines_indices[rule_index + 1]
+                    # Swap lines
+                    lines[current_line_index], lines[target_line_index] = lines[target_line_index], lines[current_line_index]
+                
+                new_content = "\n".join(lines)
+                if config_manager.save_modular_config("120_http_access.conf", new_content):
+                    flash(f"Regla movida {direction == 'up' and 'arriba' or 'abajo'} exitosamente", "success")
+                else:
+                    flash("Error al mover la regla", "error")
+                return redirect(url_for("admin.manage_http_access"))
+        
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        http_lines_indices = []
+        
+        for i, line in enumerate(lines):
+            if line.strip().startswith("http_access ") and not line.strip().startswith("#"):
+                http_lines_indices.append(i)
+        
+        if rule_index >= len(http_lines_indices):
+            flash("Índice de regla inválido", "error")
+            return redirect(url_for("admin.manage_http_access"))
+        
+        current_line_index = http_lines_indices[rule_index]
+        
+        if direction == 'up' and rule_index > 0:
+            target_line_index = http_lines_indices[rule_index - 1]
+            lines[current_line_index], lines[target_line_index] = lines[target_line_index], lines[current_line_index]
+        elif direction == 'down' and rule_index < len(http_lines_indices) - 1:
+            target_line_index = http_lines_indices[rule_index + 1]
+            lines[current_line_index], lines[target_line_index] = lines[target_line_index], lines[current_line_index]
+        
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        flash(f"Regla movida {direction == 'up' and 'arriba' or 'abajo'} exitosamente", "success")
+        
+    except (ValueError, IndexError) as e:
+        flash(f"Error al mover la regla: {str(e)}", "error")
+    
+    return redirect(url_for("admin.manage_http_access"))
+
+
+@admin_bp.route("/delay-pools/delete", methods=["POST"])
+@admin_required
+def delete_delay_pool():
+    """Delete all directives related to a specific delay pool"""
+    pool_number = request.form.get("pool_number")
+    
+    try:
+        # Check if using modular configuration
+        if config_manager.is_modular:
+            delay_content = config_manager.read_modular_config("110_delay_pools.conf")
+            if delay_content is not None:
+                lines = delay_content.split("\n")
+                new_lines = []
+                
+                # Remove all lines related to this pool number
+                for line in lines:
+                    stripped = line.strip()
+                    # Skip delay_class, delay_parameters, and delay_access for this pool
+                    if (stripped.startswith(f"delay_class {pool_number} ") or
+                        stripped.startswith(f"delay_parameters {pool_number} ") or
+                        stripped.startswith(f"delay_access {pool_number} ")):
+                        continue
+                    new_lines.append(line)
+                
+                new_content = "\n".join(new_lines)
+                if config_manager.save_modular_config("110_delay_pools.conf", new_content):
+                    flash(f"Delay Pool #{pool_number} eliminado exitosamente", "success")
+                else:
+                    flash("Error al eliminar el delay pool", "error")
+                return redirect(url_for("admin.manage_delay_pools"))
+        
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        new_lines = []
+        
+        for line in lines:
+            stripped = line.strip()
+            if (stripped.startswith(f"delay_class {pool_number} ") or
+                stripped.startswith(f"delay_parameters {pool_number} ") or
+                stripped.startswith(f"delay_access {pool_number} ")):
+                continue
+            new_lines.append(line)
+        
+        new_content = "\n".join(new_lines)
+        config_manager.save_config(new_content)
+        flash(f"Delay Pool #{pool_number} eliminado exitosamente", "success")
+        
+    except Exception as e:
+        flash(f"Error al eliminar el delay pool: {str(e)}", "error")
+    
+    return redirect(url_for("admin.manage_delay_pools"))
+
+
+@admin_bp.route("/delay-pools/edit", methods=["POST"])
+@admin_required
+def edit_delay_pool():
+    """Edit all directives related to a specific delay pool"""
+    pool_number = request.form.get("pool_number")
+    pool_class = request.form.get("pool_class")
+    parameters = request.form.get("parameters")
+    access_actions = request.form.getlist("access_action[]")
+    access_acls = request.form.getlist("access_acl[]")
+    
+    try:
+        # Build new directives
+        new_directives = []
+        new_directives.append(f"delay_class {pool_number} {pool_class}")
+        new_directives.append(f"delay_parameters {pool_number} {parameters}")
+        
+        # Add access rules
+        for action, acl in zip(access_actions, access_acls):
+            if acl.strip():
+                new_directives.append(f"delay_access {pool_number} {action} {acl}")
+        
+        # Check if using modular configuration
+        if config_manager.is_modular:
+            delay_content = config_manager.read_modular_config("110_delay_pools.conf")
+            if delay_content is not None:
+                lines = delay_content.split("\n")
+                new_lines = []
+                pool_found = False
+                insert_index = -1
+                
+                # Remove old directives and find insertion point
+                for i, line in enumerate(lines):
+                    stripped = line.strip()
+                    if (stripped.startswith(f"delay_class {pool_number} ") or
+                        stripped.startswith(f"delay_parameters {pool_number} ") or
+                        stripped.startswith(f"delay_access {pool_number} ")):
+                        if not pool_found:
+                            insert_index = len(new_lines)
+                            pool_found = True
+                        continue
+                    new_lines.append(line)
+                
+                # Insert new directives at the same location
+                if insert_index >= 0:
+                    for directive in reversed(new_directives):
+                        new_lines.insert(insert_index, directive)
+                else:
+                    # If not found, append at the end
+                    new_lines.extend(new_directives)
+                
+                new_content = "\n".join(new_lines)
+                if config_manager.save_modular_config("110_delay_pools.conf", new_content):
+                    flash(f"Delay Pool #{pool_number} actualizado exitosamente", "success")
+                else:
+                    flash("Error al actualizar el delay pool", "error")
+                return redirect(url_for("admin.manage_delay_pools"))
+        
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        new_lines = []
+        pool_found = False
+        insert_index = -1
+        
+        for i, line in enumerate(lines):
+            stripped = line.strip()
+            if (stripped.startswith(f"delay_class {pool_number} ") or
+                stripped.startswith(f"delay_parameters {pool_number} ") or
+                stripped.startswith(f"delay_access {pool_number} ")):
+                if not pool_found:
+                    insert_index = len(new_lines)
+                    pool_found = True
+                continue
+            new_lines.append(line)
+        
+        if insert_index >= 0:
+            for directive in reversed(new_directives):
+                new_lines.insert(insert_index, directive)
+        else:
+            new_lines.extend(new_directives)
+        
+        new_content = "\n".join(new_lines)
+        config_manager.save_config(new_content)
+        flash(f"Delay Pool #{pool_number} actualizado exitosamente", "success")
+        
+    except Exception as e:
+        flash(f"Error al actualizar el delay pool: {str(e)}", "error")
+    
+    return redirect(url_for("admin.manage_delay_pools"))
+
+
+@admin_bp.route("/delay-pools/add", methods=["POST"])
+@admin_required
+def add_delay_pool():
+    """Add a new delay pool with all its directives"""
+    pool_number = request.form.get("pool_number")
+    pool_class = request.form.get("pool_class")
+    parameters = request.form.get("parameters")
+    access_actions = request.form.getlist("access_action[]")
+    access_acls = request.form.getlist("access_acl[]")
+    
+    try:
+        # Build new directives
+        new_directives = []
+        new_directives.append(f"delay_class {pool_number} {pool_class}")
+        new_directives.append(f"delay_parameters {pool_number} {parameters}")
+        
+        # Add access rules
+        for action, acl in zip(access_actions, access_acls):
+            if acl.strip():
+                new_directives.append(f"delay_access {pool_number} {action} {acl}")
+        
+        # Check if using modular configuration
+        if config_manager.is_modular:
+            delay_content = config_manager.read_modular_config("110_delay_pools.conf")
+            if delay_content is not None:
+                # Append new directives at the end
+                lines = delay_content.split("\n")
+                lines.extend(new_directives)
+                
+                new_content = "\n".join(lines)
+                if config_manager.save_modular_config("110_delay_pools.conf", new_content):
+                    flash(f"Delay Pool #{pool_number} creado exitosamente", "success")
+                else:
+                    flash("Error al crear el delay pool", "error")
+                return redirect(url_for("admin.manage_delay_pools"))
+        
+        # Fallback to main config
+        lines = config_manager.config_content.split("\n")
+        lines.extend(new_directives)
+        
+        new_content = "\n".join(lines)
+        config_manager.save_config(new_content)
+        flash(f"Delay Pool #{pool_number} creado exitosamente", "success")
+        
+    except Exception as e:
+        flash(f"Error al crear el delay pool: {str(e)}", "error")
+    
+    return redirect(url_for("admin.manage_delay_pools"))
+
+
 @admin_bp.route("/view-logs")
 @admin_required
 def view_logs():
@@ -540,3 +1125,92 @@ def delete_table_data():
         if show_details:
             resp["details"] = str(e)
         return jsonify(resp), 500
+
+
+@admin_bp.route("/config/split")
+@admin_required
+def split_config_view():
+    """Vista para dividir el archivo squid.conf en archivos modulares."""
+    try:
+        splitter = SquidConfigSplitter()
+        split_info = splitter.get_split_info()
+        output_exists = splitter.check_output_dir_exists()
+        files_count = splitter.count_files_in_output_dir()
+
+        return render_template(
+            "admin/split_config.html",
+            split_info=split_info,
+            output_dir=splitter.output_dir,
+            input_file=splitter.input_file,
+            output_exists=output_exists,
+            files_count=files_count,
+        )
+    except Exception as e:
+        logger.exception("Error al cargar la vista de división de configuración")
+        flash(f"Error al cargar la vista: {str(e)}", "error")
+        return redirect(url_for("admin.admin_dashboard"))
+
+
+@admin_bp.route("/api/split-config", methods=["POST"])
+@api_auth_required
+def split_config():
+    """API endpoint para dividir el archivo squid.conf en archivos modulares."""
+    try:
+        data = request.get_json() or {}
+        strict = data.get("strict", False)
+
+        splitter = SquidConfigSplitter(strict=strict)
+
+        if not os.path.exists(splitter.input_file):
+            return jsonify({
+                "status": "error",
+                "message": f"Archivo squid.conf no encontrado en: {splitter.input_file}"
+            }), 404
+
+        results = splitter.split_config()
+
+        return jsonify({
+            "status": "success",
+            "message": f"Configuración dividida exitosamente en {len(results)} archivos",
+            "data": {
+                "output_dir": splitter.output_dir,
+                "files": results,
+                "total_files": len(results)
+            }
+        })
+
+    except FileNotFoundError as e:
+        logger.error(f"Archivo no encontrado: {e}")
+        return jsonify({
+            "status": "error",
+            "message": str(e)
+        }), 404
+
+    except PermissionError as e:
+        logger.error(f"Error de permisos: {e}")
+        return jsonify({
+            "status": "error",
+            "message": "No se tienen permisos suficientes para crear los archivos"
+        }), 403
+
+    except RuntimeError as e:
+        logger.error(f"Error de validación: {e}")
+        return jsonify({
+            "status": "error",
+            "message": str(e)
+        }), 400
+
+    except Exception as e:
+        logger.exception("Error al dividir el archivo de configuración")
+        try:
+            show_details = bool(current_app.debug)
+        except RuntimeError:
+            show_details = False
+
+        resp = {
+            "status": "error",
+            "message": "Error interno al dividir la configuración"
+        }
+        if show_details:
+            resp["details"] = str(e)
+        return jsonify(resp), 500

+ 263 - 0
services/squid_config_splitter.py

@@ -0,0 +1,263 @@
+import os
+import re
+import shutil
+from dataclasses import dataclass
+from datetime import datetime
+
+from config import logger
+
+
+@dataclass(frozen=True)
+class Rule:
+    filename: str
+    patterns: list[re.Pattern]
+
+
+class SquidConfigSplitter:
+    def __init__(self, input_file: str = None, output_dir: str = None, strict: bool = False):
+        self.input_file = input_file or "/etc/squid/squid.conf"
+        self.output_dir = output_dir or "/etc/squid/squid.d"
+        self.strict = strict
+        self.unknown_file = "999_unknown.conf"
+        self.rules = self._compile_rules()
+
+    def _compile_rules(self) -> list[Rule]:
+        """
+        Compile the directive classification rules.
+        The order matters and is intentional.
+        """
+        return [
+            Rule("00_ports.conf", [
+                re.compile(r"^http_port\b"),
+            ]),
+            Rule("10_misc.conf", [
+                re.compile(r"^max_filedesc\b"),
+                re.compile(r"^pconn_lifetime\b"),
+                re.compile(r"^visible_hostname\b"),
+                re.compile(r"^pid_filename\b"),
+                re.compile(r"^client_db\b"),
+                re.compile(r"^cache_mgr\b"),
+            ]),
+            Rule("20_security.conf", [
+                re.compile(r"^via\b"),
+                re.compile(r"^forwarded_for\b"),
+                re.compile(r"^request_header_access\b"),
+                re.compile(r"^quick_abort"),
+                re.compile(r"^httpd_suppress_version_string\b"),
+                re.compile(r"^reload_into_ims\b"),
+                re.compile(r"^read_ahead_gap\b"),
+                re.compile(r"^negative_ttl\b"),
+                re.compile(r"^positive_dns_ttl\b"),
+                re.compile(r"^negative_dns_ttl\b"),
+                re.compile(r"^range_offset_limit\b"),
+                re.compile(r"^pinger_enable\b"),
+                re.compile(r"^server_persistent_connections\b"),
+                re.compile(r"^client_persistent_connections\b"),
+                re.compile(r"^check_hostnames\b"),
+                re.compile(r"^half_closed_clients\b"),
+            ]),
+            Rule("60_logs.conf", [
+                re.compile(r"^access_log\b"),
+                re.compile(r"^cache_log\b"),
+                re.compile(r"^cache_store_log\b"),
+                re.compile(r"^cache_access_log\b"),
+                re.compile(r"^icap_log\b"),
+                re.compile(r"^logformat\b"),
+                re.compile(r"^strip_query_terms\b"),
+                re.compile(r"^coredump_dir\b"),
+            ]),
+            Rule("30_cache.conf", [
+                re.compile(r"^cache_(?!log\b|mgr\b|store_log\b|access_log\b)"),
+                re.compile(r"^maximum_object_"),
+                re.compile(r"^minimum_object_"),
+                re.compile(r"^memory_"),
+                re.compile(r"^ipcache_"),
+                re.compile(r"^fqdncache_"),
+            ]),
+            Rule("40_refresh_patterns.conf", [
+                re.compile(r"^refresh_pattern\b"),
+            ]),
+            Rule("50_ssl_bump.conf", [
+                re.compile(r"^ssl_"),
+                re.compile(r"^sslcrtd_"),
+                re.compile(r"SslBump"),
+                re.compile(r"sslproxy_"),
+            ]),
+            Rule("70_icap.conf", [
+                re.compile(r"^icap_(?!log\b)"),
+                re.compile(r"^adaptation_"),
+            ]),
+            Rule("80_dns.conf", [
+                re.compile(r"^dns_"),
+                re.compile(r"^hosts_file\b"),
+                re.compile(r"^connect_timeout\b"),
+                re.compile(r"^read_timeout\b"),
+            ]),
+            Rule("90_auth.conf", [
+                re.compile(r"^auth_param\b"),
+                re.compile(r"^authenticate_"),
+            ]),
+            Rule("100_acls.conf", [
+                re.compile(r"^acl\b"),
+            ]),
+            Rule("110_delay_pools.conf", [
+                re.compile(r"^delay_"),
+            ]),
+            Rule("115_cache_control.conf", [
+                re.compile(r"^no_cache\b"),
+                re.compile(r"^icp_access\b"),
+                re.compile(r"^cache_peer"),
+                re.compile(r"^never_direct\b"),
+            ]),
+            Rule("120_http_access.conf", [
+                re.compile(r"^http_access\b"),
+                re.compile(r"^deny_info\b"),
+            ]),
+        ]
+
+    def _classify_line(self, line: str) -> str:
+        matches = [
+            rule.filename
+            for rule in self.rules
+            for pattern in rule.patterns
+            if pattern.search(line)
+        ]
+
+        if len(matches) > 1:
+            raise ValueError(
+                f"Ambiguous rule match for line:\n{line}\nMatches: {matches}"
+            )
+
+        if matches:
+            return matches[0]
+
+        return self.unknown_file
+
+    def split_config(self) -> dict[str, int]:
+        # Verify that the input file exists
+        if not os.path.exists(self.input_file):
+            raise FileNotFoundError(f"File not found: {self.input_file}")
+
+        # Create backup of squid.conf before splitting
+        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+        backup_file = f"{self.input_file}.bak{timestamp}"
+        try:
+            shutil.copy2(self.input_file, backup_file)
+            logger.info(f"Backup created: {backup_file}")
+        except Exception as e:
+            logger.error(f"Failed to create backup: {e}")
+            raise RuntimeError(f"Failed to create backup: {e}")
+
+        # Create the output directory
+        try:
+            os.makedirs(self.output_dir, exist_ok=True)
+        except PermissionError as e:
+            raise PermissionError(
+                f"No permissions to create directory: {self.output_dir}"
+            ) from e
+
+        buffers: dict[str, list[str]] = {}
+        pending_comments: list[str] = []
+        results: dict[str, int] = {}
+        results["_backup_file"] = backup_file
+
+        try:
+            with open(self.input_file, encoding="utf-8") as f:
+                for lineno, raw_line in enumerate(f, start=1):
+                    line = raw_line.rstrip("\n")
+                    stripped = line.strip()
+
+                    # Comments and empty lines
+                    if not stripped or stripped.startswith("#"):
+                        pending_comments.append(raw_line)
+                        continue
+
+                    try:
+                        target = self._classify_line(stripped)
+                    except ValueError as e:
+                        logger.error(f"Error in line {lineno}: {e}")
+                        raise RuntimeError(f"Line {lineno}: {e}")
+
+                    if target == self.unknown_file and self.strict:
+                        raise RuntimeError(
+                            f"Unknown directive at line {lineno}: {stripped}"
+                        )
+
+                    buffers.setdefault(target, [])
+                    buffers[target].extend(pending_comments)
+                    pending_comments.clear()
+                    buffers[target].append(raw_line)
+
+            # Orphaned final comments
+            if pending_comments:
+                buffers.setdefault(self.unknown_file, []).extend(pending_comments)
+
+            # Final writing
+            for filename, content in sorted(buffers.items()):
+                path = os.path.join(self.output_dir, filename)
+                with open(path, "w", encoding="utf-8") as f:
+                    f.writelines(content)
+
+                results[filename] = len(content)
+                logger.info(f"[OK] {path} ({len(content)} lines)")
+
+            # Generate the new main squid.conf with includes
+            self._generate_main_config(list(buffers.keys()))
+            logger.info(f"Generated new main config: {self.input_file}")
+
+            return results
+
+        except Exception as e:
+            logger.exception(f"Error splitting configuration file: {e}")
+            raise
+
+    def _generate_main_config(self, generated_files: list[str]) -> None:
+        header = [
+            "# ============================================================\n",
+            "# Archivo generado automáticamente por SquidStats\n",
+            f"# Fecha: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n",
+            "# NO EDITAR A MANO - Los cambios se perderán\n",
+            "# ============================================================\n",
+            "\n",
+        ]
+
+        includes = []
+        for filename in sorted(generated_files):
+            include_path = os.path.join(self.output_dir, filename)
+            includes.append(f"include {include_path}\n")
+
+        try:
+            with open(self.input_file, "w", encoding="utf-8") as f:
+                f.writelines(header)
+                f.writelines(includes)
+            logger.info(f"Main configuration file regenerated with {len(includes)} includes")
+        except Exception as e:
+            logger.error(f"Failed to generate main config: {e}")
+            raise RuntimeError(f"Failed to generate main config: {e}")
+
+    def get_split_info(self) -> dict[str, str]:
+        return {
+            "00_ports.conf": "HTTP ports configuration",
+            "10_misc.conf": "Miscellaneous configurations",
+            "20_security.conf": "Security configuration",
+            "30_cache.conf": "Cache configuration",
+            "40_refresh_patterns.conf": "Refresh patterns",
+            "50_ssl_bump.conf": "SSL Bump configuration",
+            "60_logs.conf": "Logs configuration",
+            "70_icap.conf": "ICAP configuration",
+            "80_dns.conf": "DNS configuration",
+            "90_auth.conf": "Authentication configuration",
+            "100_acls.conf": "Access control lists (ACLs)",
+            "110_delay_pools.conf": "Delay pools configuration",
+            "115_cache_control.conf": "Cache control and peering",
+            "120_http_access.conf": "HTTP access rules",
+            "999_unknown.conf": "Unclassified directives",
+        }
+
+    def check_output_dir_exists(self) -> bool:
+        return os.path.exists(self.output_dir) and os.path.isdir(self.output_dir)
+
+    def count_files_in_output_dir(self) -> int:
+        if not self.check_output_dir_exists():
+            return 0
+        return len([f for f in os.listdir(self.output_dir) if f.endswith(".conf")])

+ 482 - 0
static/js/acls.js

@@ -0,0 +1,482 @@
+// ACL Type Information and Examples
+const aclTypeInfo = {
+    // Network / IP
+    'src': {
+        description: 'IP de origen del cliente. Puede incluir direcciones IP individuales, rangos CIDR o subredes.',
+        example: 'acl localnet src 192.168.1.0/24 10.0.0.0/8',
+        icon: 'network-wired',
+        color: 'blue',
+        slow: false
+    },
+    'dst': {
+        description: 'IP de destino (requiere búsqueda DNS inversa, puede ser lento).',
+        example: 'acl servidores dst 10.0.0.5 10.0.0.6',
+        icon: 'network-wired',
+        color: 'blue',
+        slow: true
+    },
+    'localip': {
+        description: 'IP local de la conexión proxy.',
+        example: 'acl mipublic localip 203.0.113.45',
+        icon: 'network-wired',
+        color: 'blue',
+        slow: false
+    },
+    'src_as': {
+        description: 'Autonomous System number de origen.',
+        example: 'acl mi_as src_as 64512',
+        icon: 'network-wired',
+        color: 'blue',
+        slow: false
+    },
+    'dst_as': {
+        description: 'Autonomous System number de destino.',
+        example: 'acl redes_cdn dst_as 16509',
+        icon: 'network-wired',
+        color: 'blue',
+        slow: false
+    },
+    
+    // Domains
+    'dstdomain': {
+        description: 'Dominio de destino. Soporta comodines con puntos al inicio.',
+        example: 'acl sitios_permitidos dstdomain .example.com .google.com',
+        icon: 'globe',
+        color: 'green',
+        slow: false
+    },
+    'srcdomain': {
+        description: 'Dominio de origen del cliente (requiere DNS inverso, lento).',
+        example: 'acl red_interna srcdomain .mi-empresa.local',
+        icon: 'globe',
+        color: 'green',
+        slow: true
+    },
+    'dstdom_regex': {
+        description: 'Expresión regular para coincidencia de dominios de destino.',
+        example: 'acl redes_sociales dstdom_regex -i (facebook|twitter|instagram)\\.com',
+        icon: 'globe',
+        color: 'green',
+        slow: false
+    },
+    'srcdom_regex': {
+        description: 'Expresión regular para dominios de origen (requiere DNS inverso).',
+        example: 'acl externos srcdom_regex -i ^.*\\.external\\.com$',
+        icon: 'globe',
+        color: 'green',
+        slow: true
+    },
+    
+    // Ports
+    'port': {
+        description: 'Puerto TCP de destino. Puede ser número o rango.',
+        example: 'acl Safe_ports port 80 443 8080 21',
+        icon: 'plug',
+        color: 'cyan',
+        slow: false
+    },
+    'localport': {
+        description: 'Puerto local en el que se recibió la conexión.',
+        example: 'acl puerto_principal localport 3128',
+        icon: 'plug',
+        color: 'cyan',
+        slow: false
+    },
+    'myportname': {
+        description: 'Nombre del puerto según http_port.',
+        example: 'acl transparente myportname proxy_transparente',
+        icon: 'plug',
+        color: 'cyan',
+        slow: false
+    },
+    
+    // Time
+    'time': {
+        description: 'Día de la semana y hora. Formato: [SMTWHAS][h1:m1-h2:m2]',
+        example: 'acl horario_laboral time MTWHF 09:00-18:00',
+        icon: 'clock',
+        color: 'orange',
+        slow: false
+    },
+    
+    // URL
+    'url_regex': {
+        description: 'Expresión regular que coincide con la URL completa.',
+        example: 'acl anuncios url_regex -i \\.gif$ \\.jpg$ banner',
+        icon: 'link',
+        color: 'indigo',
+        slow: false
+    },
+    'urlpath_regex': {
+        description: 'Expresión regular solo para el path de la URL.',
+        example: 'acl descarga urlpath_regex -i \\.exe$ \\.zip$ \\.rar$',
+        icon: 'link',
+        color: 'indigo',
+        slow: false
+    },
+    'urllogin': {
+        description: 'Expresión regular para el componente de login de la URL.',
+        example: 'acl usuarios_externos urllogin -i ^guest.*',
+        icon: 'link',
+        color: 'indigo',
+        slow: false
+    },
+    
+    // Protocol
+    'proto': {
+        description: 'Protocolo de la petición (HTTP, FTP, etc.).',
+        example: 'acl protocolo_http proto HTTP',
+        icon: 'exchange-alt',
+        color: 'teal',
+        slow: false
+    },
+    'method': {
+        description: 'Método HTTP de la petición.',
+        example: 'acl CONNECT method CONNECT',
+        icon: 'exchange-alt',
+        color: 'teal',
+        slow: false
+    },
+    'http_status': {
+        description: 'Código de estado HTTP en la respuesta.',
+        example: 'acl errores_server http_status 500 502 503 504',
+        icon: 'exchange-alt',
+        color: 'teal',
+        slow: false
+    },
+    
+    // Authentication
+    'proxy_auth': {
+        description: 'Usuario autenticado (requiere autenticación configurada).',
+        example: 'acl usuarios_premium proxy_auth juan maria pedro',
+        icon: 'user-lock',
+        color: 'red',
+        slow: true
+    },
+    'proxy_auth_regex': {
+        description: 'Expresión regular para nombre de usuario autenticado.',
+        example: 'acl admins proxy_auth_regex -i ^admin',
+        icon: 'user-lock',
+        color: 'red',
+        slow: true
+    },
+    'ext_user': {
+        description: 'Usuario provisto por helper externo.',
+        example: 'acl usuarios_ldap ext_user juan maria',
+        icon: 'user-lock',
+        color: 'red',
+        slow: true
+    },
+    'ext_user_regex': {
+        description: 'Expresión regular para usuarios de helper externo.',
+        example: 'acl grupo_ventas ext_user_regex -i ^ventas_',
+        icon: 'user-lock',
+        color: 'red',
+        slow: true
+    },
+    
+    // Content
+    'browser': {
+        description: 'Expresión regular para User-Agent del navegador.',
+        example: 'acl bots browser -i (bot|crawler|spider)',
+        icon: 'file-alt',
+        color: 'yellow',
+        slow: false
+    },
+    'referer_regex': {
+        description: 'Expresión regular para el header Referer.',
+        example: 'acl desde_google referer_regex -i google\\.com',
+        icon: 'file-alt',
+        color: 'yellow',
+        slow: false
+    },
+    'req_mime_type': {
+        description: 'Tipo MIME en el request.',
+        example: 'acl upload_imagen req_mime_type image/jpeg image/png',
+        icon: 'file-alt',
+        color: 'yellow',
+        slow: false
+    },
+    'rep_mime_type': {
+        description: 'Tipo MIME en la respuesta.',
+        example: 'acl tipo_video rep_mime_type video/mp4 video/mpeg',
+        icon: 'file-alt',
+        color: 'yellow',
+        slow: false
+    },
+    'req_header': {
+        description: 'Header específico del request.',
+        example: 'acl api_key req_header X-API-Key',
+        icon: 'file-alt',
+        color: 'yellow',
+        slow: false
+    },
+    'rep_header': {
+        description: 'Header específico de la respuesta.',
+        example: 'acl con_cache rep_header Cache-Control',
+        icon: 'file-alt',
+        color: 'yellow',
+        slow: false
+    },
+    
+    // SSL/TLS
+    'ssl_error': {
+        description: 'Código de error SSL/TLS.',
+        example: 'acl ssl_expired ssl_error X509_V_ERR_CERT_HAS_EXPIRED',
+        icon: 'lock',
+        color: 'emerald',
+        slow: false
+    },
+    'server_cert_fingerprint': {
+        description: 'Fingerprint del certificado del servidor.',
+        example: 'acl cert_confiable server_cert_fingerprint AA:BB:CC:DD',
+        icon: 'lock',
+        color: 'emerald',
+        slow: false
+    },
+    'ssl::server_name': {
+        description: 'Server Name Indication (SNI) en conexiones TLS.',
+        example: 'acl sitio_seguro ssl::server_name .example.com',
+        icon: 'lock',
+        color: 'emerald',
+        slow: false
+    },
+    'ssl::server_name_regex': {
+        description: 'Expresión regular para SNI.',
+        example: 'acl bancos ssl::server_name_regex -i banco.*\\.com$',
+        icon: 'lock',
+        color: 'emerald',
+        slow: false
+    },
+    
+    // Connections
+    'maxconn': {
+        description: 'Límite máximo de conexiones por IP.',
+        example: 'acl max_10 maxconn 10',
+        icon: 'server',
+        color: 'pink',
+        slow: false
+    },
+    'max_user_ip': {
+        description: 'Límite máximo de IPs diferentes por usuario.',
+        example: 'acl max_3_ips max_user_ip 3',
+        icon: 'server',
+        color: 'pink',
+        slow: false
+    },
+    
+    // Advanced
+    'external': {
+        description: 'Helper externo personalizado (puede ser muy lento).',
+        example: 'acl verificado external checker_script %DST',
+        icon: 'cogs',
+        color: 'gray',
+        slow: true
+    },
+    'random': {
+        description: 'Probabilidad aleatoria (0.0 a 1.0).',
+        example: 'acl un_tercio random 0.333',
+        icon: 'cogs',
+        color: 'gray',
+        slow: false
+    },
+    'note': {
+        description: 'Anotación de transacción.',
+        example: 'acl tiene_nota note importante',
+        icon: 'cogs',
+        color: 'gray',
+        slow: false
+    },
+    'any-of': {
+        description: 'Grupo de ACLs con lógica OR (coincide si alguna es verdadera).',
+        example: 'acl grupo any-of acl1 acl2 acl3',
+        icon: 'cogs',
+        color: 'gray',
+        slow: false
+    },
+    'all-of': {
+        description: 'Grupo de ACLs con lógica AND (coincide si todas son verdaderas).',
+        example: 'acl combinado all-of acl1 acl2',
+        icon: 'cogs',
+        color: 'gray',
+        slow: false
+    }
+};
+
+let addValueCounter = 0;
+let editValueCounter = 0;
+
+// Show Add Modal
+function showAddModal() {
+    document.getElementById('addModal').classList.remove('hidden');
+    document.getElementById('addForm').reset();
+    document.getElementById('addValuesList').innerHTML = '';
+    document.getElementById('addTypeInfo').classList.add('hidden');
+    addValueCounter = 0;
+    addValueInput('add'); // Add one value input by default
+}
+
+// Close Add Modal
+function closeAddModal() {
+    document.getElementById('addModal').classList.add('hidden');
+}
+
+// Update type information in add modal
+function updateAddTypeInfo() {
+    const typeSelect = document.getElementById('addType');
+    const selectedType = typeSelect.value;
+    const infoDiv = document.getElementById('addTypeInfo');
+    
+    if (!selectedType || !aclTypeInfo[selectedType]) {
+        infoDiv.classList.add('hidden');
+        return;
+    }
+    
+    const info = aclTypeInfo[selectedType];
+    document.getElementById('addTypeDesc').textContent = info.description;
+    document.getElementById('addTypeExample').textContent = 'Ejemplo: ' + info.example;
+    
+    // Change icon color based on slow/fast
+    const iconEl = document.getElementById('addTypeIcon');
+    if (info.slow) {
+        iconEl.className = 'fas fa-hourglass text-orange-600 mt-1 mr-2';
+    } else {
+        iconEl.className = 'fas fa-bolt text-green-600 mt-1 mr-2';
+    }
+    
+    infoDiv.classList.remove('hidden');
+}
+
+// Add value input field
+function addValueInput(mode) {
+    const listId = mode === 'add' ? 'addValuesList' : 'editValuesList';
+    const list = document.getElementById(listId);
+    
+    if (mode === 'add') {
+        addValueCounter++;
+    } else {
+        editValueCounter++;
+    }
+    
+    const counter = mode === 'add' ? addValueCounter : editValueCounter;
+    
+    const div = document.createElement('div');
+    div.className = 'flex items-center space-x-2';
+    div.id = `${mode}Value${counter}`;
+    
+    div.innerHTML = `
+        <input type="text" name="values[]" required 
+               placeholder="Ingresa un valor (ej: 192.168.1.0/24, .example.com, 80)"
+               class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
+        <button type="button" onclick="removeValueInput('${mode}', ${counter})" 
+                class="px-3 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors">
+            <i class="fas fa-trash"></i>
+        </button>
+    `;
+    
+    list.appendChild(div);
+}
+
+// Remove value input field
+function removeValueInput(mode, counter) {
+    const div = document.getElementById(`${mode}Value${counter}`);
+    if (div) {
+        div.remove();
+    }
+}
+
+// Edit ACL
+function editAcl(id, name, type, valueList, options, comment) {
+    document.getElementById('editModal').classList.remove('hidden');
+    document.getElementById('editId').value = id;
+    document.getElementById('editName').value = name;
+    document.getElementById('editType').value = type;
+    document.getElementById('editTypeDisplay').value = type;
+    document.getElementById('editComment').value = comment || '';
+    
+    // Set options checkboxes
+    document.getElementById('editOptI').checked = options.includes('-i');
+    document.getElementById('editOptN').checked = options.includes('-n');
+    document.getElementById('editOptM').checked = options.includes('-m');
+    
+    // Clear and populate values
+    const valuesList = document.getElementById('editValuesList');
+    valuesList.innerHTML = '';
+    editValueCounter = 0;
+    
+    if (valueList && valueList.length > 0) {
+        valueList.forEach(value => {
+            editValueCounter++;
+            const div = document.createElement('div');
+            div.className = 'flex items-center space-x-2';
+            div.id = `editValue${editValueCounter}`;
+            
+            div.innerHTML = `
+                <input type="text" name="values[]" required value="${value}"
+                       class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
+                <button type="button" onclick="removeValueInput('edit', ${editValueCounter})" 
+                        class="px-3 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors">
+                    <i class="fas fa-trash"></i>
+                </button>
+            `;
+            
+            valuesList.appendChild(div);
+        });
+    } else {
+        addValueInput('edit');
+    }
+}
+
+// Close Edit Modal
+function closeEditModal() {
+    document.getElementById('editModal').classList.add('hidden');
+}
+
+// Delete ACL
+function deleteAcl(id, name) {
+    if (!confirm(`¿Estás seguro de que deseas eliminar la ACL "${name}"?\n\nEsto puede afectar las reglas de http_access y delay_pools que la utilicen.`)) {
+        return;
+    }
+    
+    const form = document.createElement('form');
+    form.method = 'POST';
+    form.action = '/admin/acls/delete';
+    
+    // CSRF token
+    const csrfInput = document.createElement('input');
+    csrfInput.type = 'hidden';
+    csrfInput.name = 'csrf_token';
+    csrfInput.value = document.querySelector('input[name="csrf_token"]').value;
+    form.appendChild(csrfInput);
+    
+    // ACL ID
+    const idInput = document.createElement('input');
+    idInput.type = 'hidden';
+    idInput.name = 'id';
+    idInput.value = id;
+    form.appendChild(idInput);
+    
+    document.body.appendChild(form);
+    form.submit();
+}
+
+// Close modals on ESC key
+document.addEventListener('keydown', function(event) {
+    if (event.key === 'Escape') {
+        closeAddModal();
+        closeEditModal();
+    }
+});
+
+// Close modals when clicking outside
+document.getElementById('addModal')?.addEventListener('click', function(event) {
+    if (event.target === this) {
+        closeAddModal();
+    }
+});
+
+document.getElementById('editModal')?.addEventListener('click', function(event) {
+    if (event.target === this) {
+        closeEditModal();
+    }
+});

+ 7 - 0
templates/admin/acls.html

@@ -181,7 +181,14 @@ function deleteAcl(id, name) {
         idInput.name = 'id';
         idInput.value = id;
         
+        // Add CSRF token
+        const csrfInput = document.createElement('input');
+        csrfInput.type = 'hidden';
+        csrfInput.name = 'csrf_token';
+        csrfInput.value = '{{ csrf_token() }}';
+        
         form.appendChild(idInput);
+        form.appendChild(csrfInput);
         document.body.appendChild(form);
         form.submit();
     }

+ 226 - 0
templates/admin/acls_modals.html

@@ -0,0 +1,226 @@
+<!-- Add Modal -->
+<div id="addModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
+    <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full p-6 max-h-[90vh] overflow-y-auto">
+        <h3 class="text-2xl font-bold text-gray-800 mb-4">
+            <i class="fas fa-plus-circle text-blue-600 mr-2"></i>Agregar Nueva ACL
+        </h3>
+        <form id="addForm" method="POST" action="/admin/acls/add">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
+            
+            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
+                <div>
+                    <label class="block text-gray-700 font-semibold mb-2">Nombre de la ACL:</label>
+                    <input type="text" name="name" id="addName" required 
+                           pattern="[a-zA-Z0-9_-]+" 
+                           placeholder="mi_acl_personalizada"
+                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
+                    <p class="text-xs text-gray-500 mt-1">Solo letras, números, guiones y guiones bajos</p>
+                </div>
+                
+                <div>
+                    <label class="block text-gray-700 font-semibold mb-2">Tipo de ACL:</label>
+                    <select name="type" id="addType" onchange="updateAddTypeInfo()" required 
+                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
+                        <option value="">Selecciona un tipo...</option>
+                        <optgroup label="🌐 Red / IP">
+                            <option value="src">src - IP origen del cliente</option>
+                            <option value="dst">dst - IP destino [slow]</option>
+                            <option value="localip">localip - IP local de conexión</option>
+                            <option value="src_as">src_as - AS number origen</option>
+                            <option value="dst_as">dst_as - AS number destino</option>
+                        </optgroup>
+                        <optgroup label="🌍 Dominios">
+                            <option value="dstdomain">dstdomain - Dominio destino</option>
+                            <option value="srcdomain">srcdomain - Dominio origen [slow]</option>
+                            <option value="dstdom_regex">dstdom_regex - Regex dominio destino</option>
+                            <option value="srcdom_regex">srcdom_regex - Regex dominio origen [slow]</option>
+                        </optgroup>
+                        <optgroup label="🔌 Puertos">
+                            <option value="port">port - Puerto TCP destino</option>
+                            <option value="localport">localport - Puerto local</option>
+                            <option value="myportname">myportname - Nombre de puerto</option>
+                        </optgroup>
+                        <optgroup label="🕐 Tiempo">
+                            <option value="time">time - Día y hora</option>
+                        </optgroup>
+                        <optgroup label="🔗 URL">
+                            <option value="url_regex">url_regex - Regex en URL completa</option>
+                            <option value="urlpath_regex">urlpath_regex - Regex en path</option>
+                            <option value="urllogin">urllogin - Regex en login URL</option>
+                        </optgroup>
+                        <optgroup label="⚡ Protocolo">
+                            <option value="proto">proto - Protocolo (HTTP/FTP)</option>
+                            <option value="method">method - Método HTTP</option>
+                            <option value="http_status">http_status - Código HTTP</option>
+                        </optgroup>
+                        <optgroup label="🔐 Autenticación">
+                            <option value="proxy_auth">proxy_auth - Usuario proxy [slow]</option>
+                            <option value="proxy_auth_regex">proxy_auth_regex - Regex usuario [slow]</option>
+                            <option value="ext_user">ext_user - Usuario externo [slow]</option>
+                            <option value="ext_user_regex">ext_user_regex - Regex usuario ext [slow]</option>
+                        </optgroup>
+                        <optgroup label="📄 Contenido">
+                            <option value="browser">browser - User-Agent</option>
+                            <option value="referer_regex">referer_regex - Referer</option>
+                            <option value="req_mime_type">req_mime_type - MIME request</option>
+                            <option value="rep_mime_type">rep_mime_type - MIME reply</option>
+                            <option value="req_header">req_header - Header request</option>
+                            <option value="rep_header">rep_header - Header reply</option>
+                        </optgroup>
+                        <optgroup label="🔒 SSL/TLS">
+                            <option value="ssl_error">ssl_error - Error SSL</option>
+                            <option value="server_cert_fingerprint">server_cert_fingerprint - Fingerprint</option>
+                            <option value="ssl::server_name">ssl::server_name - SNI</option>
+                            <option value="ssl::server_name_regex">ssl::server_name_regex - SNI regex</option>
+                        </optgroup>
+                        <optgroup label="🔧 Conexiones">
+                            <option value="maxconn">maxconn - Max conexiones IP</option>
+                            <option value="max_user_ip">max_user_ip - Max IPs usuario</option>
+                        </optgroup>
+                        <optgroup label="⚙️ Avanzado">
+                            <option value="external">external - Helper externo [slow]</option>
+                            <option value="random">random - Probabilidad random</option>
+                            <option value="note">note - Anotación transacción</option>
+                            <option value="any-of">any-of - Grupo OR</option>
+                            <option value="all-of">all-of - Grupo AND</option>
+                        </optgroup>
+                    </select>
+                </div>
+            </div>
+            
+            <!-- Type Info Display -->
+            <div id="addTypeInfo" class="hidden mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3">
+                <div class="flex items-start">
+                    <i id="addTypeIcon" class="fas fa-info-circle text-blue-600 mt-1 mr-2"></i>
+                    <div class="flex-1">
+                        <p id="addTypeDesc" class="text-sm text-gray-700 font-medium"></p>
+                        <p id="addTypeExample" class="text-xs text-gray-600 mt-1 font-mono"></p>
+                    </div>
+                </div>
+            </div>
+            
+            <!-- Options -->
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Opciones (opcional):</label>
+                <div class="flex flex-wrap gap-2">
+                    <label class="flex items-center px-3 py-2 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50">
+                        <input type="checkbox" name="options[]" value="-i" class="mr-2">
+                        <span class="text-sm"><code>-i</code> Case-insensitive</span>
+                    </label>
+                    <label class="flex items-center px-3 py-2 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50">
+                        <input type="checkbox" name="options[]" value="-n" class="mr-2">
+                        <span class="text-sm"><code>-n</code> No lookups</span>
+                    </label>
+                    <label class="flex items-center px-3 py-2 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50">
+                        <input type="checkbox" name="options[]" value="-m" class="mr-2">
+                        <span class="text-sm"><code>-m</code> List membership</span>
+                    </label>
+                </div>
+            </div>
+            
+            <!-- Values -->
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Valores:</label>
+                <div id="addValuesList" class="space-y-2 mb-2">
+                    <!-- Values will be added dynamically -->
+                </div>
+                <button type="button" onclick="addValueInput('add')" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
+                    <i class="fas fa-plus-circle mr-1"></i>Agregar valor
+                </button>
+            </div>
+            
+            <!-- Comment -->
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Comentario (opcional):</label>
+                <input type="text" name="comment" placeholder="Descripción de esta ACL"
+                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
+                <p class="text-xs text-gray-500 mt-1">Se agregará como comentario antes de la ACL</p>
+            </div>
+            
+            <div class="flex space-x-2 justify-end mt-6 pt-4 border-t">
+                <button type="button" onclick="closeAddModal()" class="px-5 py-2 bg-gray-300 hover:bg-gray-400 text-gray-800 rounded-lg transition-colors font-medium">
+                    Cancelar
+                </button>
+                <button type="submit" class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors font-medium">
+                    <i class="fas fa-save mr-2"></i>Crear ACL
+                </button>
+            </div>
+        </form>
+    </div>
+</div>
+
+<!-- Edit Modal -->
+<div id="editModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
+    <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full p-6 max-h-[90vh] overflow-y-auto">
+        <h3 class="text-2xl font-bold text-gray-800 mb-4">
+            <i class="fas fa-edit text-blue-600 mr-2"></i>Editar ACL
+        </h3>
+        <form id="editForm" method="POST" action="/admin/acls/edit">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
+            <input type="hidden" name="id" id="editId">
+            
+            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
+                <div>
+                    <label class="block text-gray-700 font-semibold mb-2">Nombre de la ACL:</label>
+                    <input type="text" name="name" id="editName" required 
+                           pattern="[a-zA-Z0-9_-]+"
+                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
+                </div>
+                
+                <div>
+                    <label class="block text-gray-700 font-semibold mb-2">Tipo de ACL:</label>
+                    <input type="text" id="editTypeDisplay" disabled
+                           class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100 text-gray-600">
+                    <input type="hidden" name="type" id="editType">
+                    <p class="text-xs text-gray-500 mt-1">El tipo no se puede cambiar, crea una nueva ACL si necesitas otro tipo</p>
+                </div>
+            </div>
+            
+            <!-- Options -->
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Opciones:</label>
+                <div class="flex flex-wrap gap-2">
+                    <label class="flex items-center px-3 py-2 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50">
+                        <input type="checkbox" name="options[]" value="-i" id="editOptI" class="mr-2">
+                        <span class="text-sm"><code>-i</code> Case-insensitive</span>
+                    </label>
+                    <label class="flex items-center px-3 py-2 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50">
+                        <input type="checkbox" name="options[]" value="-n" id="editOptN" class="mr-2">
+                        <span class="text-sm"><code>-n</code> No lookups</span>
+                    </label>
+                    <label class="flex items-center px-3 py-2 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50">
+                        <input type="checkbox" name="options[]" value="-m" id="editOptM" class="mr-2">
+                        <span class="text-sm"><code>-m</code> List membership</span>
+                    </label>
+                </div>
+            </div>
+            
+            <!-- Values -->
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Valores:</label>
+                <div id="editValuesList" class="space-y-2 mb-2">
+                    <!-- Values will be filled dynamically -->
+                </div>
+                <button type="button" onclick="addValueInput('edit')" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
+                    <i class="fas fa-plus-circle mr-1"></i>Agregar valor
+                </button>
+            </div>
+            
+            <!-- Comment -->
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Comentario:</label>
+                <input type="text" name="comment" id="editComment"
+                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
+            </div>
+            
+            <div class="flex space-x-2 justify-end mt-6 pt-4 border-t">
+                <button type="button" onclick="closeEditModal()" class="px-5 py-2 bg-gray-300 hover:bg-gray-400 text-gray-800 rounded-lg transition-colors font-medium">
+                    Cancelar
+                </button>
+                <button type="submit" class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors font-medium">
+                    <i class="fas fa-save mr-2"></i>Guardar Cambios
+                </button>
+            </div>
+        </form>
+    </div>
+</div>

+ 163 - 0
templates/admin/acls_new.html

@@ -0,0 +1,163 @@
+{% extends "admin/base.html" %}
+
+{% block content %}
+<div class="bg-white rounded-lg shadow-lg p-4 sm:p-6">
+    <div class="flex justify-between items-center mb-4 sm:mb-6">
+        <div>
+            <h2 class="text-xl sm:text-2xl font-bold text-gray-800">Gestión de Access Control Lists (ACLs)</h2>
+            <p class="text-sm text-gray-600 mt-1">Define condiciones para controlar el acceso al proxy</p>
+        </div>
+        <button onclick="showAddModal()" class="bg-blue-600 hover:bg-blue-700 text-white font-semibold px-4 py-2 rounded-lg shadow-md transition-colors">
+            <i class="fas fa-plus mr-2"></i>Agregar ACL
+        </button>
+    </div>
+    
+    {% if acls %}
+    <div class="mb-4 bg-blue-50 border border-blue-200 rounded-lg p-4">
+        <div class="flex items-start">
+            <i class="fas fa-info-circle text-blue-600 mt-1 mr-3"></i>
+            <div class="text-sm text-gray-700">
+                <p class="font-semibold text-gray-800 mb-1">Acerca de las ACLs:</p>
+                <ul class="list-disc list-inside space-y-1 ml-2">
+                    <li><span class="font-mono text-xs bg-white px-1 rounded">[fast]</span> ACLs rápidas - no requieren lookups externos</li>
+                    <li><span class="font-mono text-xs bg-orange-100 px-1 rounded">[slow]</span> ACLs lentas - pueden requerir DNS o autenticación</li>
+                    <li>Usa las ACLs en reglas de http_access, http_reply_access, etc.</li>
+                    <li>ACLs predefinidas: <code class="bg-white px-1 rounded">all, manager, localhost, to_localhost, to_linklocal, CONNECT</code></li>
+                </ul>
+            </div>
+        </div>
+    </div>
+
+    <div class="space-y-2">
+        {% for acl in acls %}
+        <div class="flex flex-col sm:flex-row items-start justify-between p-4 bg-gradient-to-r from-gray-50 to-white rounded-lg border border-gray-200 hover:border-gray-300 transition-all gap-3">
+            <div class="flex items-start space-x-3 flex-1 min-w-0 w-full">
+                <div class="flex flex-col items-center space-y-1 flex-shrink-0">
+                    {% if acl.is_predefined %}
+                        <span class="inline-flex px-2 py-1 text-xs font-bold rounded-full bg-purple-100 text-purple-800 border border-purple-300">
+                            <i class="fas fa-star mr-1"></i>BUILT-IN
+                        </span>
+                    {% endif %}
+                    
+                    {% if acl.category == 'network' %}
+                        <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
+                            <i class="fas fa-network-wired text-blue-600"></i>
+                        </div>
+                    {% elif acl.category == 'domain' %}
+                        <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
+                            <i class="fas fa-globe text-green-600"></i>
+                        </div>
+                    {% elif acl.category == 'time' %}
+                        <div class="w-10 h-10 rounded-full bg-orange-100 flex items-center justify-center">
+                            <i class="fas fa-clock text-orange-600"></i>
+                        </div>
+                    {% elif acl.category == 'url' %}
+                        <div class="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center">
+                            <i class="fas fa-link text-indigo-600"></i>
+                        </div>
+                    {% elif acl.category == 'port' %}
+                        <div class="w-10 h-10 rounded-full bg-cyan-100 flex items-center justify-center">
+                            <i class="fas fa-plug text-cyan-600"></i>
+                        </div>
+                    {% elif acl.category == 'protocol' %}
+                        <div class="w-10 h-10 rounded-full bg-teal-100 flex items-center justify-center">
+                            <i class="fas fa-exchange-alt text-teal-600"></i>
+                        </div>
+                    {% elif acl.category == 'auth' %}
+                        <div class="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
+                            <i class="fas fa-user-lock text-red-600"></i>
+                        </div>
+                    {% elif acl.category == 'content' %}
+                        <div class="w-10 h-10 rounded-full bg-yellow-100 flex items-center justify-center">
+                            <i class="fas fa-file-alt text-yellow-600"></i>
+                        </div>
+                    {% elif acl.category == 'ssl' %}
+                        <div class="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center">
+                            <i class="fas fa-lock text-emerald-600"></i>
+                        </div>
+                    {% elif acl.category == 'connection' %}
+                        <div class="w-10 h-10 rounded-full bg-pink-100 flex items-center justify-center">
+                            <i class="fas fa-server text-pink-600"></i>
+                        </div>
+                    {% else %}
+                        <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center">
+                            <i class="fas fa-cog text-gray-600"></i>
+                        </div>
+                    {% endif %}
+                </div>
+                
+                <div class="flex-1 min-w-0">
+                    <div class="flex items-center gap-2 mb-2">
+                        <h3 class="text-lg font-bold text-gray-800">{{ acl.name }}</h3>
+                        <span class="inline-flex px-2 py-0.5 text-xs font-semibold rounded bg-gray-100 text-gray-700 border border-gray-300">
+                            {{ acl.type }}
+                        </span>
+                        {% if acl.is_slow %}
+                            <span class="inline-flex px-2 py-0.5 text-xs font-semibold rounded bg-orange-100 text-orange-700 border border-orange-300">
+                                <i class="fas fa-hourglass-half mr-1"></i>slow
+                            </span>
+                        {% else %}
+                            <span class="inline-flex px-2 py-0.5 text-xs font-semibold rounded bg-green-100 text-green-700 border border-green-300">
+                                <i class="fas fa-bolt mr-1"></i>fast
+                            </span>
+                        {% endif %}
+                        {% for option in acl.options %}
+                            <span class="inline-flex px-2 py-0.5 text-xs font-mono rounded bg-blue-100 text-blue-700 border border-blue-300">
+                                {{ option }}
+                            </span>
+                        {% endfor %}
+                    </div>
+                    
+                    <p class="text-sm text-gray-600 mb-2">
+                        <i class="fas fa-info-circle mr-1"></i>{{ acl.type_description }}
+                    </p>
+                    
+                    <div class="bg-gray-50 rounded p-2 border border-gray-200">
+                        <div class="flex flex-wrap gap-1">
+                            {% for value in acl.value_list %}
+                                <span class="inline-flex px-2 py-1 text-xs font-mono rounded bg-white text-gray-700 border border-gray-300">
+                                    {{ value }}
+                                </span>
+                            {% endfor %}
+                        </div>
+                    </div>
+                    
+                    {% if acl.comment %}
+                    <p class="text-xs text-gray-500 mt-2 italic">
+                        <i class="fas fa-comment-alt mr-1"></i>{{ acl.comment }}
+                    </p>
+                    {% endif %}
+                </div>
+            </div>
+            
+            <div class="flex space-x-2 flex-shrink-0 sm:ml-3">
+                <button onclick='editAcl({{ acl.id }}, "{{ acl.name }}", "{{ acl.type }}", {{ acl.value_list|tojson }}, {{ acl.options|tojson }}, "{{ acl.comment }}")' 
+                        class="text-blue-600 hover:text-blue-900 p-2 hover:bg-blue-100 rounded" 
+                        title="Editar">
+                    <i class="fas fa-edit text-lg"></i>
+                </button>
+                <button onclick='deleteAcl({{ acl.id }}, "{{ acl.name }}")' 
+                        class="text-red-600 hover:text-red-900 p-2 hover:bg-red-100 rounded" 
+                        title="Eliminar">
+                    <i class="fas fa-trash text-lg"></i>
+                </button>
+            </div>
+        </div>
+        {% endfor %}
+    </div>
+    {% else %}
+    <div class="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
+        <i class="fas fa-shield-alt text-6xl text-gray-300 mb-4"></i>
+        <p class="text-gray-500 text-lg font-medium">No hay ACLs personalizadas configuradas</p>
+        <p class="text-gray-400 text-sm mt-2">Las ACLs predefinidas de Squid siguen disponibles</p>
+        <button onclick="showAddModal()" class="mt-4 bg-blue-600 hover:bg-blue-700 text-white font-semibold px-6 py-2 rounded-lg shadow-md transition-colors">
+            <i class="fas fa-plus mr-2"></i>Crear primera ACL
+        </button>
+    </div>
+    {% endif %}
+</div>
+
+{% include 'admin/acls_modals.html' %}
+
+<script src="{{ url_for('static', filename='js/acls.js') }}"></script>
+{% endblock %}

+ 21 - 15
templates/admin/base.html

@@ -66,27 +66,33 @@
                     <a href="{{ url_for('admin.view_config') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
                         <i class="fas fa-cog mr-3"></i>Configuración
                     </a>
+                    <a href="{{ url_for('admin.split_config_view') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <i class="fas fa-code-branch mr-3"></i>Dividir Config
+                    </a>
                     <a href="{{ url_for('admin.manage_users') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
                         <i class="fas fa-users mr-3"></i>Usuarios
                     </a>
                     <a href="{{ url_for('admin.clean_data') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
                         <i class="fas fa-database mr-3"></i>Limpiar Datos
                     </a>
-                    <div class="flex items-center px-4 py-3 text-gray-400 cursor-not-allowed rounded-lg">
-                        <i class="fas fa-shield-alt mr-3"></i>
-                        <span>ACLs</span>
-                        <span class="ml-auto bg-yellow-100 text-yellow-800 text-xs font-medium px-2.5 py-0.5 rounded">Próximamente</span>
-                    </div>
-                    <div class="flex items-center px-4 py-3 text-gray-400 cursor-not-allowed rounded-lg">
-                        <i class="fas fa-clock mr-3"></i>
-                        <span>Delay Pools</span>
-                        <span class="ml-auto bg-yellow-100 text-yellow-800 text-xs font-medium px-2.5 py-0.5 rounded">Próximamente</span>
-                    </div>
-                    <div class="flex items-center px-4 py-3 text-gray-400 cursor-not-allowed rounded-lg">
-                        <i class="fas fa-key mr-3"></i>
-                        <span>HTTP Access</span>
-                        <span class="ml-auto bg-yellow-100 text-yellow-800 text-xs font-medium px-2.5 py-0.5 rounded">Próximamente</span>
-                    </div>
+                    <a href="{{ url_for('admin.manage_acls') }}" class="flex items-center justify-between px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <span class="flex items-center">
+                            <i class="fas fa-shield-alt mr-3"></i>ACLs
+                        </span>
+                        <span class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-xs font-semibold px-2.5 py-0.5 rounded-full shadow-sm">BETA</span>
+                    </a>
+                    <a href="{{ url_for('admin.manage_delay_pools') }}" class="flex items-center justify-between px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <span class="flex items-center">
+                            <i class="fas fa-clock mr-3"></i>Delay Pools
+                        </span>
+                        <span class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-xs font-semibold px-2.5 py-0.5 rounded-full shadow-sm">BETA</span>
+                    </a>
+                    <a href="{{ url_for('admin.manage_http_access') }}" class="flex items-center justify-between px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <span class="flex items-center">
+                            <i class="fas fa-key mr-3"></i>HTTP Access
+                        </span>
+                        <span class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-xs font-semibold px-2.5 py-0.5 rounded-full shadow-sm">BETA</span>
+                    </a>
                     <a href="{{ url_for('admin.view_logs') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
                         <i class="fas fa-file-alt mr-3"></i>Logs
                     </a>

+ 454 - 17
templates/admin/delay_pools.html

@@ -2,43 +2,480 @@
 
 {% block content %}
 <div class="bg-white rounded-lg shadow-lg p-4 sm:p-6">
-    <h2 class="text-xl sm:text-2xl font-bold text-gray-800 mb-4 sm:mb-6">Gestión de Delay Pools</h2>
+    <div class="flex justify-between items-center mb-4 sm:mb-6">
+        <h2 class="text-xl sm:text-2xl font-bold text-gray-800">Gestión de Delay Pools</h2>
+        <button onclick="showAddModal()" class="bg-blue-600 hover:bg-blue-700 text-white font-semibold px-4 py-2 rounded-lg shadow-md transition-colors">
+            <i class="fas fa-plus mr-2"></i>Agregar Pool
+        </button>
+    </div>
     
+    {% if delay_pools %}
     <div class="space-y-4 sm:space-y-6">
         {% for pool in delay_pools %}
-        <div class="border border-gray-200 rounded-lg p-4 sm:p-6">
+        <div class="border border-gray-200 rounded-lg p-4 sm:p-6 bg-gradient-to-br from-white to-gray-50">
             <div class="flex justify-between items-start mb-4">
-                <div>
-                    <h3 class="text-lg font-semibold text-gray-800">Pool {{ pool.id }}</h3>
-                    <p class="text-sm text-gray-600">Clase: {{ pool.class }}</p>
+                <div class="flex-1">
+                    <div class="flex items-center mb-2">
+                        <h3 class="text-xl font-bold text-gray-800">Pool #{{ pool.pool_number }}</h3>
+                        <span class="ml-3 bg-blue-100 text-blue-800 text-xs font-semibold px-2.5 py-0.5 rounded">
+                            Clase {{ pool.class }}
+                        </span>
+                    </div>
+                    <p class="text-sm text-gray-600">
+                        {% if pool.class == '1' %}
+                            <i class="fas fa-stream mr-1"></i> Bucket único agregado para todos los clientes
+                        {% elif pool.class == '2' %}
+                            <i class="fas fa-network-wired mr-1"></i> Bucket agregado + 255 buckets por host (red /24)
+                        {% elif pool.class == '3' %}
+                            <i class="fas fa-sitemap mr-1"></i> Buckets por subred + buckets por host (red /16)
+                        {% elif pool.class == '4' %}
+                            <i class="fas fa-users mr-1"></i> Como clase 3 + buckets por usuario autenticado
+                        {% elif pool.class == '5' %}
+                            <i class="fas fa-tags mr-1"></i> Buckets basados en tags de external_acl_type
+                        {% endif %}
+                    </p>
                 </div>
                 <div class="flex space-x-2">
-                    <button class="text-blue-600 hover:text-blue-900">
-                        <i class="fas fa-edit"></i>
+                    <button onclick='editPool({{ pool.pool_number }}, "{{ pool.class }}", "{{ pool.parameters }}", {{ pool.access_rules|tojson }})' 
+                            class="text-blue-600 hover:text-blue-900 p-2" title="Editar">
+                        <i class="fas fa-edit text-lg"></i>
                     </button>
-                    <button class="text-red-600 hover:text-red-900">
-                        <i class="fas fa-trash"></i>
+                    <button onclick="deletePool('{{ pool.pool_number }}')" 
+                            class="text-red-600 hover:text-red-900 p-2" title="Eliminar">
+                        <i class="fas fa-trash text-lg"></i>
                     </button>
                 </div>
             </div>
             
-            <div class="bg-gray-50 rounded-lg p-4 mb-4">
-                <h4 class="font-medium text-gray-800 mb-2">Parámetros:</h4>
-                <code class="text-sm text-gray-700">{{ pool.parameters }}</code>
+            {% if pool.parameters %}
+            <div class="bg-gray-50 rounded-lg p-4 mb-4 border border-gray-200">
+                <h4 class="font-semibold text-gray-800 mb-2 flex items-center">
+                    <i class="fas fa-tachometer-alt mr-2 text-blue-600"></i> Parámetros de Velocidad:
+                </h4>
+                <div class="font-mono text-sm text-gray-700 bg-white p-3 rounded border border-gray-300">
+                    {{ pool.parameters }}
+                </div>
+                <div class="mt-2 text-xs text-gray-600">
+                    {% set params = pool.parameters.split() %}
+                    {% if pool.class == '1' %}
+                        <span class="block"><i class="fas fa-circle text-xs mr-1"></i> Agregado: {{ params[0] if params|length > 0 }}</span>
+                    {% elif pool.class == '2' %}
+                        <span class="block"><i class="fas fa-circle text-xs mr-1"></i> Agregado: {{ params[0] if params|length > 0 }}</span>
+                        <span class="block"><i class="fas fa-circle text-xs mr-1"></i> Individual (por host): {{ params[1] if params|length > 1 }}</span>
+                    {% elif pool.class in ['3', '4'] %}
+                        <span class="block"><i class="fas fa-circle text-xs mr-1"></i> Agregado: {{ params[0] if params|length > 0 }}</span>
+                        <span class="block"><i class="fas fa-circle text-xs mr-1"></i> Red: {{ params[1] if params|length > 1 }}</span>
+                        <span class="block"><i class="fas fa-circle text-xs mr-1"></i> Individual (por host): {{ params[2] if params|length > 2 }}</span>
+                    {% endif %}
+                    <p class="mt-1 italic">Formato: restore/max (bytes por segundo)</p>
+                </div>
             </div>
+            {% endif %}
             
-            <div>
-                <h4 class="font-medium text-gray-800 mb-2">Reglas de Acceso:</h4>
-                <div class="space-y-1">
+            {% if pool.access_rules %}
+            <div class="bg-blue-50 rounded-lg p-4 border border-blue-200">
+                <h4 class="font-semibold text-gray-800 mb-3 flex items-center">
+                    <i class="fas fa-shield-alt mr-2 text-blue-600"></i> Reglas de Acceso:
+                </h4>
+                <div class="space-y-2">
                     {% for rule in pool.access_rules %}
-                    <div class="text-sm text-gray-600 bg-gray-50 p-2 rounded">
-                        <code>{{ rule }}</code>
+                    <div class="flex items-center bg-white p-2 rounded border border-gray-200">
+                        {% if rule.action == 'allow' %}
+                            <span class="bg-green-100 text-green-800 text-xs font-semibold px-2 py-1 rounded mr-2">ALLOW</span>
+                        {% else %}
+                            <span class="bg-red-100 text-red-800 text-xs font-semibold px-2 py-1 rounded mr-2">DENY</span>
+                        {% endif %}
+                        <span class="text-sm text-gray-700 font-mono">{{ rule.acl }}</span>
                     </div>
                     {% endfor %}
                 </div>
             </div>
+            {% endif %}
         </div>
         {% endfor %}
     </div>
+    {% else %}
+    <div class="text-center py-12">
+        <i class="fas fa-clock text-6xl text-gray-300 mb-4"></i>
+        <p class="text-gray-500 text-lg">No hay delay pools configurados</p>
+        <button onclick="showAddModal()" class="mt-4 bg-blue-600 hover:bg-blue-700 text-white font-semibold px-6 py-2 rounded-lg shadow-md transition-colors">
+            <i class="fas fa-plus mr-2"></i>Crear primer Pool
+        </button>
+    </div>
+    {% endif %}
+</div>
+
+<!-- Add Modal -->
+<div id="addModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
+    <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
+        <h3 class="text-2xl font-bold text-gray-800 mb-4">
+            <i class="fas fa-plus-circle text-blue-600 mr-2"></i>Agregar Nuevo Delay Pool
+        </h3>
+        <form id="addForm" method="POST" action="/admin/delay-pools/add">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Número de Pool:</label>
+                <input type="number" name="pool_number" id="addPoolNumber" min="1" max="255" 
+                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
+                       required placeholder="1">
+                <p class="text-xs text-gray-500 mt-1">Número único del pool (1-255)</p>
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Clase de Pool:</label>
+                <select name="pool_class" id="addPoolClass" onchange="updateParametersHelp('add')"
+                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
+                    <option value="">Seleccione una clase...</option>
+                    <option value="1">Clase 1 - Bucket único agregado</option>
+                    <option value="2">Clase 2 - Agregado + por host (/24)</option>
+                    <option value="3">Clase 3 - Agregado + red + por host (/16)</option>
+                    <option value="4">Clase 4 - Como clase 3 + por usuario</option>
+                    <option value="5">Clase 5 - Basado en tags</option>
+                </select>
+            </div>
+            
+            <div id="addParametersSection" class="mb-4 hidden">
+                <label class="block text-gray-700 font-semibold mb-2">Parámetros de Velocidad:</label>
+                
+                <!-- Clase 1 -->
+                <div id="addClass1Params" class="hidden space-y-3">
+                    <div class="bg-blue-50 p-3 rounded border border-blue-200 text-sm text-gray-700">
+                        <strong>Clase 1:</strong> Un solo bucket agregado para todos los clientes
+                    </div>
+                    <div>
+                        <label class="text-sm font-medium text-gray-700">Agregado (restore/max en bytes/seg):</label>
+                        <input type="text" id="addAggregateClass1" placeholder="64000/64000" 
+                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono">
+                        <p class="text-xs text-gray-500 mt-1">Ej: 64000/64000 = 512 Kbps</p>
+                    </div>
+                </div>
+                
+                <!-- Clase 2 -->
+                <div id="addClass2Params" class="hidden space-y-3">
+                    <div class="bg-blue-50 p-3 rounded border border-blue-200 text-sm text-gray-700">
+                        <strong>Clase 2:</strong> Bucket agregado + 255 buckets individuales por host
+                    </div>
+                    <div>
+                        <label class="text-sm font-medium text-gray-700">Agregado (restore/max):</label>
+                        <input type="text" id="addAggregateClass2" placeholder="64000/64000" 
+                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono">
+                    </div>
+                    <div>
+                        <label class="text-sm font-medium text-gray-700">Individual por host (restore/max):</label>
+                        <input type="text" id="addIndividualClass2" placeholder="16000/64000" 
+                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono">
+                        <p class="text-xs text-gray-500 mt-1">Usa -1/-1 para deshabilitar este bucket</p>
+                    </div>
+                </div>
+                
+                <!-- Clase 3/4 -->
+                <div id="addClass3Params" class="hidden space-y-3">
+                    <div class="bg-blue-50 p-3 rounded border border-blue-200 text-sm text-gray-700">
+                        <strong id="addClass3Title">Clase 3:</strong> <span id="addClass3Desc">Buckets por subred + por host</span>
+                    </div>
+                    <div>
+                        <label class="text-sm font-medium text-gray-700">Agregado (restore/max):</label>
+                        <input type="text" id="addAggregateClass3" placeholder="64000/64000" 
+                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono">
+                    </div>
+                    <div>
+                        <label class="text-sm font-medium text-gray-700">Por red (restore/max):</label>
+                        <input type="text" id="addNetworkClass3" placeholder="8000/64000" 
+                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono">
+                        <p class="text-xs text-gray-500 mt-1">Usa -1/-1 para deshabilitar</p>
+                    </div>
+                    <div>
+                        <label class="text-sm font-medium text-gray-700">Individual por host (restore/max):</label>
+                        <input type="text" id="addIndividualClass3" placeholder="2000/16000" 
+                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono">
+                    </div>
+                </div>
+                
+                <!-- Clase 5 -->
+                <div id="addClass5Params" class="hidden space-y-3">
+                    <div class="bg-blue-50 p-3 rounded border border-blue-200 text-sm text-gray-700">
+                        <strong>Clase 5:</strong> Basado en tags de external_acl_type (un bucket por tag)
+                    </div>
+                    <div>
+                        <label class="text-sm font-medium text-gray-700">Parámetros por tag (restore/max):</label>
+                        <input type="text" id="addTagClass5" placeholder="16000/32000" 
+                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono">
+                    </div>
+                </div>
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Reglas de Acceso (ACLs):</label>
+                <div id="addAccessRules" class="space-y-2">
+                    <!-- Las reglas se agregarán dinámicamente -->
+                </div>
+                <button type="button" onclick="addAccessRule('add')" 
+                        class="mt-2 text-blue-600 hover:text-blue-800 text-sm font-medium">
+                    <i class="fas fa-plus-circle mr-1"></i>Agregar regla de acceso
+                </button>
+            </div>
+            
+            <div class="flex space-x-2 justify-end mt-6 pt-4 border-t">
+                <button type="button" onclick="closeAddModal()" 
+                        class="px-5 py-2 bg-gray-300 hover:bg-gray-400 text-gray-800 rounded-lg transition-colors font-medium">
+                    Cancelar
+                </button>
+                <button type="submit" 
+                        class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors font-medium">
+                    <i class="fas fa-save mr-2"></i>Crear Pool
+                </button>
+            </div>
+        </form>
+    </div>
+</div>
+
+<!-- Edit Modal -->
+<div id="editModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
+    <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
+        <h3 class="text-2xl font-bold text-gray-800 mb-4">
+            <i class="fas fa-edit text-blue-600 mr-2"></i>Editar Delay Pool
+        </h3>
+        <form id="editForm" method="POST" action="/admin/delay-pools/edit">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
+            <input type="hidden" name="pool_number" id="editPoolNumber">
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Número de Pool:</label>
+                <input type="text" id="editPoolNumberDisplay" disabled
+                       class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100 text-gray-600">
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Clase de Pool:</label>
+                <select name="pool_class" id="editPoolClass" onchange="updateParametersHelp('edit')"
+                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
+                    <option value="1">Clase 1 - Bucket único agregado</option>
+                    <option value="2">Clase 2 - Agregado + por host (/24)</option>
+                    <option value="3">Clase 3 - Agregado + red + por host (/16)</option>
+                    <option value="4">Clase 4 - Como clase 3 + por usuario</option>
+                    <option value="5">Clase 5 - Basado en tags</option>
+                </select>
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Parámetros:</label>
+                <textarea name="parameters" id="editParameters" rows="2" 
+                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono text-sm" 
+                          required placeholder="64000/64000 -1/-1 16000/64000"></textarea>
+                <p class="text-xs text-gray-500 mt-1" id="editParametersHelp">Formato: restore/max (bytes/seg)</p>
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Reglas de Acceso:</label>
+                <div id="editAccessRules" class="space-y-2">
+                    <!-- Se llenarán dinámicamente -->
+                </div>
+                <button type="button" onclick="addAccessRule('edit')" 
+                        class="mt-2 text-blue-600 hover:text-blue-800 text-sm font-medium">
+                    <i class="fas fa-plus-circle mr-1"></i>Agregar regla de acceso
+                </button>
+            </div>
+            
+            <div class="flex space-x-2 justify-end mt-6 pt-4 border-t">
+                <button type="button" onclick="closeEditModal()" 
+                        class="px-5 py-2 bg-gray-300 hover:bg-gray-400 text-gray-800 rounded-lg transition-colors font-medium">
+                    Cancelar
+                </button>
+                <button type="submit" 
+                        class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors font-medium">
+                    <i class="fas fa-save mr-2"></i>Guardar Cambios
+                </button>
+            </div>
+        </form>
+    </div>
 </div>
+
+<script>
+let addAccessRuleCounter = 0;
+let editAccessRuleCounter = 0;
+
+function showAddModal() {
+    document.getElementById('addModal').classList.remove('hidden');
+    document.getElementById('addForm').reset();
+    document.getElementById('addAccessRules').innerHTML = '';
+    document.getElementById('addParametersSection').classList.add('hidden');
+    addAccessRuleCounter = 0;
+}
+
+function closeAddModal() {
+    document.getElementById('addModal').classList.add('hidden');
+}
+
+function editPool(poolNumber, poolClass, parameters, accessRules) {
+    document.getElementById('editPoolNumber').value = poolNumber;
+    document.getElementById('editPoolNumberDisplay').value = 'Pool #' + poolNumber;
+    document.getElementById('editPoolClass').value = poolClass;
+    document.getElementById('editParameters').value = parameters || '';
+    
+    // Update parameters help text
+    updateParametersHelp('edit');
+    
+    // Fill access rules
+    const rulesContainer = document.getElementById('editAccessRules');
+    rulesContainer.innerHTML = '';
+    editAccessRuleCounter = 0;
+    
+    if (accessRules && accessRules.length > 0) {
+        accessRules.forEach(rule => {
+            addAccessRule('edit', rule.action, rule.acl);
+        });
+    }
+    
+    document.getElementById('editModal').classList.remove('hidden');
+}
+
+function closeEditModal() {
+    document.getElementById('editModal').classList.add('hidden');
+}
+
+function updateParametersHelp(mode) {
+    const classSelect = document.getElementById(mode + 'PoolClass');
+    const selectedClass = classSelect.value;
+    
+    if (mode === 'add') {
+        // Hide all parameter sections
+        document.querySelectorAll('[id^="addClass"]').forEach(el => {
+            if (el.id.includes('Params')) el.classList.add('hidden');
+        });
+        
+        // Show parameters section
+        const paramsSection = document.getElementById('addParametersSection');
+        if (selectedClass) {
+            paramsSection.classList.remove('hidden');
+            
+            // Show specific class parameters
+            if (selectedClass === '1') {
+                document.getElementById('addClass1Params').classList.remove('hidden');
+            } else if (selectedClass === '2') {
+                document.getElementById('addClass2Params').classList.remove('hidden');
+            } else if (selectedClass === '3' || selectedClass === '4') {
+                document.getElementById('addClass3Params').classList.remove('hidden');
+                if (selectedClass === '4') {
+                    document.getElementById('addClass3Title').textContent = 'Clase 4:';
+                    document.getElementById('addClass3Desc').textContent = 'Buckets por subred + por host + por usuario autenticado';
+                } else {
+                    document.getElementById('addClass3Title').textContent = 'Clase 3:';
+                    document.getElementById('addClass3Desc').textContent = 'Buckets por subred + por host';
+                }
+            } else if (selectedClass === '5') {
+                document.getElementById('addClass5Params').classList.remove('hidden');
+            }
+        } else {
+            paramsSection.classList.add('hidden');
+        }
+    } else {
+        // Update edit help text
+        const helpText = document.getElementById('editParametersHelp');
+        if (selectedClass === '1') {
+            helpText.textContent = 'Formato: aggregate_restore/aggregate_max';
+        } else if (selectedClass === '2') {
+            helpText.textContent = 'Formato: aggregate_restore/aggregate_max individual_restore/individual_max';
+        } else if (selectedClass === '3' || selectedClass === '4') {
+            helpText.textContent = 'Formato: aggregate_restore/aggregate_max network_restore/network_max individual_restore/individual_max';
+        } else if (selectedClass === '5') {
+            helpText.textContent = 'Formato: tag_restore/tag_max';
+        }
+    }
+}
+
+function addAccessRule(mode, action = 'allow', acl = '') {
+    const container = document.getElementById(mode + 'AccessRules');
+    const counter = mode === 'add' ? addAccessRuleCounter++ : editAccessRuleCounter++;
+    
+    const ruleDiv = document.createElement('div');
+    ruleDiv.className = 'flex items-center space-x-2 bg-gray-50 p-2 rounded border border-gray-200';
+    ruleDiv.id = mode + 'AccessRule' + counter;
+    
+    ruleDiv.innerHTML = `
+        <select name="access_action[]" class="px-3 py-2 border border-gray-300 rounded-lg text-sm">
+            <option value="allow" ${action === 'allow' ? 'selected' : ''}>allow</option>
+            <option value="deny" ${action === 'deny' ? 'selected' : ''}>deny</option>
+        </select>
+        <input type="text" name="access_acl[]" value="${acl}" placeholder="ACL names (ej: students !local)" 
+               class="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono">
+        <button type="button" onclick="removeAccessRule('${mode}', ${counter})" 
+                class="text-red-600 hover:text-red-800 p-2">
+            <i class="fas fa-times"></i>
+        </button>
+    `;
+    
+    container.appendChild(ruleDiv);
+}
+
+function removeAccessRule(mode, counter) {
+    const ruleDiv = document.getElementById(mode + 'AccessRule' + counter);
+    if (ruleDiv) {
+        ruleDiv.remove();
+    }
+}
+
+function deletePool(poolNumber) {
+    if (confirm('¿Estás seguro de que quieres eliminar el Delay Pool #' + poolNumber + '?\n\nEsto eliminará todas las configuraciones asociadas (clase, parámetros y reglas de acceso).')) {
+        const form = document.createElement('form');
+        form.method = 'POST';
+        form.action = '/admin/delay-pools/delete';
+        
+        const poolInput = document.createElement('input');
+        poolInput.type = 'hidden';
+        poolInput.name = 'pool_number';
+        poolInput.value = poolNumber;
+        
+        const csrfInput = document.createElement('input');
+        csrfInput.type = 'hidden';
+        csrfInput.name = 'csrf_token';
+        csrfInput.value = '{{ csrf_token() }}';
+        
+        form.appendChild(poolInput);
+        form.appendChild(csrfInput);
+        document.body.appendChild(form);
+        form.submit();
+    }
+}
+
+// Form submission handler for add form
+document.getElementById('addForm').addEventListener('submit', function(e) {
+    e.preventDefault();
+    
+    const formData = new FormData(this);
+    const poolClass = formData.get('pool_class');
+    
+    // Build parameters string based on class
+    let parameters = '';
+    if (poolClass === '1') {
+        parameters = document.getElementById('addAggregateClass1').value;
+    } else if (poolClass === '2') {
+        const agg = document.getElementById('addAggregateClass2').value;
+        const ind = document.getElementById('addIndividualClass2').value;
+        parameters = `${agg} ${ind}`;
+    } else if (poolClass === '3' || poolClass === '4') {
+        const agg = document.getElementById('addAggregateClass3').value;
+        const net = document.getElementById('addNetworkClass3').value;
+        const ind = document.getElementById('addIndividualClass3').value;
+        parameters = `${agg} ${net} ${ind}`;
+    } else if (poolClass === '5') {
+        parameters = document.getElementById('addTagClass5').value;
+    }
+    
+    // Validate parameters
+    if (!parameters.trim()) {
+        alert('Por favor completa los parámetros de velocidad');
+        return;
+    }
+    
+    // Add parameters to form
+    const paramsInput = document.createElement('input');
+    paramsInput.type = 'hidden';
+    paramsInput.name = 'parameters';
+    paramsInput.value = parameters.trim();
+    this.appendChild(paramsInput);
+    
+    this.submit();
+});
+</script>
 {% endblock %}

+ 431 - 13
templates/admin/http_access.html

@@ -2,34 +2,452 @@
 
 {% block content %}
 <div class="bg-white rounded-lg shadow-lg p-4 sm:p-6">
-    <h2 class="text-xl sm:text-2xl font-bold text-gray-800 mb-4 sm:mb-6">Reglas de Acceso HTTP</h2>
+    <div class="flex justify-between items-center mb-4 sm:mb-6">
+        <div>
+            <h2 class="text-xl sm:text-2xl font-bold text-gray-800">Reglas de Acceso HTTP</h2>
+            <p class="text-sm text-gray-600 mt-1">Las reglas se evalúan en orden. La primera coincidencia determina el acceso.</p>
+        </div>
+        <button onclick="showAddModal()" class="bg-blue-600 hover:bg-blue-700 text-white font-semibold px-4 py-2 rounded-lg shadow-md transition-colors">
+            <i class="fas fa-plus mr-2"></i>Agregar Regla
+        </button>
+    </div>
     
-    <div class="space-y-3">
+    {% if rules %}
+    <div class="mb-4 bg-blue-50 border border-blue-200 rounded-lg p-4">
+        <div class="flex items-start">
+            <i class="fas fa-info-circle text-blue-600 mt-1 mr-3"></i>
+            <div class="text-sm text-gray-700">
+                <p class="font-semibold text-gray-800 mb-1">Importante sobre el orden:</p>
+                <ul class="list-disc list-inside space-y-1 ml-2">
+                    <li>Las reglas se procesan de arriba hacia abajo</li>
+                    <li>La primera regla que coincida se aplica (allow o deny)</li>
+                    <li>Si ninguna regla coincide, se aplica el comportamiento contrario a la última regla</li>
+                    <li>Se recomienda terminar con "deny all" para evitar confusión</li>
+                </ul>
+            </div>
+        </div>
+    </div>
+
+    <div class="space-y-2">
         {% for rule in rules %}
-        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 bg-gray-50 rounded-lg gap-2">
-            <div class="flex items-center space-x-2 sm:space-x-4 flex-1 min-w-0">
-                <div class="flex-shrink-0">
-                    {% if 'allow' in rule %}
-                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
-                            ALLOW
+        <div class="flex flex-col sm:flex-row items-start justify-between p-4 bg-gradient-to-r from-gray-50 to-white rounded-lg border border-gray-200 hover:border-gray-300 transition-all gap-3">
+            <div class="flex items-start space-x-3 flex-1 min-w-0 w-full">
+                <div class="flex items-center space-x-2 flex-shrink-0">
+                    <span class="text-xs font-mono text-gray-400">#{{ loop.index }}</span>
+                    {% if rule.action == 'allow' %}
+                        <span class="inline-flex px-3 py-1 text-xs font-bold rounded-full bg-green-100 text-green-800 border border-green-300">
+                            <i class="fas fa-check mr-1"></i>ALLOW
                         </span>
                     {% else %}
-                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">
-                            DENY
+                        <span class="inline-flex px-3 py-1 text-xs font-bold rounded-full bg-red-100 text-red-800 border border-red-300">
+                            <i class="fas fa-times mr-1"></i>DENY
                         </span>
                     {% endif %}
                 </div>
-                <code class="text-xs sm:text-sm text-gray-700 break-all">{{ rule }}</code>
+                
+                <div class="flex-1 min-w-0">
+                    <div class="flex flex-wrap items-center gap-2">
+                        {% for acl in rule.acls %}
+                            {% if acl.startswith('!') %}
+                                <span class="inline-flex items-center px-2 py-1 rounded bg-orange-100 text-orange-800 text-xs font-mono border border-orange-300">
+                                    <i class="fas fa-exclamation-circle mr-1"></i>{{ acl }}
+                                </span>
+                            {% elif acl in ['localhost', 'manager', 'all'] %}
+                                <span class="inline-flex items-center px-2 py-1 rounded bg-purple-100 text-purple-800 text-xs font-mono border border-purple-300">
+                                    <i class="fas fa-star mr-1"></i>{{ acl }}
+                                </span>
+                            {% elif 'ports' in acl.lower() %}
+                                <span class="inline-flex items-center px-2 py-1 rounded bg-blue-100 text-blue-800 text-xs font-mono border border-blue-300">
+                                    <i class="fas fa-plug mr-1"></i>{{ acl }}
+                                </span>
+                            {% elif acl == 'CONNECT' %}
+                                <span class="inline-flex items-center px-2 py-1 rounded bg-indigo-100 text-indigo-800 text-xs font-mono border border-indigo-300">
+                                    <i class="fas fa-link mr-1"></i>{{ acl }}
+                                </span>
+                            {% else %}
+                                <span class="inline-flex items-center px-2 py-1 rounded bg-gray-100 text-gray-800 text-xs font-mono border border-gray-300">
+                                    {{ acl }}
+                                </span>
+                            {% endif %}
+                        {% endfor %}
+                    </div>
+                    
+                    {% if rule.description %}
+                    <p class="text-xs text-gray-500 mt-2 italic">
+                        <i class="fas fa-comment-alt mr-1"></i>{{ rule.description }}
+                    </p>
+                    {% endif %}
+                    
+                    {% if rule.is_negative %}
+                    <p class="text-xs text-orange-600 mt-1">
+                        <i class="fas fa-info-circle mr-1"></i>Contiene negación (!) - se aplica cuando NO coincide con la ACL
+                    </p>
+                    {% endif %}
+                </div>
             </div>
-            <div class="flex space-x-2 flex-shrink-0">\n                <button class="text-blue-600 hover:text-blue-900">
+            
+            <div class="flex space-x-2 flex-shrink-0 sm:ml-3">
+                <button onclick='moveRuleUp({{ loop.index0 }})' 
+                        class="text-gray-600 hover:text-gray-900 p-2 hover:bg-gray-100 rounded" 
+                        title="Mover arriba"
+                        {% if loop.first %}disabled class="opacity-30 cursor-not-allowed"{% endif %}>
+                    <i class="fas fa-arrow-up"></i>
+                </button>
+                <button onclick='moveRuleDown({{ loop.index0 }})' 
+                        class="text-gray-600 hover:text-gray-900 p-2 hover:bg-gray-100 rounded" 
+                        title="Mover abajo"
+                        {% if loop.last %}disabled class="opacity-30 cursor-not-allowed"{% endif %}>
+                    <i class="fas fa-arrow-down"></i>
+                </button>
+                <button onclick='editRule({{ loop.index0 }}, "{{ rule.action }}", "{{ rule.acl_string }}", "{{ rule.description }}")' 
+                        class="text-blue-600 hover:text-blue-900 p-2 hover:bg-blue-100 rounded" 
+                        title="Editar">
                     <i class="fas fa-edit"></i>
                 </button>
-                <button class="text-red-600 hover:text-red-900">
+                <button onclick='deleteRule({{ loop.index0 }}, "{{ rule.action }} {{ rule.acl_string }}")' 
+                        class="text-red-600 hover:text-red-900 p-2 hover:bg-red-100 rounded" 
+                        title="Eliminar">
                     <i class="fas fa-trash"></i>
                 </button>
             </div>
         </div>
         {% endfor %}
     </div>
+    {% else %}
+    <div class="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
+        <i class="fas fa-shield-alt text-6xl text-gray-300 mb-4"></i>
+        <p class="text-gray-500 text-lg font-medium">No hay reglas HTTP access configuradas</p>
+        <p class="text-gray-400 text-sm mt-2">⚠️ Sin reglas, el acceso será DENEGADO por defecto</p>
+        <button onclick="showAddModal()" class="mt-4 bg-blue-600 hover:bg-blue-700 text-white font-semibold px-6 py-2 rounded-lg shadow-md transition-colors">
+            <i class="fas fa-plus mr-2"></i>Crear primera regla
+        </button>
+    </div>
+    {% endif %}
+</div>
+
+<!-- Add Modal -->
+<div id="addModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
+    <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
+        <h3 class="text-2xl font-bold text-gray-800 mb-4">
+            <i class="fas fa-plus-circle text-blue-600 mr-2"></i>Agregar Regla HTTP Access
+        </h3>
+        <form id="addForm" method="POST" action="/admin/http-access/add">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Acción:</label>
+                <div class="grid grid-cols-2 gap-3">
+                    <label class="flex items-center justify-center p-4 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-green-500 hover:bg-green-50 transition-all">
+                        <input type="radio" name="action" value="allow" class="mr-3 w-4 h-4" required>
+                        <div class="text-center">
+                            <i class="fas fa-check-circle text-green-600 text-2xl mb-1"></i>
+                            <p class="font-semibold text-gray-800">ALLOW</p>
+                            <p class="text-xs text-gray-600">Permitir acceso</p>
+                        </div>
+                    </label>
+                    <label class="flex items-center justify-center p-4 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-red-500 hover:bg-red-50 transition-all">
+                        <input type="radio" name="action" value="deny" class="mr-3 w-4 h-4" required>
+                        <div class="text-center">
+                            <i class="fas fa-times-circle text-red-600 text-2xl mb-1"></i>
+                            <p class="font-semibold text-gray-800">DENY</p>
+                            <p class="text-xs text-gray-600">Denegar acceso</p>
+                        </div>
+                    </label>
+                </div>
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">ACLs:</label>
+                <div id="addAclsList" class="space-y-2 mb-2">
+                    <!-- ACLs se agregarán dinámicamente -->
+                </div>
+                <button type="button" onclick="addAclInput('add')" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
+                    <i class="fas fa-plus-circle mr-1"></i>Agregar ACL
+                </button>
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">
+                    <i class="fas fa-star text-yellow-500 mr-1"></i>ACLs Comunes (opcional):
+                </label>
+                <div class="grid grid-cols-2 sm:grid-cols-3 gap-2">
+                    <button type="button" onclick="addCommonAcl('add', 'localhost')" class="px-3 py-2 bg-purple-100 hover:bg-purple-200 text-purple-800 rounded text-sm border border-purple-300">
+                        localhost
+                    </button>
+                    <button type="button" onclick="addCommonAcl('add', 'manager')" class="px-3 py-2 bg-purple-100 hover:bg-purple-200 text-purple-800 rounded text-sm border border-purple-300">
+                        manager
+                    </button>
+                    <button type="button" onclick="addCommonAcl('add', 'all')" class="px-3 py-2 bg-purple-100 hover:bg-purple-200 text-purple-800 rounded text-sm border border-purple-300">
+                        all
+                    </button>
+                    <button type="button" onclick="addCommonAcl('add', '!Safe_ports')" class="px-3 py-2 bg-orange-100 hover:bg-orange-200 text-orange-800 rounded text-sm border border-orange-300">
+                        !Safe_ports
+                    </button>
+                    <button type="button" onclick="addCommonAcl('add', '!SSL_ports')" class="px-3 py-2 bg-orange-100 hover:bg-orange-200 text-orange-800 rounded text-sm border border-orange-300">
+                        !SSL_ports
+                    </button>
+                    <button type="button" onclick="addCommonAcl('add', 'CONNECT')" class="px-3 py-2 bg-indigo-100 hover:bg-indigo-200 text-indigo-800 rounded text-sm border border-indigo-300">
+                        CONNECT
+                    </button>
+                </div>
+                <p class="text-xs text-gray-500 mt-2">
+                    <i class="fas fa-info-circle mr-1"></i>Haz clic en estas ACLs predefinidas para agregarlas rápidamente
+                </p>
+            </div>
+            
+            <div class="mb-4 bg-yellow-50 border border-yellow-200 rounded-lg p-3">
+                <p class="text-sm text-gray-700">
+                    <i class="fas fa-lightbulb text-yellow-600 mr-2"></i>
+                    <strong>Tip:</strong> Usa <code class="bg-white px-1 rounded">!</code> antes del nombre de una ACL para negación.
+                    Ej: <code class="bg-white px-1 rounded">!Safe_ports</code> coincide cuando NO es un puerto seguro.
+                </p>
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Descripción (opcional):</label>
+                <input type="text" name="description" placeholder="Ej: Permitir acceso desde la red local"
+                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
+                <p class="text-xs text-gray-500 mt-1">Se agregará como comentario antes de la regla</p>
+            </div>
+            
+            <div class="flex space-x-2 justify-end mt-6 pt-4 border-t">
+                <button type="button" onclick="closeAddModal()" class="px-5 py-2 bg-gray-300 hover:bg-gray-400 text-gray-800 rounded-lg transition-colors font-medium">
+                    Cancelar
+                </button>
+                <button type="submit" class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors font-medium">
+                    <i class="fas fa-save mr-2"></i>Crear Regla
+                </button>
+            </div>
+        </form>
+    </div>
+</div>
+
+<!-- Edit Modal -->
+<div id="editModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
+    <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
+        <h3 class="text-2xl font-bold text-gray-800 mb-4">
+            <i class="fas fa-edit text-blue-600 mr-2"></i>Editar Regla HTTP Access
+        </h3>
+        <form id="editForm" method="POST" action="/admin/http-access/edit">
+            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
+            <input type="hidden" name="index" id="editIndex">
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Acción:</label>
+                <div class="grid grid-cols-2 gap-3">
+                    <label class="flex items-center justify-center p-4 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-green-500 hover:bg-green-50 transition-all">
+                        <input type="radio" name="action" value="allow" id="editActionAllow" class="mr-3 w-4 h-4" required>
+                        <div class="text-center">
+                            <i class="fas fa-check-circle text-green-600 text-2xl mb-1"></i>
+                            <p class="font-semibold text-gray-800">ALLOW</p>
+                        </div>
+                    </label>
+                    <label class="flex items-center justify-center p-4 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-red-500 hover:bg-red-50 transition-all">
+                        <input type="radio" name="action" value="deny" id="editActionDeny" class="mr-3 w-4 h-4" required>
+                        <div class="text-center">
+                            <i class="fas fa-times-circle text-red-600 text-2xl mb-1"></i>
+                            <p class="font-semibold text-gray-800">DENY</p>
+                        </div>
+                    </label>
+                </div>
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">ACLs:</label>
+                <div id="editAclsList" class="space-y-2 mb-2">
+                    <!-- ACLs se llenarán dinámicamente -->
+                </div>
+                <button type="button" onclick="addAclInput('edit')" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
+                    <i class="fas fa-plus-circle mr-1"></i>Agregar ACL
+                </button>
+            </div>
+            
+            <div class="mb-4">
+                <label class="block text-gray-700 font-semibold mb-2">Descripción (opcional):</label>
+                <input type="text" name="description" id="editDescription" placeholder="Ej: Permitir acceso desde la red local"
+                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
+            </div>
+            
+            <div class="flex space-x-2 justify-end mt-6 pt-4 border-t">
+                <button type="button" onclick="closeEditModal()" class="px-5 py-2 bg-gray-300 hover:bg-gray-400 text-gray-800 rounded-lg transition-colors font-medium">
+                    Cancelar
+                </button>
+                <button type="submit" class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors font-medium">
+                    <i class="fas fa-save mr-2"></i>Guardar Cambios
+                </button>
+            </div>
+        </form>
+    </div>
 </div>
+
+<script>
+let addAclCounter = 0;
+let editAclCounter = 0;
+
+function showAddModal() {
+    document.getElementById('addModal').classList.remove('hidden');
+    document.getElementById('addForm').reset();
+    document.getElementById('addAclsList').innerHTML = '';
+    addAclCounter = 0;
+    // Add one initial ACL input
+    addAclInput('add');
+}
+
+function closeAddModal() {
+    document.getElementById('addModal').classList.add('hidden');
+}
+
+function editRule(index, action, aclString, description) {
+    document.getElementById('editIndex').value = index;
+    
+    // Set action radio button
+    if (action === 'allow') {
+        document.getElementById('editActionAllow').checked = true;
+    } else {
+        document.getElementById('editActionDeny').checked = true;
+    }
+    
+    // Set description
+    document.getElementById('editDescription').value = description || '';
+    
+    // Parse ACLs and fill inputs
+    const acls = aclString.split(' ');
+    const aclsContainer = document.getElementById('editAclsList');
+    aclsContainer.innerHTML = '';
+    editAclCounter = 0;
+    
+    acls.forEach(acl => {
+        if (acl.trim()) {
+            addAclInput('edit', acl.trim());
+        }
+    });
+    
+    // If no ACLs were added, add one empty input
+    if (editAclCounter === 0) {
+        addAclInput('edit');
+    }
+    
+    document.getElementById('editModal').classList.remove('hidden');
+}
+
+function closeEditModal() {
+    document.getElementById('editModal').classList.add('hidden');
+}
+
+function addAclInput(mode, value = '') {
+    const container = document.getElementById(mode + 'AclsList');
+    const counter = mode === 'add' ? addAclCounter++ : editAclCounter++;
+    
+    const aclDiv = document.createElement('div');
+    aclDiv.className = 'flex items-center space-x-2';
+    aclDiv.id = mode + 'Acl' + counter;
+    
+    aclDiv.innerHTML = `
+        <input type="text" name="acls[]" value="${value}" placeholder="Nombre de ACL (ej: localhost, !Safe_ports)" 
+               class="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-blue-500" required>
+        <button type="button" onclick="removeAclInput('${mode}', ${counter})" 
+                class="text-red-600 hover:text-red-800 p-2">
+            <i class="fas fa-times"></i>
+        </button>
+    `;
+    
+    container.appendChild(aclDiv);
+}
+
+function removeAclInput(mode, counter) {
+    const aclDiv = document.getElementById(mode + 'Acl' + counter);
+    if (aclDiv) {
+        // Only allow removal if there's more than one ACL input
+        const container = document.getElementById(mode + 'AclsList');
+        if (container.children.length > 1) {
+            aclDiv.remove();
+        } else {
+            alert('Debe haber al menos una ACL en la regla');
+        }
+    }
+}
+
+function addCommonAcl(mode, aclName) {
+    addAclInput(mode, aclName);
+}
+
+function deleteRule(index, rule) {
+    if (confirm('¿Estás seguro de que quieres eliminar la regla:\nhttp_access ' + rule + '?\n\nEsto puede afectar el acceso al proxy.')) {
+        const form = document.createElement('form');
+        form.method = 'POST';
+        form.action = '/admin/http-access/delete';
+        
+        const indexInput = document.createElement('input');
+        indexInput.type = 'hidden';
+        indexInput.name = 'index';
+        indexInput.value = index;
+        
+        const csrfInput = document.createElement('input');
+        csrfInput.type = 'hidden';
+        csrfInput.name = 'csrf_token';
+        csrfInput.value = '{{ csrf_token() }}';
+        
+        form.appendChild(indexInput);
+        form.appendChild(csrfInput);
+        document.body.appendChild(form);
+        form.submit();
+    }
+}
+
+function moveRuleUp(index) {
+    if (index === 0) return;
+    
+    const form = document.createElement('form');
+    form.method = 'POST';
+    form.action = '/admin/http-access/move';
+    
+    const indexInput = document.createElement('input');
+    indexInput.type = 'hidden';
+    indexInput.name = 'index';
+    indexInput.value = index;
+    
+    const directionInput = document.createElement('input');
+    directionInput.type = 'hidden';
+    directionInput.name = 'direction';
+    directionInput.value = 'up';
+    
+    const csrfInput = document.createElement('input');
+    csrfInput.type = 'hidden';
+    csrfInput.name = 'csrf_token';
+    csrfInput.value = '{{ csrf_token() }}';
+    
+    form.appendChild(indexInput);
+    form.appendChild(directionInput);
+    form.appendChild(csrfInput);
+    document.body.appendChild(form);
+    form.submit();
+}
+
+function moveRuleDown(index) {
+    const form = document.createElement('form');
+    form.method = 'POST';
+    form.action = '/admin/http-access/move';
+    
+    const indexInput = document.createElement('input');
+    indexInput.type = 'hidden';
+    indexInput.name = 'index';
+    indexInput.value = index;
+    
+    const directionInput = document.createElement('input');
+    directionInput.type = 'hidden';
+    directionInput.name = 'direction';
+    directionInput.value = 'down';
+    
+    const csrfInput = document.createElement('input');
+    csrfInput.type = 'hidden';
+    csrfInput.name = 'csrf_token';
+    csrfInput.value = '{{ csrf_token() }}';
+    
+    form.appendChild(indexInput);
+    form.appendChild(directionInput);
+    form.appendChild(csrfInput);
+    document.body.appendChild(form);
+    form.submit();
+}
+</script>
 {% endblock %}

+ 233 - 0
templates/admin/split_config.html

@@ -0,0 +1,233 @@
+{% extends "admin/base.html" %}
+
+{% block title %}Dividir Configuración Squid{% endblock %}
+
+{% block content %}
+<div class="max-w-7xl mx-auto">
+    <!-- Header -->
+    <div class="bg-gradient-to-r from-blue-600 to-blue-700 rounded-xl shadow-lg p-6 mb-6 text-white">
+        <div class="flex items-center space-x-4">
+            <i class="fas fa-code-branch text-4xl"></i>
+            <div>
+                <h2 class="text-3xl font-bold">Dividir Configuración Squid</h2>
+                <p class="text-blue-100 mt-1">Modulariza tu archivo squid.conf para una gestión más sencilla</p>
+            </div>
+        </div>
+    </div>
+
+    <!-- Info Cards -->
+    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
+        <div class="bg-white rounded-lg shadow-md p-6">
+            <div class="flex items-center space-x-3">
+                <i class="fas fa-file-code text-blue-600 text-2xl"></i>
+                <div>
+                    <p class="text-gray-600 text-sm">Archivo de entrada</p>
+                    <p class="font-semibold text-gray-800 text-sm">{{ input_file }}</p>
+                </div>
+            </div>
+        </div>
+        <div class="bg-white rounded-lg shadow-md p-6">
+            <div class="flex items-center space-x-3">
+                <i class="fas fa-folder text-emerald-600 text-2xl"></i>
+                <div>
+                    <p class="text-gray-600 text-sm">Directorio de salida</p>
+                    <p class="font-semibold text-gray-800 text-sm">{{ output_dir }}</p>
+                </div>
+            </div>
+        </div>
+        <div class="bg-white rounded-lg shadow-md p-6">
+            <div class="flex items-center space-x-3">
+                <i class="fas fa-layer-group text-amber-600 text-2xl"></i>
+                <div>
+                    <p class="text-gray-600 text-sm">Estado</p>
+                    {% if output_exists %}
+                        <p class="font-semibold text-emerald-600 text-sm">{{ files_count }} archivos generados</p>
+                    {% else %}
+                        <p class="font-semibold text-gray-600 text-sm">No dividido aún</p>
+                    {% endif %}
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <!-- Description -->
+    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
+        <h3 class="text-xl font-bold text-gray-800 mb-3 flex items-center">
+            <i class="fas fa-info-circle text-blue-600 mr-2"></i>
+            ¿Qué hace esta funcionalidad?
+        </h3>
+        <p class="text-gray-700 mb-4">
+            Esta herramienta divide tu archivo monolítico <code class="bg-gray-100 px-2 py-1 rounded">squid.conf</code> 
+            en múltiples archivos modulares organizados por categorías. Esto facilita:
+        </p>
+        <ul class="list-disc list-inside text-gray-700 space-y-2 ml-4">
+            <li>Gestión y mantenimiento más sencillo de la configuración</li>
+            <li>Mejor organización de directivas por funcionalidad</li>
+            <li>Facilita la edición desde la interfaz web</li>
+            <li>Reduce errores al editar configuraciones complejas</li>
+        </ul>
+    </div>
+
+    <!-- Files to be generated -->
+    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
+        <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
+            <i class="fas fa-list text-blue-600 mr-2"></i>
+            Archivos que se generarán
+        </h3>
+        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
+            {% for filename, description in split_info.items() %}
+                <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
+                    <div class="flex items-start space-x-3">
+                        <i class="fas fa-file-alt text-blue-500 mt-1"></i>
+                        <div class="flex-1">
+                            <p class="font-semibold text-gray-800 text-sm">{{ filename }}</p>
+                            <p class="text-gray-600 text-xs mt-1">{{ description }}</p>
+                        </div>
+                    </div>
+                </div>
+            {% endfor %}
+        </div>
+    </div>
+
+    <!-- Actions -->
+    <div class="bg-white rounded-lg shadow-md p-6">
+        <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
+            <i class="fas fa-cogs text-blue-600 mr-2"></i>
+            Acciones
+        </h3>
+        
+        <div class="space-y-4">
+            <!-- Strict mode toggle -->
+            <div class="flex items-center space-x-3 p-4 bg-gray-50 rounded-lg">
+                <input type="checkbox" id="strictMode" class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500">
+                <div class="flex-1">
+                    <label for="strictMode" class="font-medium text-gray-800 cursor-pointer">Modo estricto</label>
+                    <p class="text-sm text-gray-600">Abortar si se encuentran directivas desconocidas</p>
+                </div>
+            </div>
+
+            <!-- Action buttons -->
+            <div class="flex flex-col sm:flex-row gap-4">
+                <button onclick="executeSplit()" class="flex-1 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold px-6 py-3 rounded-lg shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-200 flex items-center justify-center">
+                    <i class="fas fa-code-branch mr-2"></i>
+                    Dividir Configuración
+                </button>
+                
+                {% if output_exists %}
+                <a href="{{ url_for('admin.view_config') }}" class="flex-1 bg-gradient-to-r from-emerald-600 to-emerald-700 hover:from-emerald-700 hover:to-emerald-800 text-white font-semibold px-6 py-3 rounded-lg shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-200 flex items-center justify-center text-center">
+                    <i class="fas fa-folder-open mr-2"></i>
+                    Ver Archivos Generados
+                </a>
+                {% endif %}
+            </div>
+        </div>
+
+        <!-- Warning -->
+        <div class="mt-6 bg-amber-50 border border-amber-200 rounded-lg p-4 flex items-start space-x-3">
+            <i class="fas fa-exclamation-triangle text-amber-600 text-xl mt-1"></i>
+            <div class="flex-1">
+                <p class="font-semibold text-amber-800">Advertencia</p>
+                <p class="text-sm text-amber-700 mt-1">
+                    Esta operación creará múltiples archivos en el directorio <code class="bg-amber-100 px-2 py-0.5 rounded">{{ output_dir }}</code>. 
+                    Si ya existen archivos en ese directorio, serán sobrescritos.
+                </p>
+            </div>
+        </div>
+    </div>
+
+    <!-- Results area (hidden by default) -->
+    <div id="resultsArea" class="hidden mt-6 bg-white rounded-lg shadow-md p-6">
+        <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
+            <i class="fas fa-check-circle text-emerald-600 mr-2"></i>
+            Resultados
+        </h3>
+        <div id="resultsContent" class="space-y-3"></div>
+    </div>
+</div>
+
+<!-- Toastr CSS -->
+<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
+<!-- jQuery (required for Toastr) -->
+<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
+<!-- Toastr JS -->
+<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
+
+<script>
+    // Configure toastr
+    toastr.options = {
+        closeButton: true,
+        progressBar: true,
+        positionClass: "toast-top-right",
+        timeOut: "5000",
+    };
+
+    // Get CSRF token
+    function getCsrfToken() {
+        return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
+    }
+
+    async function executeSplit() {
+        const strictMode = document.getElementById('strictMode').checked;
+        const resultsArea = document.getElementById('resultsArea');
+        const resultsContent = document.getElementById('resultsContent');
+
+        try {
+            // Show loading toast
+            toastr.info('Dividiendo configuración...', 'Procesando');
+
+            const response = await fetch('/admin/api/split-config', {
+                method: 'POST',
+                headers: {
+                    'Content-Type': 'application/json',
+                    'X-CSRFToken': getCsrfToken()
+                },
+                body: JSON.stringify({ strict: strictMode })
+            });
+
+            const data = await response.json();
+
+            if (data.status === 'success') {
+                toastr.success(data.message, 'Éxito');
+
+                // Show results
+                resultsArea.classList.remove('hidden');
+                resultsContent.innerHTML = `
+                    <div class="bg-emerald-50 border border-emerald-200 rounded-lg p-4">
+                        <p class="font-semibold text-emerald-800 mb-2">
+                            <i class="fas fa-check-circle mr-2"></i>
+                            Configuración dividida exitosamente
+                        </p>
+                        <p class="text-sm text-emerald-700">
+                            Se generaron <strong>${data.data.total_files}</strong> archivos en 
+                            <code class="bg-emerald-100 px-2 py-0.5 rounded">${data.data.output_dir}</code>
+                        </p>
+                    </div>
+                    <div class="mt-4">
+                        <p class="font-semibold text-gray-800 mb-2">Archivos generados:</p>
+                        <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
+                            ${Object.entries(data.data.files).map(([filename, lines]) => `
+                                <div class="flex justify-between items-center bg-gray-50 px-3 py-2 rounded">
+                                    <span class="text-sm text-gray-700">${filename}</span>
+                                    <span class="text-xs text-gray-500">${lines} líneas</span>
+                                </div>
+                            `).join('')}
+                        </div>
+                    </div>
+                `;
+
+                // Reload page after 3 seconds to update the stats
+                setTimeout(() => {
+                    window.location.reload();
+                }, 3000);
+            } else {
+                toastr.error(data.message || 'Error al dividir la configuración', 'Error');
+                resultsArea.classList.add('hidden');
+            }
+        } catch (error) {
+            console.error('Error:', error);
+            toastr.error('Error de conexión al dividir la configuración', 'Error');
+            resultsArea.classList.add('hidden');
+        }
+    }
+</script>
+{% endblock %}

+ 444 - 90
utils/admin.py

@@ -1,5 +1,8 @@
 import logging
 import os
+import shutil
+from datetime import datetime
+from typing import Optional
 
 from dotenv import load_dotenv
 
@@ -10,7 +13,7 @@ load_dotenv()
 # SQUID_CONFIG_PATH = os.getenv("SQUID_CONFIG_PATH", "/etc/squid/squid.conf")
 # ACL_FILES_DIR = os.getenv("ACL_FILES_DIR", "/etc/squid/acls")
 SQUID_CONFIG_PATH = "/etc/squid/squid.conf"
-ACL_FILES_DIR = "/etc/squid/acls"
+ACL_FILES_DIR = "/etc/squid/squid.d/"
 
 
 def validate_paths():
@@ -59,16 +62,19 @@ def validate_paths():
 
 
 class SquidConfigManager:
-    def __init__(self, config_path=SQUID_CONFIG_PATH):
+    def __init__(self, config_path=SQUID_CONFIG_PATH, config_dir=ACL_FILES_DIR):
         self.config_path = config_path
+        self.config_dir = config_dir
         self.config_content = ""
         self.is_valid = False
         self.errors = []
+        self.is_modular = False  # Flag to check if using modular configs
 
         self._validate_environment()
 
         if self.is_valid:
             self.load_config()
+            self._check_modular_config()
 
     def _validate_environment(self):
         self.errors = validate_paths()
@@ -143,70 +149,189 @@ class SquidConfigManager:
             logger.error("Cannot create backup: invalid environment")
             return False
 
-        """ try:
-            if not os.path.exists(BACKUP_DIR):
-                logger.error(f"Backup directory does not exist: {BACKUP_DIR}")
-                return False
-
-            if not os.access(BACKUP_DIR, os.W_OK):
-                logger.error(f"No write permissions in backup directory: {BACKUP_DIR}")
-                return False
-
-            if not os.path.exists(self.config_path):
-                logger.warning("No configuration file exists to backup")
-                return False
-
-            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
-            backup_filename = f"squid.conf.backup_{timestamp}"
-            backup_path = os.path.join(BACKUP_DIR, backup_filename)
-
-            shutil.copy2(self.config_path, backup_path)
-            logger.info(f"Backup created: {backup_path}")
-            return True
-
-        except PermissionError:
-            logger.error(f"No permissions to create backup in: {BACKUP_DIR}")
-            return False
-        except OSError as e:
-            logger.error(f"System error creating backup: {e}")
-            return False
-        except Exception as e:
-            logger.error(f"Unexpected error creating backup: {e}")
-            return False """
-
     def get_acls(self):
+        """
+        Parse ACL definitions with enhanced information.
+        Returns a list of ACL dictionaries with full details.
+        Format:
+        {
+            'id': 0,
+            'name': 'localnet',
+            'type': 'src',
+            'options': ['-i'],  # ACL options like -i, -n, -m
+            'values': ['10.0.0.0/8', '192.168.0.0/16'],  # List of values
+            'value_string': '10.0.0.0/8 192.168.0.0/16',  # Original value string
+            'is_predefined': False,  # True for Squid predefined ACLs
+            'is_slow': False,  # True for slow ACL types
+            'category': 'network',  # Category: network, time, auth, content, ssl, etc.
+            'description': 'RFC 1918 private networks',  # Human-readable description
+            'line_number': 5
+        }
+        """
         if not self.is_valid:
             logger.error("Cannot get ACLs: invalid environment")
             return []
 
-        if not self.config_content:
-            logger.warning("No configuration content available")
-            return []
+        # If using modular config, read from the ACLs specific file
+        if self.is_modular:
+            acl_content = self.read_modular_config("100_acls.conf")
+            if not acl_content:
+                logger.warning("Could not read modular ACL config, falling back to main config")
+                config_to_parse = self.config_content
+            else:
+                config_to_parse = acl_content
+        else:
+            if not self.config_content:
+                logger.warning("No configuration content available")
+                return []
+            config_to_parse = self.config_content
 
         try:
             acls = []
-            lines = self.config_content.split("\n")
+            lines = config_to_parse.split("\n")
             acl_index = 0
+            
+            # Predefined ACLs in Squid
+            predefined_acls = ['all', 'manager', 'localhost', 'to_localhost', 'to_linklocal', 'CONNECT']
+            
+            # ACL type metadata
+            acl_types_info = {
+                # Network ACLs
+                'src': {'category': 'network', 'slow': False, 'desc': 'Source IP address'},
+                'dst': {'category': 'network', 'slow': True, 'desc': 'Destination IP address'},
+                'localip': {'category': 'network', 'slow': False, 'desc': 'Local IP client connected to'},
+                'arp': {'category': 'network', 'slow': False, 'desc': 'MAC address (EUI-48)'},
+                'eui64': {'category': 'network', 'slow': False, 'desc': 'EUI-64 address'},
+                'client_connection_mark': {'category': 'network', 'slow': False, 'desc': 'CONNMARK of connection'},
+                
+                # Domain ACLs
+                'srcdomain': {'category': 'domain', 'slow': True, 'desc': 'Reverse DNS lookup of client IP'},
+                'dstdomain': {'category': 'domain', 'slow': False, 'desc': 'Destination domain from URL'},
+                'srcdom_regex': {'category': 'domain', 'slow': True, 'desc': 'Regex match on client name'},
+                'dstdom_regex': {'category': 'domain', 'slow': False, 'desc': 'Regex match on server domain'},
+                
+                # AS Number ACLs
+                'src_as': {'category': 'network', 'slow': False, 'desc': 'Source Autonomous System number'},
+                'dst_as': {'category': 'network', 'slow': False, 'desc': 'Destination AS number'},
+                
+                # Time ACLs
+                'time': {'category': 'time', 'slow': False, 'desc': 'Time of day and day of week'},
+                
+                # URL ACLs
+                'url_regex': {'category': 'url', 'slow': False, 'desc': 'Regex match on full URL'},
+                'urllogin': {'category': 'url', 'slow': False, 'desc': 'Regex match on URL login field'},
+                'urlpath_regex': {'category': 'url', 'slow': False, 'desc': 'Regex match on URL path'},
+                
+                # Port ACLs
+                'port': {'category': 'port', 'slow': False, 'desc': 'Destination TCP port'},
+                'localport': {'category': 'port', 'slow': False, 'desc': 'TCP port client connected to'},
+                'myportname': {'category': 'port', 'slow': False, 'desc': 'Port name from *_port directive'},
+                
+                # Protocol & Method ACLs
+                'proto': {'category': 'protocol', 'slow': False, 'desc': 'Request protocol (HTTP, FTP, etc)'},
+                'method': {'category': 'protocol', 'slow': False, 'desc': 'HTTP request method'},
+                'http_status': {'category': 'protocol', 'slow': False, 'desc': 'HTTP status code in reply'},
+                
+                # Header ACLs
+                'browser': {'category': 'content', 'slow': False, 'desc': 'User-Agent header pattern'},
+                'referer_regex': {'category': 'content', 'slow': False, 'desc': 'Referer header pattern'},
+                'req_header': {'category': 'content', 'slow': False, 'desc': 'Request header pattern'},
+                'rep_header': {'category': 'content', 'slow': False, 'desc': 'Reply header pattern'},
+                
+                # Authentication ACLs
+                'proxy_auth': {'category': 'auth', 'slow': True, 'desc': 'Proxy authentication username'},
+                'proxy_auth_regex': {'category': 'auth', 'slow': True, 'desc': 'Proxy auth username regex'},
+                'ext_user': {'category': 'auth', 'slow': True, 'desc': 'External ACL helper username'},
+                'ext_user_regex': {'category': 'auth', 'slow': True, 'desc': 'External ACL helper username regex'},
+                
+                # MIME Type ACLs
+                'req_mime_type': {'category': 'content', 'slow': False, 'desc': 'Request MIME type'},
+                'rep_mime_type': {'category': 'content', 'slow': False, 'desc': 'Reply MIME type'},
+                
+                # Connection ACLs
+                'maxconn': {'category': 'connection', 'slow': False, 'desc': 'Max TCP connections from IP'},
+                'max_user_ip': {'category': 'connection', 'slow': False, 'desc': 'Max IPs per user'},
+                
+                # SSL/TLS ACLs
+                'ssl_error': {'category': 'ssl', 'slow': False, 'desc': 'SSL certificate validation error'},
+                'server_cert_fingerprint': {'category': 'ssl', 'slow': False, 'desc': 'Server cert fingerprint'},
+                'ssl::server_name': {'category': 'ssl', 'slow': False, 'desc': 'TLS SNI server name'},
+                'ssl::server_name_regex': {'category': 'ssl', 'slow': False, 'desc': 'TLS SNI regex match'},
+                'connections_encrypted': {'category': 'ssl', 'slow': False, 'desc': 'All connections over TLS'},
+                
+                # Advanced ACLs
+                'external': {'category': 'advanced', 'slow': True, 'desc': 'External ACL helper lookup'},
+                'random': {'category': 'advanced', 'slow': False, 'desc': 'Random probability match'},
+                'note': {'category': 'advanced', 'slow': False, 'desc': 'Transaction annotation'},
+                'annotate_transaction': {'category': 'advanced', 'slow': False, 'desc': 'Add transaction annotation'},
+                'annotate_client': {'category': 'advanced', 'slow': False, 'desc': 'Add client annotation'},
+                'peername': {'category': 'advanced', 'slow': False, 'desc': 'Cache peer name'},
+                'peername_regex': {'category': 'advanced', 'slow': False, 'desc': 'Cache peer name regex'},
+                'hier_code': {'category': 'advanced', 'slow': False, 'desc': 'Squid hierarchy code'},
+                
+                # Group ACLs
+                'any-of': {'category': 'group', 'slow': False, 'desc': 'Match any of the ACLs'},
+                'all-of': {'category': 'group', 'slow': False, 'desc': 'Match all of the ACLs'},
+            }
+            
+            last_comment = ""
 
             for line_num, line in enumerate(lines, 1):
                 try:
-                    line = line.strip()
-                    if line.startswith("acl ") and not line.startswith("#"):
-                        parts = line.split()
+                    stripped = line.strip()
+                    
+                    # Track comments for context
+                    if stripped.startswith("#"):
+                        last_comment = stripped[1:].strip()
+                        continue
+                    
+                    if stripped.startswith("acl "):
+                        parts = stripped.split()
                         if len(parts) >= 3:
                             acl_name = parts[1]
-                            acl_type = parts[2]
-                            acl_value = " ".join(parts[3:]) if len(parts) > 3 else ""
-                            acls.append(
-                                {
-                                    "id": acl_index,
-                                    "name": acl_name,
-                                    "type": acl_type,
-                                    "value": acl_value,
-                                    "full_line": line,
-                                }
-                            )
+                            
+                            # Parse options and type
+                            options = []
+                            type_index = 2
+                            while type_index < len(parts) and parts[type_index].startswith('-'):
+                                options.append(parts[type_index])
+                                type_index += 1
+                            
+                            if type_index >= len(parts):
+                                continue
+                                
+                            acl_type = parts[type_index]
+                            values = parts[type_index + 1:] if len(parts) > type_index + 1 else []
+                            value_string = " ".join(values)
+                            
+                            # Get type metadata
+                            type_info = acl_types_info.get(acl_type, {
+                                'category': 'other',
+                                'slow': False,
+                                'desc': 'Custom ACL type'
+                            })
+                            
+                            # Check if predefined
+                            is_predefined = acl_name in predefined_acls
+                            
+                            acls.append({
+                                "id": acl_index,
+                                "name": acl_name,
+                                "type": acl_type,
+                                "options": options,
+                                "value_list": values,
+                                "value_string": value_string,
+                                "is_predefined": is_predefined,
+                                "is_slow": type_info.get('slow', False),
+                                "category": type_info.get('category', 'other'),
+                                "type_description": type_info.get('desc', ''),
+                                "comment": last_comment if last_comment else "",
+                                "line_number": line_num,
+                                "full_line": stripped
+                            })
                             acl_index += 1
+                            last_comment = ""
+                            
                 except Exception as e:
                     logger.warning(f"Error processing ACL at line {line_num}: {e}")
                     continue
@@ -219,65 +344,102 @@ class SquidConfigManager:
             return []
 
     def get_delay_pools(self):
+        """
+        Parse delay pools configuration and group by pool number.
+        Returns a list of pool dictionaries with all related directives.
+        Format:
+        {
+            'pool_number': '1',
+            'class': '3',
+            'parameters': '8192/131072 1024/65536 256/32768',
+            'access_rules': [{'action': 'allow', 'acl': 'students'}]
+        }
+        """
         if not self.is_valid:
             logger.error("Cannot get delay pools: invalid environment")
             return []
 
-        if not self.config_content:
-            logger.warning("No configuration content available")
-            return []
+        # If using modular config, read from the delay pools specific file
+        if self.is_modular:
+            delay_content = self.read_modular_config("110_delay_pools.conf")
+            if not delay_content:
+                logger.warning("Could not read modular delay pools config, falling back to main config")
+                config_to_parse = self.config_content
+            else:
+                config_to_parse = delay_content
+        else:
+            if not self.config_content:
+                logger.warning("No configuration content available")
+                return []
+            config_to_parse = self.config_content
 
         try:
-            delay_pools = []
-            lines = self.config_content.split("\n")
+            pools_dict = {}  # Dictionary to group by pool number
+            total_pools = 0
+            lines = config_to_parse.split("\n")
 
             for line_num, line in enumerate(lines, 1):
                 try:
                     line = line.strip()
+                    
                     if line.startswith("delay_pools "):
                         parts = line.split()
                         if len(parts) >= 2:
-                            delay_pools.append(
-                                {"directive": "delay_pools", "value": parts[1]}
-                            )
+                            total_pools = int(parts[1])
+                            
                     elif line.startswith("delay_class "):
                         parts = line.split()
                         if len(parts) >= 3:
-                            delay_pools.append(
-                                {
-                                    "directive": "delay_class",
-                                    "pool": parts[1],
-                                    "class": parts[2],
+                            pool_num = parts[1]
+                            if pool_num not in pools_dict:
+                                pools_dict[pool_num] = {
+                                    'pool_number': pool_num,
+                                    'class': parts[2],
+                                    'parameters': None,
+                                    'access_rules': []
                                 }
-                            )
+                            else:
+                                pools_dict[pool_num]['class'] = parts[2]
+                                
                     elif line.startswith("delay_parameters "):
                         parts = line.split()
                         if len(parts) >= 3:
-                            delay_pools.append(
-                                {
-                                    "directive": "delay_parameters",
-                                    "pool": parts[1],
-                                    "parameters": " ".join(parts[2:]),
+                            pool_num = parts[1]
+                            if pool_num not in pools_dict:
+                                pools_dict[pool_num] = {
+                                    'pool_number': pool_num,
+                                    'class': None,
+                                    'parameters': " ".join(parts[2:]),
+                                    'access_rules': []
                                 }
-                            )
+                            else:
+                                pools_dict[pool_num]['parameters'] = " ".join(parts[2:])
+                                
                     elif line.startswith("delay_access "):
                         parts = line.split()
                         if len(parts) >= 4:
-                            delay_pools.append(
-                                {
-                                    "directive": "delay_access",
-                                    "pool": parts[1],
-                                    "action": parts[2],
-                                    "acl": " ".join(parts[3:]),
+                            pool_num = parts[1]
+                            if pool_num not in pools_dict:
+                                pools_dict[pool_num] = {
+                                    'pool_number': pool_num,
+                                    'class': None,
+                                    'parameters': None,
+                                    'access_rules': []
                                 }
-                            )
+                            pools_dict[pool_num]['access_rules'].append({
+                                'action': parts[2],
+                                'acl': " ".join(parts[3:])
+                            })
+                            
                 except Exception as e:
                     logger.warning(
                         f"Error processing delay pool at line {line_num}: {e}"
                     )
                     continue
 
-            logger.debug(f"Found {len(delay_pools)} delay pool configurations")
+            # Convert dictionary to sorted list
+            delay_pools = [pools_dict[key] for key in sorted(pools_dict.keys(), key=int)]
+            logger.debug(f"Found {len(delay_pools)} delay pool configurations (total_pools={total_pools})")
             return delay_pools
 
         except Exception as e:
@@ -285,27 +447,85 @@ class SquidConfigManager:
             return []
 
     def get_http_access_rules(self):
+        """
+        Parse http_access rules with enhanced information.
+        Returns a list of rule dictionaries with action, acls (list), and metadata.
+        Format:
+        {
+            'action': 'allow',
+            'acls': ['!Safe_ports'],  # List of ACLs including negations
+            'acl_string': '!Safe_ports',  # Original ACL string
+            'is_negative': True,  # If it contains negation
+            'line_number': 5,  # Original line number
+            'description': ''  # Optional description from comments
+        }
+        """
         if not self.is_valid:
             logger.error("Cannot get HTTP rules: invalid environment")
             return []
 
-        if not self.config_content:
-            logger.warning("No configuration content available")
-            return []
+        # If using modular config, read from the http_access specific file
+        if self.is_modular:
+            http_content = self.read_modular_config("120_http_access.conf")
+            if not http_content:
+                logger.warning("Could not read modular http_access config, falling back to main config")
+                config_to_parse = self.config_content
+            else:
+                config_to_parse = http_content
+        else:
+            if not self.config_content:
+                logger.warning("No configuration content available")
+                return []
+            config_to_parse = self.config_content
 
         try:
             rules = []
-            lines = self.config_content.split("\n")
+            lines = config_to_parse.split("\n")
+            last_comment = ""
 
             for line_num, line in enumerate(lines, 1):
                 try:
-                    line = line.strip()
-                    if line.startswith("http_access ") and not line.startswith("#"):
-                        parts = line.split()
+                    stripped = line.strip()
+                    
+                    # Track comments for context
+                    if stripped.startswith("#"):
+                        last_comment = stripped[1:].strip()
+                        continue
+                    
+                    if stripped.startswith("http_access "):
+                        parts = stripped.split()
                         if len(parts) >= 3:
-                            rules.append(
-                                {"action": parts[1], "acl": " ".join(parts[2:])}
-                            )
+                            action = parts[1]
+                            acl_string = " ".join(parts[2:])
+                            acls = parts[2:]
+                            
+                            # Check if any ACL has negation
+                            is_negative = any(acl.startswith("!") for acl in acls)
+                            
+                            # Identify special/common ACLs
+                            special_acls = []
+                            if "localhost" in acls:
+                                special_acls.append("localhost")
+                            if "manager" in acls:
+                                special_acls.append("manager")
+                            if any("Safe_ports" in acl for acl in acls):
+                                special_acls.append("Safe_ports")
+                            if any("SSL_ports" in acl for acl in acls):
+                                special_acls.append("SSL_ports")
+                            if "CONNECT" in acls:
+                                special_acls.append("CONNECT")
+                            
+                            rules.append({
+                                "action": action,
+                                "acls": acls,
+                                "acl_string": acl_string,
+                                "is_negative": is_negative,
+                                "line_number": line_num,
+                                "description": last_comment if last_comment else "",
+                                "special_acls": special_acls
+                            })
+                            last_comment = ""  # Reset comment
+                            
                 except Exception as e:
                     logger.warning(
                         f"Error processing HTTP rule at line {line_num}: {e}"
@@ -319,12 +539,146 @@ class SquidConfigManager:
             logger.error(f"Unexpected error extracting HTTP rules: {e}")
             return []
 
+    def _check_modular_config(self):
+        """Check if the main config file uses modular includes."""
+        if not self.config_content:
+            return
+
+        # Check if config contains include directives pointing to squid.d
+        self.is_modular = "include" in self.config_content.lower() and "squid.d" in self.config_content
+        if self.is_modular:
+            logger.info("Modular configuration detected")
+
+    def list_modular_configs(self) -> list[dict[str, str]]:
+        """List all modular configuration files in squid.d directory."""
+        if not os.path.exists(self.config_dir):
+            logger.warning(f"Config directory not found: {self.config_dir}")
+            return []
+
+        try:
+            configs = []
+            for filename in sorted(os.listdir(self.config_dir)):
+                if filename.endswith('.conf'):
+                    filepath = os.path.join(self.config_dir, filename)
+                    if os.path.isfile(filepath):
+                        try:
+                            stat = os.stat(filepath)
+                            configs.append({
+                                "filename": filename,
+                                "filepath": filepath,
+                                "size": stat.st_size,
+                                "modified": datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M:%S"),
+                                "readable": os.access(filepath, os.R_OK),
+                                "writable": os.access(filepath, os.W_OK),
+                            })
+                        except Exception as e:
+                            logger.warning(f"Error reading file info for {filename}: {e}")
+            return configs
+        except Exception as e:
+            logger.error(f"Error listing modular configs: {e}")
+            return []
+
+    def read_modular_config(self, filename: str) -> Optional[str]:
+        """Read a specific modular configuration file."""
+        filepath = os.path.join(self.config_dir, filename)
+
+        if not os.path.exists(filepath):
+            logger.error(f"Config file not found: {filepath}")
+            return None
+
+        if not filepath.endswith('.conf'):
+            logger.error(f"Invalid file extension: {filename}")
+            return None
+
+        try:
+            with open(filepath, 'r', encoding='utf-8') as f:
+                content = f.read()
+            logger.debug(f"Read modular config: {filename}")
+            return content
+        except Exception as e:
+            logger.error(f"Error reading modular config {filename}: {e}")
+            return None
+
+    def save_modular_config(self, filename: str, content: str) -> bool:
+        """Save content to a specific modular configuration file."""
+        filepath = os.path.join(self.config_dir, filename)
+
+        if not filename.endswith('.conf'):
+            logger.error(f"Invalid file extension: {filename}")
+            return False
+
+        # Validate filename to prevent directory traversal
+        if '/' in filename or '\\' in filename or '..' in filename:
+            logger.error(f"Invalid filename (potential path traversal): {filename}")
+            return False
+
+        try:
+            # Create backup before saving
+            if os.path.exists(filepath):
+                backup_path = f"{filepath}.bak{datetime.now().strftime('%Y%m%d_%H%M%S')}"
+                try:
+                    shutil.copy2(filepath, backup_path)
+                    logger.info(f"Backup created: {backup_path}")
+                except Exception as e:
+                    logger.warning(f"Could not create backup: {e}")
+
+            with open(filepath, 'w', encoding='utf-8') as f:
+                f.write(content)
+
+            logger.info(f"Saved modular config: {filename}")
+            return True
+        except Exception as e:
+            logger.error(f"Error saving modular config {filename}: {e}")
+            return False
+
+    def delete_modular_config(self, filename: str) -> bool:
+        """Delete a specific modular configuration file."""
+        filepath = os.path.join(self.config_dir, filename)
+
+        if not os.path.exists(filepath):
+            logger.error(f"Config file not found: {filepath}")
+            return False
+
+        if not filename.endswith('.conf'):
+            logger.error(f"Invalid file extension: {filename}")
+            return False
+
+        # Validate filename to prevent directory traversal
+        if '/' in filename or '\\' in filename or '..' in filename:
+            logger.error(f"Invalid filename (potential path traversal): {filename}")
+            return False
+
+        try:
+            # Create backup before deleting
+            backup_path = f"{filepath}.deleted{datetime.now().strftime('%Y%m%d_%H%M%S')}"
+            try:
+                shutil.move(filepath, backup_path)
+                logger.info(f"File moved to: {backup_path}")
+                return True
+            except Exception as e:
+                logger.error(f"Error deleting file {filename}: {e}")
+                return False
+        except Exception as e:
+            logger.error(f"Error handling file deletion {filename}: {e}")
+            return False
+
+    def get_modular_config_info(self) -> dict:
+        """Get information about the modular configuration setup."""
+        return {
+            "is_modular": self.is_modular,
+            "config_dir": self.config_dir,
+            "config_dir_exists": os.path.exists(self.config_dir),
+            "config_files_count": len(self.list_modular_configs()),
+            "main_config_path": self.config_path,
+        }
+
     def get_status(self):
         return {
             "is_valid": self.is_valid,
             "errors": self.errors,
             "config_loaded": bool(self.config_content),
             "config_path": self.config_path,
-            # "backup_dir": BACKUP_DIR,
+            "config_dir": self.config_dir,
+            "is_modular": self.is_modular,
             "acl_files_dir": ACL_FILES_DIR,
         }