4
0

icap_service.py 1.4 KB

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