connections.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import re
  2. from collections import defaultdict
  3. REGEX_MAP = {
  4. "fd": re.compile(r"FD (\d+)"),
  5. "uri": re.compile(r"uri (.+)"),
  6. "username": re.compile(r"username (.+)"),
  7. "logType": re.compile(r"logType (.+)"),
  8. "start": re.compile(r"start ([\d.]+)"),
  9. "elapsed_time": re.compile(r"start .*?\(([\d.]+) seconds ago\)"),
  10. "client_ip": re.compile(r"remote:\s+([\[\]a-fA-F0-9:\.]+:\d+)"),
  11. "proxy_local_ip": re.compile(r"local:\s+([\[\]a-fA-F0-9:\.]+:\d+)"),
  12. "fd_read": re.compile(r"read (\d+)"),
  13. "fd_wrote": re.compile(r"wrote (\d+)"),
  14. "nrequests": re.compile(r"nrequests: (\d+)"),
  15. "delay_pool": re.compile(r"delay_pool (\d+)"),
  16. "out_size": re.compile(r"out\.size (\d+)"),
  17. "squid_version": re.compile(r"Server:\s*squid/([^\s]+)"),
  18. "via_squid": re.compile(r"Via:.*\(squid/([^\)]+)\)"),
  19. "kid_open": re.compile(r"^\s*by\s+(kid\d+)\s*\{"),
  20. "kid_close": re.compile(r"^\s*\}\s+by\s+(kid\d+)\s*$"),
  21. }
  22. def parse_raw_data(raw_data: str, source_host: str | None = None):
  23. if not raw_data:
  24. return []
  25. first_idx = raw_data.find("Connection:")
  26. header = raw_data[:first_idx] if first_idx != -1 else raw_data
  27. body = raw_data[first_idx:] if first_idx != -1 else ""
  28. squid_version = "N/A"
  29. m = REGEX_MAP["squid_version"].search(header)
  30. if m:
  31. squid_version = m.group(1)
  32. else:
  33. vm = REGEX_MAP["via_squid"].search(header)
  34. if vm:
  35. squid_version = vm.group(1)
  36. connections = []
  37. current_kid = None
  38. current_block_lines = None
  39. lines = body.splitlines()
  40. for line in lines:
  41. if REGEX_MAP["kid_open"].match(line):
  42. current_kid = REGEX_MAP["kid_open"].match(line).group(1)
  43. continue
  44. if REGEX_MAP["kid_close"].match(line):
  45. current_kid = None
  46. continue
  47. if line.lstrip().startswith("Connection:"):
  48. if current_block_lines is not None:
  49. block_text = "\n".join(current_block_lines)
  50. try:
  51. conn = parse_connection_block(
  52. block_text, squid_version, kid=current_kid
  53. )
  54. if source_host:
  55. conn["proxy_host"] = source_host
  56. connections.append(conn)
  57. except Exception as e:
  58. print(f"Error parseando bloque: {e}\n{block_text[:120]}...")
  59. current_block_lines = [line]
  60. else:
  61. if current_block_lines is not None:
  62. current_block_lines.append(line)
  63. if current_block_lines is not None:
  64. block_text = "\n".join(current_block_lines)
  65. try:
  66. conn = parse_connection_block(block_text, squid_version, kid=current_kid)
  67. if source_host:
  68. conn["proxy_host"] = source_host
  69. connections.append(conn)
  70. except Exception as e:
  71. print(f"Error parseando bloque: {e}\n{block_text[:120]}...")
  72. filtered = [
  73. c
  74. for c in connections
  75. if not (
  76. isinstance(c.get("uri"), str)
  77. and "squid-internal-mgr/active_requests" in c.get("uri")
  78. )
  79. ]
  80. return filtered
  81. def parse_connection_block(block: str, squid_version: str, kid: str | None = None):
  82. conn: dict = {}
  83. for key, regex in REGEX_MAP.items():
  84. if key not in [
  85. "fd_read",
  86. "fd_wrote",
  87. "nrequests",
  88. "delay_pool",
  89. "fd_total",
  90. "out_size",
  91. "squid_version",
  92. "squid_host",
  93. "via_squid",
  94. ]:
  95. match = regex.search(block)
  96. value = match.group(1) if match else "N/A"
  97. if key == "client_ip" and match:
  98. value = match.group(1).rsplit(":", 1)[0].strip("[]")
  99. conn[key] = value
  100. conn["fd_read"] = (
  101. int(REGEX_MAP["fd_read"].search(block).group(1))
  102. if REGEX_MAP["fd_read"].search(block)
  103. else 0
  104. )
  105. conn["fd_wrote"] = (
  106. int(REGEX_MAP["fd_wrote"].search(block).group(1))
  107. if REGEX_MAP["fd_wrote"].search(block)
  108. else 0
  109. )
  110. conn["fd_total"] = conn["fd_read"] + conn["fd_wrote"]
  111. conn["nrequests"] = (
  112. int(REGEX_MAP["nrequests"].search(block).group(1))
  113. if REGEX_MAP["nrequests"].search(block)
  114. else 0
  115. )
  116. conn["delay_pool"] = (
  117. int(REGEX_MAP["delay_pool"].search(block).group(1))
  118. if REGEX_MAP["delay_pool"].search(block)
  119. else "N/A"
  120. )
  121. out_size_match = REGEX_MAP["out_size"].search(block)
  122. conn["out_size"] = int(out_size_match.group(1)) if out_size_match else 0
  123. conn["squid_version"] = squid_version
  124. if kid:
  125. conn["kid"] = kid
  126. elapsed_match = REGEX_MAP["elapsed_time"].search(block)
  127. elapsed_time = float(elapsed_match.group(1)) if elapsed_match else 0
  128. conn["elapsed_time"] = elapsed_time
  129. if conn["out_size"] > 0 and elapsed_time > 0:
  130. conn["bandwidth_bps"] = round((conn["out_size"] * 8) / elapsed_time, 2)
  131. conn["bandwidth_kbps"] = round(conn["bandwidth_bps"] / 1000, 2)
  132. else:
  133. conn["bandwidth_bps"] = 0
  134. conn["bandwidth_kbps"] = 0
  135. return conn
  136. def group_by_user(connections):
  137. ANONYMOUS_INDICATORS = {
  138. None,
  139. "",
  140. "-",
  141. "Anónimo",
  142. "N/A",
  143. "anonymous",
  144. "Anonymous",
  145. "unknown",
  146. "guest",
  147. "none",
  148. "null",
  149. }
  150. grouped = defaultdict(lambda: {"client_ip": "Not found", "connections": []})
  151. for connection in connections:
  152. user = connection.get("username")
  153. if not isinstance(user, str):
  154. user = str(user) if user is not None else ""
  155. user_normalized = user.strip().lower() if user else ""
  156. if user_normalized == "n/a":
  157. continue
  158. is_anonymous = not user_normalized or user_normalized in (
  159. indicator.lower()
  160. for indicator in ANONYMOUS_INDICATORS
  161. if indicator is not None
  162. )
  163. raw_ip = connection.get("client_ip", "Not found")
  164. if not is_anonymous:
  165. key = user
  166. client_ip = raw_ip
  167. else:
  168. key = raw_ip
  169. client_ip = raw_ip
  170. if not grouped[key]["connections"]:
  171. grouped[key]["client_ip"] = client_ip
  172. grouped[key]["connections"].append(connection)
  173. return dict(grouped)