anti_servspam.lua 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. if not minetest.global_exists("spam") then spam = {} end
  2. spam.keys = spam.keys or {}
  3. spam.ips = spam.ips or {}
  4. local spamkeys = spam.keys
  5. -- Return 'true' if key was recently marked. Otherwise, return 'false'.
  6. function spam.test_key(key)
  7. local last = spamkeys[key] or 0
  8. if os.time() < last then
  9. return true
  10. end
  11. spamkeys[key] = nil
  12. return false
  13. end
  14. -- Mark 'key' as not to be used again for 'time' seconds (starting from now).
  15. function spam.mark_key(key, time)
  16. time = time or 60
  17. spamkeys[key] = os.time() + time
  18. end
  19. local spamips = spam.ips
  20. function spam.should_block_player(pname, ip)
  21. -- Don't slow dev testing down. I'm on the clock, here!
  22. if ip == "127.0.0.1" or ip == "0.0.0.0" then
  23. return false
  24. end
  25. -- Should block from joining too quick only if someone else logged in with same IP already.
  26. if spamips[ip] then
  27. return true
  28. end
  29. return false
  30. end
  31. function spam.on_prejoinplayer(name, ip)
  32. -- Needed for debugging/testing.
  33. --if name == "bobman" then
  34. -- return "Go away please."
  35. --end
  36. local last = spamips[ip] or 0
  37. if os.time() < last and spam.should_block_player(name, ip) then
  38. return "The path is narrow and crowded. Perhaps you should wait awhile ..."
  39. end
  40. end
  41. -- Block anyone from the same IP as player (by name) from joining for some time.
  42. function spam.block_playerjoin(pname, time)
  43. local pref = minetest.get_player_by_name(pname)
  44. if not pref then
  45. return
  46. end
  47. local ip = minetest.get_player_ip(pname)
  48. if not ip then
  49. return
  50. end
  51. time = time or 60
  52. spamips[ip] = os.time() + time
  53. end
  54. -- Only block future logins from this IP only if they successfully logged in the first time.
  55. function spam.on_joinplayer(pref, last_login)
  56. local ip = minetest.get_player_ip(pref:get_player_name())
  57. spamips[ip] = os.time() + 30
  58. end
  59. if not spam.run_once then
  60. spam.run_once = true
  61. minetest.register_on_prejoinplayer(function(...)
  62. return spam.on_prejoinplayer(...) end)
  63. minetest.register_on_joinplayer(function(...)
  64. return spam.on_joinplayer(...) end)
  65. end