Advertisement
Guest User

server.lua

a guest
Dec 23rd, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 8.22 KB | None | 0 0
  1. --Variables
  2. version = "0.1"
  3.  
  4. --The 2 holy protocols
  5. messageProtocol = "csIRC_msg"
  6. authProtocol = "csIRC_auth"
  7. clientProtocol = "csIRC_client"
  8.  
  9. --Client will have to use this format, otherwise the message will be discarded
  10. --Message protocol format: "msg:*message here*"
  11. --Auth protocol format: "type:*type of auth here, there are 3 possible ones: reg, login, logout*, user:*name of the user, always needed*, pass:*password of the user, not needed in logouts*"
  12. msgPrefix = "msg:"
  13.  
  14. authTypePrefix = "type:"
  15. authUserPrefix = "user:"
  16. authPassPrefix = "pass:"
  17. authTokenPrefix = "token:"
  18.  
  19. --Auth type prefixes
  20. authRegPrefix = "reg"
  21. authLoginPrefix = "login"
  22. authLogoutPrefix = "logout"
  23.  
  24. InfoCOLOR = colors.white
  25. WarningCOLOR = colors.yellow
  26. ErrorCOLOR = colors.red
  27.  
  28. --User file property strings
  29. userNameKey = "user"
  30. passKey = "pass"
  31. IDKey = "ID"
  32.  
  33. loggingFOLDER = "serverLogs"
  34. loggingENABLED = true
  35.  
  36. usersFolder = "Users"
  37.  
  38. --The logged in users are stored in the loggedUsers 2D array (user ID/token)
  39. loggedUsers = {}
  40. --Functions
  41. function printMSG(message, color)
  42.     prefixedMessage = os.time()..message
  43.     LogMessage(prefixedMessage)
  44.     term.setTextColor(color)
  45.     print(prefixedMessage)
  46. end
  47.  
  48. function infoMSG(message)
  49.     printMSG("[INFO]: "..message,InfoCOLOR)
  50. end
  51.  
  52. function warningMSG(message)
  53.     printMSG("[WARNING]: "..message,WarningCOLOR)
  54. end
  55.  
  56. function errorMSG(message)
  57.     printMSG("[ERROR]: "..message,ErrorCOLOR)
  58. end
  59.  
  60. function LogMessage(message)
  61.     if loggingENABLED == true then logfileHandle.writeLine(message) end
  62. end
  63.  
  64. function GetFileValue(file, key)
  65.     if file ~= nil and key ~= nil then
  66.         local handle = fs.open(file,"r")
  67.         if handle ~= nil then
  68.             while true do
  69.                 local line = handle.readLine()
  70.                 if line == nil then
  71.                     handle.close()
  72.                     return nil
  73.                 end
  74.                 if string.find(line, key) ~= nil then
  75.                     handle.close()
  76.                     return string.sub(line, string.len(key) + 2)--2 because the first is the last letter of the key and the second is the = symbol
  77.                 end
  78.             end
  79.         end
  80.     end
  81. end
  82.  
  83. function SetFileValue(file, key, value)
  84.     local handle = fs.open(file,"r")
  85.     local allLines = {}
  86.     if handle ~= nil then
  87.         while true do
  88.             currentLine = handle.readLine()
  89.             if currentLine == nil then break end
  90.             table.insert(allLines, currentLine)
  91.         end
  92.         local isValueFound = false
  93.         for i, line in ipairs(allLines) do
  94.             if string.find(line, key) ~= nil then
  95.                 line = key.."="..value
  96.                 isValueFound = true
  97.             end
  98.         end
  99.     end
  100.     handle = fs.open(file, "w")
  101.     if allLines ~= nil then
  102.         for i, line in ipairs(allLines) do
  103.             handle.writeLine(line)
  104.         end
  105.     end
  106.     if isValueFound == false or isValueFound == nil then handle.writeLine(key.."="..value) end
  107.     handle.close()
  108. end
  109.  
  110. function GenerateLoginToken()
  111.     local token
  112.     while true do
  113.         token = tostring(math.random(1000000,9999999))
  114.         if FindUserByToken(token) == nil then return token end
  115.     end
  116. end
  117.  
  118. function FindUserByName(username) -- Finds the user and returns the directory of the user so that you can open a handle to it
  119.     AllUsers = fs.find(usersFolder.."/*")
  120.     for i, user in ipairs(AllUsers) do
  121.         foundLine = GetFileValue(user, userNameKey)
  122.         if foundLine ~= nil then
  123.             if foundLine == username then return user end
  124.         end
  125.     end
  126.     return nil
  127. end
  128.  
  129. function FindUserByID(ID)
  130.     AllUsers = fs.find(usersFolder.."/*")
  131.     for i, user in ipairs(AllUsers) do
  132.         foundLine = GetFileValue(user, IDString)
  133.         if foundLine ~= nil then
  134.             if foundLine == ID then return user end
  135.         end
  136.     end
  137.     return nil
  138. end
  139.  
  140. function FindUserByToken(token)
  141.     for i, id in ipairs(loggedUsers) do
  142.         if loggedUsers[i][1] == token then return FindUserByID(id) end
  143.     end
  144.     return nil
  145. end
  146.  
  147. function CreateUser(username, password)
  148.     if FindUserByName(username) == nil then
  149.         if string.len(username) <= 16 then
  150.             if password ~= nil then
  151.                 while userID == nil do
  152.                     userID = math.random(100000,999999)--Create a new id
  153.                     if FindUserByID(userID) == nil then break end
  154.                 end
  155.                 local newFile = usersFolder.."/"..tostring(math.random(0,1000000))
  156.                 SetFileValue(newFile, userNameKey, username)
  157.                 SetFileValue(newFile, passKey, password)
  158.                 SetFileValue(newFile, IDKey, userID)
  159.                 infoMSG("User created. ID: "..userID.." / Username: "..username.." / Password: "..password)
  160.                 return userID
  161.             end
  162.         end
  163.     end
  164.     return nil
  165. end
  166.  
  167. function LoginUser(username, password)
  168.     local FoundUser = FindUserByName(username)
  169.     if FoundUser ~= nil then
  170.         --Check password
  171.         if password == GetFileValue(FoundUser,passKey) then
  172.             newToken = GenerateLoginToken()
  173.             print(#loggedUsers)
  174.             print(#loggedUsers + 1)
  175.             loggedUsers[#loggedUsers + 1] = {}
  176.             loggedUsers[1] = {GetFileValue(FoundUser, IDKey), newToken}
  177.             infoMSG("User logged in. Username: "..username.." / Token: "..newToken)
  178.             return newToken
  179.         end
  180.     end
  181.     return nil
  182. end
  183.  
  184. function LogoutUser(username, token)--Token used for verification, since a single username could just log people out
  185.     local FoundUser = FindUserByName(username)
  186.     local userID = GetFileValue(FoundUser, IDKey)
  187.     for i, value in ipairs(loggedUsers) do
  188.         if userID == value then
  189.             if loggedUsers[i][1] == token then--Token verification
  190.                 table.remove(loggedUsers, i)
  191.             end
  192.         end
  193.     end
  194. end
  195.  
  196. function InitLogging()
  197.     if fs.exists(loggingFOLDER) == false then
  198.         fs.makeDir(loggingFOLDER)
  199.     end
  200.    
  201.     if fs.exists(loggingFOLDER.."/latest.log") == true then
  202.         fs.move(loggingFOLDER.."/latest.log", loggingFOLDER.."/"..os.day().." "..os.time()..".log")
  203.     end
  204.    
  205.     logfileHandle = fs.open(loggingFOLDER.."/latest.log","w")
  206.     logfileHandle.writeLine("--Logging started--")
  207.     infoMSG("Logger initialized")
  208. end
  209.  
  210. function InitServer()
  211.     term.clear()
  212.     term.setCursorPos(1,1)
  213.    
  214.     if loggingENABLED == true then
  215.         InitLogging()
  216.     end
  217.     local rnSides = {"top","bottom","left","right","front","back"}
  218.     infoMSG("Checking for rednet modem")
  219.     local rednetFoundFlag = false
  220.     for i, side in ipairs(rnSides) do
  221.         if rednetFoundFlag == false then
  222.             if peripheral.getType(side) == "modem" then
  223.                 rednet.open(side)
  224.                 rednetFoundFlag = true
  225.                 infoMSG("Rednet modem turned on")
  226.             end
  227.         end
  228.     end
  229.     if rednetFoundFlag == false then
  230.         --Error out of the program because of missing modem
  231.         errorMSG("Modem not found")
  232.         error()
  233.     end
  234.    
  235.     infoMSG("Server initialized")
  236.     infoMSG("IRC Server running on version "..version)
  237. end
  238.  
  239. function ShutdownServer()
  240.     infoMSG("Shutting down server..")
  241.     logfileHandle.close()
  242. end
  243.  
  244. --Main
  245. InitServer()
  246. while true do
  247.     local event, p1, p2, p3 = os.pullEvent()
  248.    
  249.     if event == "key" then
  250.         if p1 == keys.e then
  251.             ShutdownServer()
  252.             break
  253.         end
  254.     end
  255.     if event == "rednet_message" then
  256.         if p3 == authProtocol then
  257.             local authPrefixStart, authPrefixEnd = string.find(p2,authTypePrefix)
  258.             local authUserPrefixStart, authUserPrefixEnd = string.find(p2,authUserPrefix)
  259.             if authPrefixStart ~= nil and authPrefixEnd ~= nil and authUserPrefixStart ~= nil and authUserPrefixEnd ~= nil then --Check if the prefix actually exists
  260.                 local operationType = string.sub(p2, authPrefixEnd + 1, string.find(p2, ",", authPrefixEnd) - 1)
  261.                 local authUser = string.sub(p2, authUserPrefixEnd + 1, string.find(p2, ",", authUserPrefixEnd) - 1)
  262.                 --Put the logging out here because the password is still not checked for here
  263.                 if operationType == authLogoutPrefix then
  264.                     local authTokenPrefixStart, authTokenPrefixEnd = string.find(p2, authTokenPrefix)
  265.                     if authTokenPrefixStart ~= nil and authTokenPrefixEnd ~= nil then
  266.                         local authToken = string.sub(p2, authTokenPrefixEnd + 1)
  267.                         LogoutUser(authUser, authToken)
  268.                     end
  269.                 end
  270.                 local authPassPrefixStart, authPassPrefixEnd = string.find(p2, authPassPrefix)
  271.                 if authPassPrefixStart ~= nil and authPassPrefixEnd ~= nil then
  272.                     local authPass = string.sub(p2, authPassPrefixEnd + 1)
  273.                     if operationType == authRegPrefix then
  274.                         if CreateUser(authUser, authPass) ~= nil then
  275.                             rednet.send(p1,"reg_success",clientProtocol)
  276.                         end
  277.                     end
  278.                     if operationType == authLoginPrefix then
  279.                         loginToken = LoginUser(authUser, authPass)
  280.                         print(loginToken)
  281.                         if loginToken ~= nil then
  282.                             rednet.send(p1,loginToken)
  283.                         end
  284.                     end
  285.                 end
  286.             end
  287.         end
  288.     end
  289. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement