icap_service.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """import os
  2. import tempfile
  3. import icapclient
  4. from config import Config
  5. ICAP_HOST = os.getenv("ICAP_HOST", Config.SQUID_HOST)
  6. ICAP_PORT = int(os.getenv("ICAP_PORT", 1344))
  7. def scan_file_with_icap(file_storage):
  8. if file_storage.filename == "":
  9. return {"error": "No selected file"}, 400
  10. # Save file to a temporary location
  11. with tempfile.NamedTemporaryFile(delete=False) as tmp:
  12. file_storage.save(tmp.name)
  13. temp_path = tmp.name
  14. try:
  15. conn = icapclient.ICAPConnection(ICAP_HOST, port=ICAP_PORT)
  16. conn.request("REQMOD", temp_path, service="avscan")
  17. resp = conn.getresponse()
  18. icap_status = resp.icap_status
  19. icap_reason = resp.icap_reason
  20. icap_headers = dict(resp.icap_headers)
  21. infection = resp.get_icap_header("x-infection-found")
  22. http_resp_line = getattr(resp, "http_resp_line", None)
  23. conn.close()
  24. result = {
  25. "icap_status": icap_status,
  26. "icap_reason": icap_reason,
  27. "icap_headers": icap_headers,
  28. "http_resp_line": http_resp_line,
  29. "virus_found": infection is not None,
  30. "infection_details": infection,
  31. }
  32. return result, 200
  33. except Exception as e:
  34. return {"error": f"Error scanning file with ICAP: {e}"}, 500
  35. finally:
  36. try:
  37. os.remove(temp_path)
  38. except Exception:
  39. pass
  40. """