Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local programs = {}
- local drivers = {}
- local sysFiles = {}
- programs["setperm"] = [[
- local args = {...}
- if #args == 3 then
- local targetFile = args[1]
- local targetUser = args[2]
- local targetPerms = args[3]
- local perms = {
- ["write"] = false,
- ["read"] = false,
- ["execute"] = false,
- ["delete"] = false,
- }
- for char in targetPerms:gmatch(".") do
- if char == "w" or char == "W" then
- perms["write"] = true
- elseif char == "r" or char == "R" then
- perms["read"] = true
- elseif char == "x" or char == "X" then
- perms["execute"] = true
- elseif char == "d" or char == "D" then
- perms["delete"] = true
- end
- end
- for i,v in pairs(perms) do
- local ok, err = os.setPerm(targetFile, i, v, targetUser)
- if not ok then
- error("Could not set permission: "..i)
- end
- end
- else
- print("USAGE: setperm [file] [user] [perms]")
- print("[perms] is a string of letters describing what permissions said user has.")
- print("Example:")
- print("setperm test Test rx")
- print("That would allow the user \"Test\" to do look at and execute the file \"test\",")
- print("but he/she wouldn't be able to change it or delete it.")
- end
- ]]
- programs["setowner"] = [[
- local args = {...}
- if #args == 2 then
- if os.setOwner(args[1], args[2]) then
- print("Done!")
- else
- term.setTextColor(colors.red)
- print("Permission denied.")
- term.setTextColor(colors.white)
- end
- else
- print("USAGE: setowner [file] [new owner]")
- end
- ]]
- programs["turtleSettings"] = [[
- -- Turtle Settings Manager
- local args = {...}
- local function listSettings()
- local settingsFile = fs.open(".os/turtle", "r")
- local canMove = settingsFile.readLine()
- local canDig = settingsFile.readLine()
- local canPlace = settingsFile.readLine()
- local canSuck = settingsFile.readLine()
- settingsFile.close()
- return canMove, canDig, canPlace, canSuck
- end
- local function changeSettings(canMove, canDig, canPlace, canSuck)
- local settingsFile = fs.open(".os/turtle", "w")
- settingsFile.writeLine(canMove)
- settingsFile.writeLine(canDig)
- settingsFile.writeLine(canPlace)
- settingsFile.writeLine(canSuck)
- settingsFile.close()
- end
- if os.getCurrentUser() == "root" then
- if args[1] == "set" then
- if #args == 5 then
- changeSettings(args[2], args[3], args[4], args[5])
- else
- print("USAGE: turtleSettings [get/set] [canMove] [canDig] [canPlace] [canSuck]")
- end
- elseif args[1] == "get" then
- local canMove,canDig,canPlace,canSuck = listSettings()
- print("Can Move: "..canMove)
- print("Can Dig: "..canDig)
- print("Can Place: "..canPlace)
- print("Can Suck: "..canSuck)
- end
- else
- print("You need to be root to do this!")
- end
- ]]
- programs["backup"] = [=[
- args = {}
- local function getAllFilesInDir(dir, includeDirs)
- dir = dir or ""
- local files = {}
- for i,v in ipairs(fs.list(dir)) do
- if fs.isDir(dir.."/"..v) then
- if string.sub(v, 1,4) ~= "disk" and v ~= "rom" then
- if includeDirs then
- table.insert(files, v)
- end
- for i2, v2 in ipairs(getAllFilesInDir(dir.."/"..v, includeDirs)) do
- table.insert(files, v.."/"..v2)
- end
- end
- else
- table.insert(files, v)
- end
- end
- return files
- end
- local function getDriveOne()
- for i,v in ipairs(rs.getSides()) do
- if peripheral.isPresent(v) and peripheral.getType(v) == "drive" and disk.getMountPath(v) == "disk" then
- return v
- end
- end
- end
- local restoreProgram = [[
- local function getDriveOne()
- for i,v in ipairs(rs.getSides()) do
- if peripheral.isPresent(v) and peripheral.getType(v) == "drive" and disk.getMountPath(v) == "disk" then
- return v
- end
- end
- end
- local function restore()
- if fs.exists("disk/backup") then
- local backup = fs.open("disk/backup", "r")
- local fileTable = backup.readAll()
- backup.close()
- local fileTable = textutils.unserialize(fileTable)
- write("This disk contains a stored backup of computer ")
- term.setTextColor(colors.lime)
- print(tostring(fileTable[1])..".")
- term.setTextColor(colors.white)
- if type(fileTable[4]) == "string" then
- write("Label: ")
- term.setTextColor(colors.lime)
- print(fileTable[4]..".")
- term.setTextColor(colors.white)
- os.setComputerLabel(fileTable[4])
- hasLabel = true
- end
- write("Total files: ")
- term.setTextColor(colors.lime)
- print(tostring(fileTable[3]))
- term.setTextColor(colors.white)
- write("Total file size: ")
- term.setTextColor(colors.lime)
- print(tostring(fileTable[2]))
- term.setTextColor(colors.white)
- if fs.getFreeSpace("/") < fileTable[2] then
- print("This computer does not have enough space to restore from the backup.")
- print("Exiting...")
- return
- else
- while true do
- print("Restore from backup? (Y/N) >")
- local yn = read()
- yn = string.upper(yn)
- if yn == "Y" then
- break
- elseif yn == "N" then
- return
- else
- term.setTextColor(colors.red)
- print("Please provide a valid response.")
- term.setTextColor(colors.white)
- end
- end
- os.sleep(1.5)
- for i,v in ipairs(fileTable) do
- if i ~= 1 and i~= 2 and i ~= 3 then
- term.clear()
- term.setCursorPos(1,1)
- print("Restoring file...")
- write("ID: ")
- term.setTextColor(colors.lime)
- print(v[1])
- term.setTextColor(colors.white)
- write("Path: ")
- term.setTextColor(colors.lime)
- print(v[2])
- term.setTextColor(colors.white)
- if v[3] then
- print("Is a directory.")
- else
- print("Is a file.")
- write("Size: ")
- term.setTextColor(colors.lime)
- print(tostring(v[4]))
- term.setTextColor(colors.white)
- end
- if v[3] then
- fs.makeDir(v[2])
- else
- local file = fs.open(v[2], "w")
- file.write(v[5])
- file.close()
- end
- os.sleep(0.5)
- end
- end
- print(" ")
- print("Restore complete.")
- os.sleep(1)
- disk.eject(getDriveOne())
- os.reboot()
- end
- end
- end
- restore()
- ]]
- local function writeBackupToDisk(entries)
- local backup = fs.open("disk/backup", "w")
- backup.write(textutils.serialize(entries))
- backup.close()
- disk.setLabel(getDriveOne(), "Backup of computer "..tostring(os.computerID()))
- local programHandle = fs.open("disk/startup", "w")
- programHandle.write(restoreProgram)
- programHandle.close()
- disk.eject(getDriveOne())
- end
- local function makeBackup()
- local files = getAllFilesInDir("", true)
- local entries = {}
- local size = 0
- for i,v in ipairs(files) do
- if not fs.isDir(v) then
- size = size + fs.getSize(v)
- end
- end
- table.insert(entries, os.getComputerID())
- table.insert(entries, size)
- table.insert(entries, #files)
- for i,v in ipairs(files) do
- local fileEntry = {}
- table.insert(fileEntry, i) --v[1]
- table.insert(fileEntry, v) --v[2]
- table.insert(fileEntry, fs.isDir(v)) --v[3]
- if not fs.isDir(v) then
- table.insert(fileEntry, fs.getSize(v)) --v[4]
- local fileHandle = fs.open(v, "r")
- table.insert(fileEntry, fileHandle.readAll()) --v[5]
- fileHandle.close()
- end
- table.insert(entries, fileEntry)
- end
- return entries
- end
- local function int_main()
- if args[1] == "-disk" then
- while true do
- if getDriveOne() ~= nil then
- write("Starting backup to disk in drive on side: ")
- term.setTextColor(colors.lime)
- print(getDriveOne())
- term.setTextColor(colors.white)
- entries = makeBackup()
- writeBackupToDisk(entries)
- break
- else
- term.setTextColor(colors.red)
- print("Please insert a disk.")
- term.setTextColor(colors.white)
- os.pullEvent("disk")
- end
- end
- end
- if args[1] == "-rednet" and (args[2] == "-backup_server" or args[2] == nil) then
- entries = makeBackup()
- for i,v in ipairs(rs.getSides()) do
- rednet.open(v)
- end
- write "Transmitting via "
- term.setTextColor(colors.lime)
- write "Backup-Server Protocol"
- term.setTextColor(colors.white)
- print "..."
- local packet = {}
- table.insert(packet, "backup")
- table.insert(packet, textutils.serialize(entries))
- packet = textutils.serialize(packet)
- if args[3] == nil then
- rednet.broadcast(packet)
- else
- rednet.send(tonumber(args[3]), packet)
- end
- end
- if args[1] == "-rednet" and args[2] == "-CommuteOS" then
- entries = makeBackup()
- for i,v in ipairs(rs.getSides()) do
- rednet.open(v)
- end
- write("Transmitting via ")
- term.setTextColor(colors.lightBlue)
- write("Project Patchwork / CommuteOS")
- term.setTextColor(colors.lime)
- write(" RemoteFile Protocol")
- term.setTextColor(colors.white)
- print("...")
- local packet = {"FILE", "BACKUP_"..tostring(os.computerID()), textutils.serialize(entries)}
- packet = textutils.serialize(packet)
- if args[3] == nil then
- rednet.broadcast(packet)
- else
- rednet.send(tonumber(args[3]), packet)
- end
- end
- if args[1] == "-local" then
- entries = makeBackup()
- local handle = fs.open("local_backup", "w")
- handle.write(textutils.serialize(entries))
- handle.close()
- end
- return 0
- end
- local function set_params()
- local option_1 = 1
- local option_2 = 1
- local option_3 = -1
- while true do
- term.clear()
- term.setCursorPos(1,1)
- print("Backup - Client")
- print("Step 1: Choose a backup medium:")
- print("1 - Rednet") -- y: 5, x: 1-10
- print("2 - Disk") -- y: 6, x: 1-8
- print("3 - Local") -- y: 7, x: 1-9
- local event, x, y, btn = os.pullEvent()
- if event == "key" then
- option_1 = x - 1
- if option_1 <= 3 and option_1 > 0 then
- break
- end
- elseif event == "click" then
- if (x <= 10 and x >= 1) and y == 3 then
- option_1 = 1
- break
- elseif (x <= 8 and x >= 1) and y == 4 then
- option_1 = 2
- break
- elseif (x <= 9 and x >= 1) and y == 5 then
- option_1 = 3
- break
- end
- end
- end
- if option_1 == 1 then
- while true do
- term.clear()
- term.setCursorPos(1,1)
- print("Backup - Client")
- print("Step 2: Choose a backup server type:")
- print("1 - Backup Server") -- y: 3, x: 1-17
- print("2 - Project Patchwork RemoteFile Protocol") -- y: 4, x: 1-42
- local event, x, y, btn = os.pullEvent()
- if event == "key" then
- option_2 = x - 1
- if option_2 <= 2 and option_2 > 0 then
- break
- end
- elseif event == "click" then
- if (x <= 17 and x >= 1) and y == 3 then
- option_2 = 1
- break
- elseif (x <= 42 and x >= 1) and y == 4 then
- option_2 = 2
- break
- end
- end
- end
- while true do
- term.clear()
- term.setCursorPos(1,1)
- print("Backup - Client")
- print("Step 3: Choose a server to backup to.")
- print("(or you can choose 'broadcast'):")
- local server = read()
- if server == "broadcast" then
- option_3 = -1
- break
- elseif type(tonumber(server)) == "number" then
- option_3 = tonumber(server)
- break
- end
- end
- end
- if option_1 == 1 then
- args[1] = "-rednet"
- if option_2 == 1 then
- args[2] = "-backup_server"
- elseif option_2 == 2 then
- args[2] = "-CommuteOS"
- end
- if option_3 == -1 then
- args[3] = nil
- else
- args[3] = option_3
- end
- elseif option_1 == 2 then
- args[1] = "-disk"
- elseif option_1 == 3 then
- args[1] = "-local"
- end
- end
- set_params()
- int_main()
- ]=]
- programs["addUser"] = [[
- os.addNewUser_dialog()
- term.clear()
- term.setCursorPos(1,1)
- ]]
- programs["whoami"] = [[
- print("You are: "..os.getCurrentUser())
- ]]
- programs["su"] = [[
- args = {...}
- local function switchUser()
- if os.getCurrentUser() == args[1] then
- print("You are already "..args[1].."!")
- return
- end
- if fs.exists("os/users/"..args[1]) then
- if os.switchUser(args[2], args[1]) then
- print("Successfully switched user!")
- print("You are now: "..args[1])
- end
- else
- print("ERROR: User does not exist!")
- end
- end
- if #args == 2 then
- switchUser()
- else
- print("USAGE: su [target user] [target password]")
- end
- ]]
- programs["delUser"] = [[
- args = {...}
- function delUser()
- if os.getCurrentUser() == "root" then
- if args[1] == "root" then
- print("ERROR: Cannot delete root!")
- return
- end
- if not fs.exists(".os/users/"..args[1]) then
- print("ERROR: User does not exist!")
- return
- end
- io.write("Are you sure you want to delete user "..args[1].."? (Y/N)>")
- local yn = io.read()
- yn = string.upper(yn)
- if yn == "Y" then
- fs.delete(".os/users/"..args[1])
- if fs.exists(args[1]) then
- fs.delete(args[1])
- end
- else
- return
- end
- else
- print("You need to be root to do this!")
- return
- end
- end
- if #args == 1 then
- delUser()
- else
- print("USAGE: delUser [username]")
- end
- ]]
- programs["changePassword"] = [[
- args = {...}
- local function writePassword(file, password)
- local handle = fs.open(file, "wb")
- local bytes = {}
- for i=1, #password do
- handle.write(string.byte(password, i, i))
- end
- handle.close()
- end
- if #args == 3 then
- if fs.exists(".os/users/"..args[1]) then
- if os.authenticate(args[1], args[2]) then
- local ciphertext = secure.rc4_cipher(args[3], args[1])
- writePassword(".os/users/"..args[1], ciphertext)
- write("Done. Your new password is: ")
- term.setTextColor(colors.lime)
- print(args[3])
- term.setTextColor(colors.white)
- else
- term.setTextColor(colors.red)
- error("Incorrect password!")
- term.setTextColor(colors.white)
- end
- else
- error("That user doesn't exist!")
- end
- else
- term.setTextColor(colors.lime)
- print("USAGE: changePassword [target] [old password] [new password]")
- term.setTextColor(colors.white)
- end
- ]]
- programs["backupServer"] = [=[
- local args = {...}
- -- backup packet structure:
- -- {identifier, originator_id, files}
- local function getDriveOne()
- for i,v in ipairs(rs.getSides()) do
- if peripheral.isPresent(v) and peripheral.getType(v) == "drive" and disk.getMountPath(v) == "disk" then
- return v
- end
- end
- end
- local restoreProgram = [[
- local function getDriveOne()
- for i,v in ipairs(rs.getSides()) do
- if peripheral.isPresent(v) and peripheral.getType(v) == "drive" and disk.getMountPath(v) == "disk" then
- return v
- end
- end
- end
- local function restore()
- if fs.exists("disk/backup") then
- local backup = fs.open("disk/backup", "r")
- local fileTable = backup.readAll()
- backup.close()
- local fileTable = textutils.unserialize(fileTable)
- print("This disk contains a stored backup of computer "..tostring(fileTable[1])..".")
- if type(fileTable[4]) == "string" then
- print("Label: "..fileTable[4]..".")
- os.setComputerLabel(fileTable[4])
- hasLabel = true
- end
- print("Total files: "..tostring(fileTable[3]))
- print("Total file size: "..tostring(fileTable[2]))
- while true do
- print("Restore from backup? (Y/N) >")
- local yn = read()
- yn = string.upper(yn)
- if yn == "Y" then
- break
- elseif yn == "N" then
- return
- else
- print("Please provide a valid response.")
- end
- end
- os.sleep(1.5)
- for i,v in ipairs(fileTable) do
- if i ~= 1 and i~= 2 and i ~= 3 then
- term.clear()
- term.setCursorPos(1,1)
- print("Restoring file.")
- print("ID: "..v[1])
- print("Path: "..v[2])
- if v[3] then
- print("Is a directory.")
- else
- print("Is a file.")
- print("Size: "..tostring(v[4]))
- end
- if v[3] then
- fs.makeDir(v[2])
- else
- local file = fs.open(v[2], "w")
- file.write(v[5])
- file.close()
- end
- os.sleep(0.5)
- end
- end
- print("Restore complete.")
- os.sleep(1)
- disk.eject(getDriveOne())
- os.reboot()
- end
- end
- restore()
- ]]
- local function writeBackupToDisk(entries, id)
- local backup = fs.open("disk/backup", "w")
- backup.write(entries)
- backup.close()
- disk.setLabel(getDriveOne(), "Backup of computer "..id)
- local programHandle = fs.open("disk/startup", "w")
- programHandle.write(restoreProgram)
- programHandle.close()
- disk.eject(getDriveOne())
- end
- local function handleIncomingPackets()
- for i,v in ipairs(rs.getSides()) do
- rednet.open(v)
- end
- while true do
- id, message = rednet.receive()
- local packet = textutils.unserialize(message)
- if type(packet) == "table" then -- valid packet
- if packet[1] == "backup" then
- if not fs.exists("backups") then
- fs.makeDir("backups")
- end
- print("Received backup from computer "..tostring(id)..".")
- local backupHandle = fs.open("backups/"..tostring(id), "w")
- backupHandle.write(packet[2])
- backupHandle.close()
- end
- end
- end
- end
- local function handleInput()
- while true do
- term.clear()
- term.setCursorPos(1,1)
- print("Please enter a backup ID:")
- local backup = read()
- if type(tonumber(backup)) == "number" then
- if fs.exists("backups/"..backup) then
- local handle = fs.open("backups/"..backup, "r")
- local files = handle.readAll()
- handle.close()
- writeBackupToDisk(files, backup)
- else
- print("That backup does not exist.")
- os.sleep(2)
- end
- else
- print("Please type in a valid ID.")
- os.sleep(2)
- end
- end
- end
- parallel.waitForAny(handleIncomingPackets, handleInput)
- ]=]
- drivers["modem"] = [[
- local modemSide = "none"
- function initialize(side)
- rednet.open(side)
- modemSide = side
- while true do
- local id, msg = rednet.receive()
- msg = textutils.unserialize(msg) -- File Packet Structure: {"FILE", fileName, fileContents}
- if type(msg) == "table" then
- if msg[1] == "FILE" then
- if not fs.exists("remoteFiles/"..os.getCurrentUser()) then
- fs.makeDir("remoteFiles/"..os.getCurrentUser())
- end
- local handle = fs.open(fs.combine("remoteFiles/"..os.getCurrentUser(), msg[2]), "w")
- handle.write(msg[3])
- handle.close()
- os.queueEvent("file_received", id, msg[2], msg[3])
- local oldX, oldY = term.getCursorPos()
- term.setCursorPos(1,1)
- term.setTextColor(colors.lime)
- term.write("File Received!")
- term.setTextColor(colors.white)
- term.setCursorPos(oldX, oldY)
- os.sleep(2)
- oldX, oldY = term.getCursorPos()
- term.setCursorPos(1,1)
- term.clearLine()
- term.setCursorPos(oldX, oldY)
- end
- end
- end
- end
- function exit()
- rednet.close(modemSide)
- end
- ]]
- drivers["printer"] = [[
- local modemSide = "none"
- function initialize(side)
- rednet.open(side)
- modemSide = side
- while true do
- local id, msg = rednet.receive()
- msg = textutils.unserialize(msg) -- File Packet Structure: {"FILE", fileName, fileContents}
- if type(msg) == "table" then
- if msg[1] == "FILE" then
- if not fs.exists("remoteFiles/"..os.getCurrentUser()) then
- fs.makeDir("remoteFiles/"..os.getCurrentUser())
- end
- local handle = fs.open(fs.combine("remoteFiles/"..os.getCurrentUser(), msg[2]), "w")
- handle.write(msg[3])
- handle.close()
- os.queueEvent("file_received", id, msg[2], msg[3])
- local oldX, oldY = term.getCursorPos()
- term.setCursorPos(1,1)
- term.setTextColor(colors.lime)
- term.write("File Received!")
- term.setTextColor(colors.white)
- term.setCursorPos(oldX, oldY)
- os.sleep(2)
- oldX, oldY = term.getCursorPos()
- term.setCursorPos(1,1)
- term.clearLine()
- term.setCursorPos(oldX, oldY)
- end
- end
- end
- end
- function exit()
- rednet.close(modemSide)
- end
- ]]
- sysFiles[".os/OS"] = [=[
- local version = "PatchworkOS v1.2"
- local osBase = ".os/"
- local fileMetadataBase = osBase.."metadata/"
- local permBase = fileMetadataBase.."perms/"
- local ownerBase = fileMetadataBase.."owners/"
- local userBase = osBase.."users/"
- local logBase = osBase.."logs/"
- local PNPDriverBase = osBase.."PNP/"
- local oldFSOpen = fs.open
- local oldOSPullEvent = os.pullEvent
- local oldOSPullEventRaw = os.pullEventRaw
- os.pullEvent = oldOSPullEventRaw
- -- BEGIN ARC4 CODE:
- -- ARCFOUR implementation in pure Lua
- -- Copyright 2008 Rob Kendrick <rjek@rjek.com>
- -- Distributed under the MIT licence
- --[[
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated document
- ation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
- to whom the Software is furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
- Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
- WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- ]]--
- local function make_byte_table(bits)
- local f = { }
- for i = 0, 255 do
- f[i] = { }
- end
- f[0][0] = bits[1] * 255
- local m = 1
- for k = 0, 7 do
- for i = 0, m - 1 do
- for j = 0, m - 1 do
- local fij = f[i][j] - bits[1] * m
- f[i ][j+m] = fij + bits[2] * m
- f[i+m][j ] = fij + bits[3] * m
- f[i+m][j+m] = fij + bits[4] * m
- end
- end
- m = m * 2
- end
- return f
- end
- local byte_xor = make_byte_table { 0, 1, 1, 0 }
- local function generate(self, count)
- local S, i, j = self.S, self.i, self.j
- local o = { }
- local char = string.char
- for z = 1, count do
- i = (i + 1) % 256
- j = (j + S[i]) % 256
- S[i], S[j] = S[j], S[i]
- o[z] = char(S[(S[i] + S[j]) % 256])
- end
- self.i, self.j = i, j
- return table.concat(o)
- end
- local function cipher(self, plaintext)
- local pad = generate(self, #plaintext)
- local r = { }
- local byte = string.byte
- local char = string.char
- for i = 1, #plaintext do
- r[i] = char(byte_xor[byte(plaintext, i)][byte(pad, i)])
- end
- return table.concat(r)
- end
- local function schedule(self, key)
- local S = self.S
- local j, kz = 0, #key
- local byte = string.byte
- for i = 0, 255 do
- j = (j + S[i] + byte(key, (i % kz) + 1)) % 256;
- S[i], S[j] = S[j], S[i]
- end
- end
- local function new_arc4(key)
- local S = { }
- local r = {
- S = S, i = 0, j = 0,
- generate = generate,
- cipher = cipher,
- schedule = schedule
- }
- for i = 0, 255 do
- S[i] = i
- end
- if key then
- r:schedule(key)
- end
- return r
- end
- -- Gee, I sure do love putting arc4 everywhere, don't I?
- local function rc4_cipher(key, text)
- local rc4 = new_arc4(key)
- rc4:generate(3072)
- local encrypted = rc4:cipher(text)
- return encrypted
- end
- local function readPassword(file)
- local handle = oldFSOpen(file, "rb")
- local bytes = {}
- while true do
- local byte = handle.read()
- if byte ~= nil then
- table.insert(bytes, byte)
- else
- break
- end
- end
- handle.close()
- return string.char(unpack(bytes))
- end
- local function writePassword(file, password)
- local handle = oldFSOpen(file, "wb")
- local bytes = {}
- for i=1, #password do
- handle.write(string.byte(password, i, i))
- end
- handle.close()
- end
- local currentUser = "root"
- local function writeToLog(logFile, text)
- local logHandle = oldFSOpen(logBase..logFile, "a")
- logHandle.writeLine("["..currentUser.."] "..text)
- logHandle.close()
- end
- fs.makeDir(permBase)
- fs.makeDir(ownerBase)
- fs.makeDir(userBase)
- fs.makeDir(logBase)
- fs.makeDir(PNPDriverBase)
- local function makeFileSafe(file)
- file = string.gsub(file, "%/", "#002F")
- file = string.gsub(file, "%\\", "#005C")
- file = string.gsub(file, "%:", "#003A")
- file = string.gsub(file, "%*", "#002A")
- file = string.gsub(file, "%?", "#003F")
- file = string.gsub(file, "%\"", "#0022")
- file = string.gsub(file, "%<", "#003C")
- file = string.gsub(file, "%>", "#003E")
- file = string.gsub(file, "%|", "#007C")
- return file
- end
- local function safeFilenameToTrueName(file)
- file = string.gsub(file, "#002F", "/")
- file = string.gsub(file, "#005C", "\\")
- file = string.gsub(file, "#003A", ":")
- file = string.gsub(file, "#002A", "*")
- file = string.gsub(file, "#003F", "?")
- file = string.gsub(file, "#0022", "\"")
- file = string.gsub(file, "#003C", "<")
- file = string.gsub(file, "#003E", ">")
- file = string.gsub(file, "#007C", "|")
- return file
- end
- local oldFSDelete = fs.delete
- local oldFSMove = fs.move
- local oldFSCopy = fs.copy
- local oldLoadFile = loadfile
- local oldDoFile = dofile
- local oldOSLoadAPI = os.loadAPI
- local function newFilePrep(file)
- if not fs.exists(file) then
- local permsHandle = oldFSOpen(fs.combine(permBase, makeFileSafe(file)), "w")
- permsHandle.write(textutils.serialize({[currentUser]={["delete"]=true, ["read"]=true, ["write"]=true, ["execute"]=true}}))
- permsHandle.close()
- local ownerHandle = oldFSOpen(fs.combine(ownerBase, makeFileSafe(file)), "w")
- ownerHandle.write(currentUser)
- ownerHandle.close()
- return true
- else
- return false, "file already exists"
- end
- end
- local function getFileMetadata(file)
- if not fs.exists(fs.combine(ownerBase, makeFileSafe(file))) then
- local ownerHandle = oldFSOpen(fs.combine(ownerBase, makeFileSafe(file)), "w")
- ownerHandle.write("root")
- ownerHandle.close()
- end
- if not fs.exists(fs.combine(permBase, makeFileSafe(file))) then
- local permsHandle = oldFSOpen(fs.combine(permBase, makeFileSafe(file)), "w")
- permsHandle.write(textutils.serialize({["root"]={["delete"]=true, ["read"]=true, ["write"]=true, ["execute"]=true}}))
- permsHandle.close()
- end
- local permsHandle = oldFSOpen(fs.combine(permBase, makeFileSafe(file)), "r")
- local ownerHandle = oldFSOpen(fs.combine(ownerBase, makeFileSafe(file)), "r")
- local perms = textutils.unserialize(permsHandle.readAll())
- local owner = ownerHandle.readAll()
- permsHandle.close()
- ownerHandle.close()
- return perms, owner
- end
- local function isAllowed(file, action)
- if currentUser == "root" then
- return true
- end
- if fs.exists(file) then
- if fs.isReadOnly(file) and (action == "read" or action == "execute") then
- return true
- elseif (string.find(file, ".metadata") ~= nil or string.find(file, ".os") ~= nil) then
- return false
- elseif (string.sub(file,1, 4) == "bin/") and (action == "read" or action == "execute") then
- return true
- end
- local perms, owner = getFileMetadata(file)
- if currentUser == owner then
- return true
- elseif action == "delete" or action == "write" or action == "read" or action == "execute" then
- if perms[currentUser] then
- return perms[currentUser][action]
- else
- return false
- end
- elseif action == "modperms" then
- return (owner == currentUser)
- else
- error("isAllowed: Invalid action parameter")
- end
- else
- return true
- end
- end
- os.getPerms = function(file)
- local perms, owner = getFileMetadata(file)
- return perms[currentUser], owner
- end
- os.setPerm = function(file, perm, value, user)
- if user == nil then
- user = currentUser
- end
- if (perm ~= "delete") and (perm ~= "read") and (perm ~= "write") and (perm ~= "execute") then
- return false, "invalid permission"
- end
- if fs.exists(file) then
- if isAllowed(file, "modperms") and not fs.isReadOnly(file) then
- writeToLog("FilePerm", "Setting perms for file: "..file..", user: "..user)
- writeToLog("FilePerm", "Perm: "..perm..", value: "..tostring(value))
- local perms = getFileMetadata(file)
- if perms[user] == nil then
- perms[user] = {["delete"]=false, ["read"]=false, ["write"]=false, ["execute"]=false}
- end
- perms[user][perm] = value
- local permsHandle = oldFSOpen(fs.combine(permBase, makeFileSafe(file)), "w")
- permsHandle.write(textutils.serialize(perms))
- permsHandle.close()
- return true
- else
- writeToLog("FilePerm", "Unauthorized user attempted to set perms for file: "..file..".")
- return false, "not owner"
- end
- else
- writeToLog("FilePerm", "User attempted to set perms for nonexistent file.")
- return false, "file does not exist"
- end
- end
- os.setOwner = function(file, newOwner)
- if isAllowed(file, "modperms") then
- writeToLog("FilePerm", "File "..file.." is switching owners to "..newOwher)
- local ownerHandle = oldFSOpen(fs.combine(ownerBase, makeFileSafe(file)), "r")
- ownerHandle.write(newOwner)
- ownerHandle.close()
- return true
- else
- writeToLog("FilePerm", "Unauthorized user attempted to change the ownership of file:"..file..".")
- return false, "not owner"
- end
- end
- -- begin FS rewrites
- fs.open = function(file, mode)
- if fs.exists(file) then
- if mode == "a" or mode == "ab" or mode == "w" or mode == "wb" then
- if isAllowed(file, "write") then
- writeToLog("FileAccess", "User opened "..file.." for writing.")
- return oldFSOpen(file, mode)
- else
- writeToLog("FileAccess", "User attempted to write to file "..file.." without permission.")
- end
- elseif mode == "r" or mode == "rb" then
- if isAllowed(file, "read") then
- writeToLog("FileAccess", "User opened "..file.." for reading.")
- return oldFSOpen(file, mode)
- else
- writeToLog("FileAccess", "User attempted to read from file "..file.." without permission.")
- end
- end
- else
- writeToLog("FileAccess", "User opened new file "..file..".")
- newFilePrep(file)
- return oldFSOpen(file, mode)
- end
- end
- fs.delete = function(file)
- if fs.exists(file) then
- if isAllowed(file, "delete") then
- writeToLog("FileAccess", "User deleted "..file..".")
- return oldFSDelete(file)
- else
- writeToLog("FileAccess", "User tried to delete "..file.." without permission.")
- end
- end
- end
- fs.copy = function(oldFile, newFile)
- if not fs.exists(newFile) then
- if isAllowed(oldFile, "read") then
- writeToLog("FileAccess", "User copied "..oldFile.." to "..newFile..".")
- return oldFSCopy(oldFile, newFile)
- else
- writeToLog("FileAccess", "User tried to copy "..oldFile.." to "..newFile.." without permission.")
- end
- end
- end
- fs.move = function(oldFile, newFile)
- if not fs.exists(newFile) then
- if isAllowed(oldFile, "read") then
- writeToLog("FileAccess", "User moved "..oldFile.." to "..newFile..".")
- return oldFSMove(oldFile, newFile)
- else
- writeToLog("FileAccess", "User tried to move "..oldFile.." to "..newFile.." without permission.")
- end
- end
- end
- loadfile = function(file)
- if fs.exists(file) then
- if isAllowed(file, "execute") then
- writeToLog("FileExecute", "Executing: "..file)
- local handle = oldFSOpen(file, "r")
- local func, err = loadstring(handle.readAll(), fs.getName(file))
- handle.close()
- return func, err
- else
- writeToLog("FileExecute", "User tried to execute "..file.." without permission.")
- return nil, "Cannot execute"
- end
- else
- return nil, "File not found"
- end
- end
- dofile = function(file)
- local func, err = loadfile(file)
- if not func then
- error("dofile: "..err, 2)
- else
- setfenv(func, getfenv(2))
- return func()
- end
- end
- local function trustedLoadAPI(path)
- local handle = oldFSOpen(path, "r")
- local data = handle.readAll()
- handle.close()
- local func = loadstring(data)
- local env = {}
- setmetatable(env, {__index = _G})
- setfenv(func, env)
- func()
- local api = {}
- for i,v in pairs(env) do
- api[i] = v
- end
- _G[fs.getName(path)] = api
- end
- local oldOSRun = os.run
- os.run = function(env, path, ...)
- if isAllowed(path, "execute") then
- writeToLog("FileExecute", "Executing: "..path)
- return oldOSRun(env, path, unpack(arg))
- else
- writeToLog("FileExecute", "User tried to execute "..path.." without permission.")
- return false, "cannot execute"
- end
- end
- if fs.exists(osBase.."arcfour") then -- of course
- os.loadAPI(osBase.."arcfour")
- os.sleep(1)
- else
- if http then
- local webHandle = http.get("http://pastebin.com/raw.php?i=73q8zCPc")
- local data = webHandle.readAll()
- webHandle.close()
- local fileHandle = fs.open(osBase.."arcfour", "w")
- fileHandle.write(data)
- fileHandle.close()
- os.loadAPI(osBase.."arcfour")
- else
- print("arcfour API not found!")
- end
- end
- local loadUsers = function()
- local users = {}
- local passwordCiphertext = {}
- for i,v in ipairs(fs.list(userBase)) do
- print(i..": "..v)
- local handle = oldFSOpen(userBase..v, "rb")
- local bytes = {}
- while true do
- local byte = handle.read()
- if byte then
- table.insert(bytes, byte)
- else
- break
- end
- end
- handle.close()
- users[v] = true
- passwordCiphertext[v] = string.char(unpack(bytes))
- end
- return users, passwordCiphertext
- end
- local oldRSSetOutput = rs.setOutput
- local oldRSSetBundledOutput = rs.setBundledOutput
- rs.setOutput = function(side, value)
- writeToLog("RS", "Set redstone output on "..side.." to "..tostring(value)..".")
- return oldRSSetOutput(side, value)
- end
- rs.setBundledOutput = function(side, value)
- writeToLog("RS", "Set bundled redstone output on "..side.." to "..tostring(value)..".")
- return oldRSSetBundledOutput(side, value)
- end
- redstone.setOutput = rs.setOutput
- redstone.setBundledOutput = rs.setBundledOutput
- if http then
- local oldHTTPRequest = http.request
- local oldHTTPGet = http.get
- local oldHTTPPost = http.post
- http.request = function(url, postData)
- if postData == nil then
- writeToLog("HTTP", "Request sent to "..url..", no data sent.")
- else
- writeToLog("HTTP", "Request sent to "..url..", data:"..postData)
- end
- return oldHTTPRequest(url, postData)
- end
- http.get = function(url)
- writeToLog("HTTP", "Fetched data from "..url..".")
- return oldHTTPGet(url)
- end
- http.post = function(url, postData)
- writeToLog("HTTP", "Sent data:"..postData.." to url:"..url..".")
- return oldHTTPPost(url, postData)
- end
- print("Done.")
- end
- os.version = function()
- return version
- end
- local oldShellRun = shell.run
- local function existsInFolder(dir, file)
- for _,v in ipairs(fs.list(dir)) do
- if v == file then
- return true -- found a match in the toplevel dir
- end
- end
- end
- shell.run = function(program, ...)
- writeToLog("FileExecute", "shell.run called, program:"..program)
- oldShellRun(program, unpack(arg))
- end
- local oldRednetSend = rednet.send
- local oldRednetBroadcast = rednet.broadcast
- local oldRednetAnnounce = rednet.announce
- rednet.send = function(senderID, message)
- writeToLog("Rednet", "Sent message to id "..senderID.." with message "..message)
- return oldRednetSend(senderID, message)
- end
- rednet.broadcast = function(message)
- writeToLog("Rednet", "Broadcasted message "..message)
- return oldRednetBroadcast(message)
- end
- rednet.announce = function()
- writeToLog("Rednet", "Sent announce message.")
- return oldRednetAnnounce()
- end
- local oldOSShutdown = os.shutdown
- local oldOSReboot = os.reboot
- local oldOSLoadAPI = os.loadAPI
- local oldOSSetLabel = os.setComputerLabel
- os.shutdown = function()
- writeToLog("OS", "Shutting down "..version..". Uptime:"..tostring(os.clock()))
- oldOSShutdown()
- end
- os.reboot = function()
- writeToLog("OS", "Rebooting "..version..". Uptime:"..tostring(os.clock()))
- oldOSReboot()
- end
- os.loadAPI = function(api)
- writeToLog("OS", "Loading API: "..api)
- oldOSLoadAPI(api)
- end
- os.setComputerLabel = function(label)
- writeToLog("OS", "Setting computer label to:"..label)
- oldOSSetLabel(label)
- end
- if turtle then
- if fs.exists(osBase.."turtle") then
- local settingsFile = fs.open(osBase.."turtle", "r")
- local canMove = settingsFile.readLine()
- local canDig = settingsFile.readLine()
- local canPlace = settingsFile.readLine()
- local canSuck = settingsFile.readLine()
- settingsFile.close()
- else
- local handle = fs.open(osBase.."turtle", "w")
- handle.write("true")
- handle.write("true")
- handle.write("true")
- handle.write("true")
- handle.close()
- local canMove = "true"
- local canDig = "true"
- local canPlace = "true"
- local canSuck = "true"
- end
- local oldTurtleDig = turtle.dig
- local oldTurtleDigUp = turtle.digUp
- local oldTurtleDigDown = turtle.digDown
- local oldTurtlePlaceDown = turtle.placeDown
- local oldTurtlePlaceUp = turtle.placeUp
- local oldTurtlePlace = turtle.place
- local oldTurtleForward = turtle.forward
- local oldTurtleBack = turtle.back
- local oldTurtleTurnLeft = turtle.turnLeft
- local oldTurtleTurnRight = turtle.turnRight
- local oldTurtleUp = turtle.up
- local oldTurtleDown = turtle.down
- local oldTurtleSuck = turtle.suck
- local oldTurtleSuckUp = turtle.suckUp
- local oldTurtleSuckDown = turtle.suckDown
- local oldTurtleRefuel = turtle.refuel
- turtle.dig = function()
- if canDig == "true" or currentUser == "root" then
- writeToLog("Turtle", "Broke block in front.")
- return oldTurtleDig()
- else
- writeToLog("Turtle", "Tried to dig, but digging has been diabled.")
- return false
- end
- end
- turtle.digUp = function()
- if canDig == "true" or currentUser == "root" then
- writeToLog("Turtle", "Broke block on top.")
- return oldTurtleDigUp()
- else
- writeToLog("Turtle", "Tried to dig, but digging has been diabled.")
- return false
- end
- end
- turtle.digDown = function()
- if canDig == "true" or currentUser == "root" then
- writeToLog("Turtle", "Broke block under.")
- return oldTurtleDigDown()
- else
- writeToLog("Turtle", "Tried to dig, but digging has been diabled.")
- return false
- end
- end
- turtle.place = function()
- if canPlace == "true" or currentUser == "root" then
- writeToLog("Turtle", "Placed block in front.")
- return oldTurtlePlace()
- else
- writeToLog("Turtle", "Tried to place, but placing has been diabled.")
- return false
- end
- end
- turtle.placeDown = function()
- if canPlace == "true" or currentUser == "root" then
- writeToLog("Turtle", "Placed block under.")
- return oldTurtlePlaceDown()
- else
- writeToLog("Turtle", "Tried to place, but placing has been diabled.")
- return false
- end
- end
- turtle.placeUp = function()
- if canPlace == "true" or currentUser == "root" then
- writeToLog("Turtle", "Placed block on top.")
- return oldTurtlePlaceUp()
- else
- writeToLog("Turtle", "Tried to place, but placing has been diabled.")
- return false
- end
- end
- turtle.forward = function()
- if canMove == "true" or currentUser == "root" then
- writeToLog("Turtle", "Moved forward.")
- return oldTurtleForward()
- else
- writeToLog("Turtle", "Tried to move, but movement has been diabled.")
- return false
- end
- end
- turtle.back = function()
- if canMove == "true" or currentUser == "root" then
- writeToLog("Turtle", "Moved backwards.")
- return oldTurtleBack()
- else
- writeToLog("Turtle", "Tried to move, but movement has been diabled.")
- return false
- end
- end
- turtle.turnLeft = function()
- if canMove == "true" or currentUser == "root" then
- writeToLog("Turtle", "Turned left.")
- return oldTurtleTurnLeft()
- else
- writeToLog("Turtle", "Tried to move, but movement has been diabled.")
- return false
- end
- end
- turtle.up = function()
- if canMove == "true" or currentUser == "root" then
- writeToLog("Turtle", "Went up.")
- return oldTurtleUp()
- else
- writeToLog("Turtle", "Tried to move, but movement has been diabled.")
- return false
- end
- end
- turtle.down = function()
- if canMove == "true" or currentUser == "root" then
- writeToLog("Turtle", "Went down.")
- return oldTurtleDown()
- else
- writeToLog("Turtle", "Tried to move, but movement has been diabled.")
- return false
- end
- end
- turtle.turnRight = function()
- if canMove == "true" or currentUser == "root" then
- writeToLog("Turtle", "Turned right.")
- return oldTurtleTurnRight()
- else
- writeToLog("Turtle", "Tried to move, but movement has been diabled.")
- return false
- end
- end
- turtle.suck = function()
- if canSuck == "true" or currentUser == "root" then
- writeToLog("Turtle", "Retrieved items.")
- return oldTurtleSuck()
- else
- writeToLog("Turtle", "Tried to retrieve items, but item retrieval has been diabled.")
- return false
- end
- end
- turtle.suckUp = function()
- if canSuck == "true" or currentUser == "root" then
- writeToLog("Turtle", "Retrieved items from above.")
- return oldTurtleSuckUp()
- else
- writeToLog("Turtle", "Tried to retrieve items, but item retrieval has been diabled.")
- return false
- end
- end
- turtle.suckDown = function()
- if canSuck == "true" or currentUser == "root" then
- writeToLog("Turtle", "Retrieved items from underneath.")
- return oldTurtleSuckDown()
- else
- writeToLog("Turtle", "Tried to retrieve items, but item retrieval has been diabled.")
- return false
- end
- end
- turtle.refuel = function()
- writeToLog("Turtle", "Refueled turtle, current fuel level is: "..turtle.getFuelLevel())
- return oldTurtleRefuel()
- end
- end
- local users, pwCtext = loadUsers()
- os.authenticate = function(username, password)
- if users[username] then
- local pText = arcfour.rc4_cipher(password, pwCtext[username])
- return (pText == username)
- else
- return false, "user not found"
- end
- end
- os.switchUser = function(targetUser, password)
- if os.authenticate(targetUser, password) then
- currentUser = targetUser
- return true
- else
- return false
- end
- end
- os.newUser = function(user, password)
- if currentUser == "root" then
- local handle = oldFSOpen(userBase..user, "wb")
- local cText = arcfour.rc4_cipher(password, user)
- for i=1, #cText do
- handle.write(string.byte(string.sub(cText, i, i)))
- end
- handle.close()
- return true
- else
- return false
- end
- end
- os.getCurrentUser = function()
- return currentUser
- end
- os.retrieveCredentials = function()
- local function readAdv(maxChars, startX, startY, replaceChar, returnToStart, backgroundChar)
- term.setCursorBlink(true)
- local function clearArea(clearLine, clearX, clearArea, replaceChar)
- local formerX,formerY = term.getCursorPos()
- for i=0, clearArea do
- term.setCursorPos(clearX+i, clearLine)
- if replaceChar ~= nil then
- io.write(replaceChar)
- else
- io.write(" ")
- end
- end
- term.setCursorPos(formerX,formerY)
- end
- local x,y = term.getCursorPos()
- term.setCursorPos(startX, startY)
- clearArea(startY, startX, maxChars, backgroundChar)
- local input = ""
- while true do
- local event, key = os.pullEvent()
- if event == "key" then
- if key == 28 or key == 156 then
- if returnToStart then
- term.setCursorPos(x,y)
- end
- return input
- elseif key == 14 then
- input = string.sub(input, 1, #input-1)
- term.setCursorPos(startX, startY)
- clearArea(startY, startX, maxChars, backgroundChar)
- if replaceChar == nil then
- io.write(input)
- else
- for i=1, #input do
- io.write(replaceChar)
- end
- end
- end
- elseif event == "char" then
- if maxChars ~= nil then
- if #input <= maxChars then
- input = input..key
- term.setCursorPos(startX, startY)
- clearArea(startY, startX, maxChars, backgroundChar)
- if replaceChar == nil then
- io.write(input)
- else
- for i=1, #input do
- io.write(replaceChar)
- end
- end
- end
- end
- end
- end
- end
- local function printLoginScreen(startX, startY)
- term.setCursorPos(startX, startY)
- print("===========================")
- term.setCursorPos(startX, startY+1)
- write("| ")
- term.setTextColor(colors.green)
- write("Please log in")
- term.setTextColor(colors.white)
- print(": |")
- term.setCursorPos(startX, startY+2)
- print("===========================")
- term.setCursorPos(startX, startY+3)
- print("| Username: |")
- term.setCursorPos(startX, startY+4)
- print("| |")
- term.setCursorPos(startX, startY+5)
- print("===========================")
- term.setCursorPos(startX, startY+6)
- print("| Password: |")
- term.setCursorPos(startX, startY+7)
- print("| |")
- term.setCursorPos(startX, startY+8)
- print("===========================")
- term.setCursorPos(1,0)
- end
- --LOGINSCRN SPECS:
- --XLen: 27
- --YLen: 11
- --Textbox Space: 26
- --Username XStart:2
- --Username YStart:5
- --Password XStart:2
- --Password YStart:8
- term.clear()
- if not turtle then
- printLoginScreen(13,4)
- else
- printLoginScreen(1,1)
- end
- term.setTextColor(colors.lightGray)
- if not turtle then
- username = readAdv(24, 14, 8, nil, true, nil)
- password = readAdv(24, 14, 11, "#", true, nil)
- else
- username = readAdv(24, 2, 5, nil, true, nil)
- password = readAdv(24, 2, 8, "#", true, nil)
- end
- term.setTextColor(colors.white)
- term.clear()
- term.setCursorPos(1,1)
- term.setCursorBlink(false)
- return username, password
- end
- os.addNewUser_screen = function()
- if currentUser == "root" then
- term.clear()
- term.setCursorPos(1,1)
- local function readAdv(maxChars, startX, startY, replaceChar, returnToStart, backgroundChar)
- term.setCursorBlink(true)
- local function clearArea(clearLine, clearX, clearArea, replaceChar)
- local formerX,formerY = term.getCursorPos()
- for i=0, clearArea do
- term.setCursorPos(clearX+i, clearLine)
- if replaceChar ~= nil then
- io.write(replaceChar)
- else
- io.write(" ")
- end
- end
- term.setCursorPos(formerX,formerY)
- end
- local x,y = term.getCursorPos()
- term.setCursorPos(startX, startY)
- clearArea(startY, startX, maxChars, backgroundChar)
- local input = ""
- while true do
- local event, key = os.pullEvent()
- if event == "key" then
- if key == 28 or key == 156 then
- if returnToStart then
- term.setCursorPos(x,y)
- end
- return input
- elseif key == 14 then
- input = string.sub(input, 1, #input-1)
- term.setCursorPos(startX, startY)
- clearArea(startY, startX, maxChars, backgroundChar)
- if replaceChar == nil then
- io.write(input)
- else
- for i=1, #input do
- io.write(replaceChar)
- end
- end
- end
- elseif event == "char" then
- if maxChars ~= nil then
- if #input <= maxChars then
- input = input..key
- term.setCursorPos(startX, startY)
- clearArea(startY, startX, maxChars, backgroundChar)
- if replaceChar == nil then
- io.write(input)
- else
- for i=1, #input do
- io.write(replaceChar)
- end
- end
- end
- end
- end
- end
- end
- local startX = 1
- local startY = 1
- if not turtle then
- startX = 13
- startY = 3
- end
- term.setCursorPos(startX, startY)
- print("===========================")
- term.setCursorPos(startX, startY+1)
- write("| ")
- term.setTextColor(colors.lime)
- write("New User")
- term.setTextColor(colors.white)
- print(": |")
- term.setCursorPos(startX, startY+2)
- print("===========================")
- term.setCursorPos(startX, startY+3)
- print("| Username: |")
- term.setCursorPos(startX, startY+4)
- print("| |")
- term.setCursorPos(startX, startY+5)
- print("===========================")
- term.setCursorPos(startX, startY+6)
- print("| Password: |")
- term.setCursorPos(startX, startY+7)
- print("| |")
- term.setCursorPos(startX, startY+8)
- print("===========================")
- term.setTextColor(colors.lightGray)
- if not turtle then
- username = readAdv(24, 14, 8, nil, true, nil)
- password = readAdv(24, 14, 11, "#", true, nil)
- else
- user = readAdv(24, 2, 5, nil, true, nil)
- pass = readAdv(24, 2, 8, nil, true, nil)
- end
- term.setTextColor(colors.white)
- return user, pass
- end
- end
- local function makeRootAcct()
- term.clear()
- term.setCursorPos(1,1)
- local function readAdv(maxChars, startX, startY, replaceChar, returnToStart, backgroundChar)
- term.setCursorBlink(true)
- local function clearArea(clearLine, clearX, clearArea, replaceChar)
- local formerX,formerY = term.getCursorPos()
- for i=0, clearArea do
- term.setCursorPos(clearX+i, clearLine)
- if replaceChar ~= nil then
- io.write(replaceChar)
- else
- io.write(" ")
- end
- end
- term.setCursorPos(formerX,formerY)
- end
- local x,y = term.getCursorPos()
- term.setCursorPos(startX, startY)
- clearArea(startY, startX, maxChars, backgroundChar)
- local input = ""
- while true do
- local event, key = os.pullEvent()
- if event == "key" then
- if key == 28 or key == 156 then
- if returnToStart then
- term.setCursorPos(x,y)
- end
- return input
- elseif key == 14 then
- input = string.sub(input, 1, #input-1)
- term.setCursorPos(startX, startY)
- clearArea(startY, startX, maxChars, backgroundChar)
- if replaceChar == nil then
- io.write(input)
- else
- for i=1, #input do
- io.write(replaceChar)
- end
- end
- end
- elseif event == "char" then
- if maxChars ~= nil then
- if #input <= maxChars then
- input = input..key
- term.setCursorPos(startX, startY)
- clearArea(startY, startX, maxChars, backgroundChar)
- if replaceChar == nil then
- io.write(input)
- else
- for i=1, #input do
- io.write(replaceChar)
- end
- end
- end
- end
- end
- end
- end
- local startX = 1
- local startY = 1
- local pass = "root"
- if not turtle then
- startX = 13
- startY = 4
- end
- term.setCursorPos(startX, startY)
- print("===========================")
- term.setCursorPos(startX, startY+1)
- write("| ")
- term.setTextColor(colors.lime)
- write("New User")
- term.setTextColor(colors.white)
- print(": |")
- term.setCursorPos(startX, startY+2)
- print("===========================")
- term.setCursorPos(startX, startY+3)
- print("| Username: |")
- term.setCursorPos(startX, startY+4)
- print("|root |")
- term.setCursorPos(startX, startY+5)
- print("===========================")
- term.setCursorPos(startX, startY+6)
- print("| Password: |")
- term.setCursorPos(startX, startY+7)
- print("| |")
- term.setCursorPos(startX, startY+8)
- print("===========================")
- term.setTextColor(colors.lightGray)
- if turtle then
- pass = readAdv(24, 2, 8, nil, true, nil)
- else
- pass = readAdv(24, 14, 11, nil, true, nil)
- end
- term.setTextColor(colors.white)
- return pass
- end
- os.addNewUser_noDialog = function(user, pass)
- if currentUser == "root" then
- local ciphertext = rc4_cipher(pass, user)
- writePassword(userBase..user, ciphertext)
- end
- end
- os.addNewUser_dialog = function()
- if currentUser == "root" then
- os.addNewUser_noDialog(os.addNewUser_screen())
- end
- end
- local function drawLine(char)
- local maxX = term.getSize()
- print(" "..string.rep(char, maxX-2))
- end
- local function printCentered(input)
- local maxX = term.getSize()
- print(string.rep(" ", math.floor((maxX - string.len(input))/2))..input)
- end
- local function printColored(...)
- for i=1, arg["n"], 2 do
- if term.isColor() then
- term.setTextColor(arg[i])
- end
- write(arg[i+1])
- end
- print("")
- if term.isColor() then
- term.setTextColor(colors.white)
- end
- end
- local PNPDriverBase = osBase.."PNP/"
- local peripherals = {}
- local function loadPeripheral(peripheral)
- local function copy()
- if not fs.exists(".temp/PNPDrivers/") then
- fs.makeDir(".temp/PNPDrivers/")
- end
- local handle1 = oldFSOpen(PNPDriverBase..peripheral, "r")
- local handle2 = oldFSOpen(".temp/PNPDrivers/"..peripheral, "w")
- handle2.write(handle1.readAll())
- handle1.close()
- handle2.close()
- end
- if fs.exists(PNPDriverBase..peripheral) then
- copy()
- trustedLoadAPI(".temp/PNPDrivers/"..peripheral)
- return true
- else
- return false
- end
- end
- function runPNPFunc(peripheral, func, arg1)
- arg1 = arg1 or ""
- local chkString = "local function func() if type("..peripheral..") ~= \"table\" then return false else return type("..peripheral.."."..func.."()) == \"function\" end end return func()"
- local checkFunc = loadstring(chkString)
- if checkFunc() then
- local funcString = "local function func_call() "..peripheral.."."..func.."("..arg1..")".." end return func_call()"
- local func = loadstring(funcString)
- return func()
- end
- end
- function getPNPFunc(peripheral, func, arg1)
- arg1 = arg1 or ""
- local chkString = "local function func() if type("..peripheral..") ~= \"table\" then return false else return type("..peripheral.."."..func..") == \"function\" end end return func()"
- local checkFunc = loadstring(chkString)
- if checkFunc() then
- local funcString = "local function func_call() "..peripheral.."."..func.."("..arg1..")".." end return func_call()"
- local func = loadstring(funcString)
- return func
- end
- end
- local function pnp_waitForPeripheralEvent()
- while true do
- local event, side = os.pullEvent()
- if event == "peripheral" or event == "peripheral_detach" then
- return
- end
- end
- end
- local function pnp_checkOnce()
- for i,v in ipairs(rs.getSides()) do
- if peripheral.isPresent(v) then
- runPNPFunc(peripheral.getType(v), "exit")
- os.unloadAPI(peripheral.getType(v))
- end
- end
- peripherals = {}
- for index,side in ipairs(rs.getSides()) do
- if peripheral.isPresent(side) then
- if loadPeripheral(peripheral.getType(side)) then
- table.insert(peripherals, getPNPFunc(peripheral.getType(side), "initialize", "\""..side.."\""))
- end
- end
- end
- parallel.waitForAny(pnp_waitForPeripheralEvent, parallel.waitForAll(unpack(peripherals)))
- end
- term.clear()
- term.setCursorPos(1,1)
- if #fs.list(userBase) == 0 then
- printCentered("Hello.")
- printCentered("Welcome to "..version..".")
- printCentered("We'll need you to make a root account")
- printCentered("Before you can go on.")
- os.sleep(2)
- os.addNewUser_noDialog("root", makeRootAcct())
- os.reboot()
- end
- local function readCommands()
- local commandHistory = {}
- while true do
- write(os.getCurrentUser().."@")
- if os.getComputerLabel() == nil then
- write(tostring(os.getComputerID()))
- else
- write(os.getComputerLabel())
- end
- write(":")
- if os.getCurrentUser() == "root" then
- if shell.dir() == "" then
- write("-# ")
- else
- write("/"..shell.dir().."# ")
- end
- else
- if shell.dir() == "" then
- write("-$ ")
- else
- write("/"..shell.dir().."$ ")
- end
- end
- local input = read(nil, commandHistory)
- table.insert(commandHistory, input)
- local input_words = {}
- for i in input:gmatch("%S+") do
- table.insert(input_words, i)
- end
- if input_words[1] ~= nil then
- os.pullEvent = oldOSPullEvent
- shell.run(input_words[1], unpack(input_words, 2))
- os.pullEvent = oldOSPullEventRaw
- end
- os.sleep(0)
- end
- end
- if os.switchUser(os.retrieveCredentials()) then
- term.clear()
- term.setCursorPos(1,1)
- shell.setPath(shell.path()..":/bin")
- parallel.waitForAll(readCommands, function() while true do pnp_checkOnce() end end)
- end
- ]=]
- sysFiles["startup"] = [[
- local oldTermSetTextColor = term.setTextColor
- local oldTermSetBGColor = term.setBackgroundColor
- if not term.isColor or not term.isColor() then
- term.setTextColor = function() oldTermSetTextColor(colors.white) end
- term.setBackgroundColor = function() oldTermSetTextColor(colors.black) end
- end
- if not fs.exists(".os/rpc") then
- local handle = http.get("http://pastebin.com/raw.php?i=AJEnqBtA")
- local data = handle.readAll()
- handle.close()
- local file = fs.open(".os/rpc", "w")
- file.write(data)
- file.close()
- end
- os.loadAPI(".os/rpc")
- if turtle and fs.exists(".os/allowTurtleRPC") then
- rpc.new("forward", "return turtle.forward()")
- rpc.new("turnLeft", "return turtle.turnLeft()")
- rpc.new("turnRight", "return turtle.turnRight()")
- rpc.new("back", "return turtle.back()")
- rpc.new("up", "return turtle.up()")
- rpc.new("down", "return turtle.down()")
- rpc.new("dig", "return turtle.dig()")
- rpc.new("digUp", "return turtle.digUp()")
- rpc.new("digDown", "return turtle.digDown()")
- rpc.new("place", "local args = {...} return turtle.place(args[1])")
- rpc.new("placeUp", "return turtle.placeUp()")
- rpc.new("placeDown", "return turtle.placeDown()")
- rpc.new("detect", "return turtle.detect()")
- rpc.new("detectUp", "return turtle.detectUp()")
- rpc.new("detectDown", "return turtle.detectDown()")
- rpc.new("compare", "return turtle.compare()")
- rpc.new("compareTo", "local args = {...} return turtle.compareTo(tonumber(args[1]))")
- rpc.new("compareUp", "return turtle.compareUp()")
- rpc.new("compareDown", "return turtle.compareDown()")
- rpc.new("suck", "return turtle.suck()")
- rpc.new("suckUp", "return turtle.suckUp()")
- rpc.new("suckDown", "return turtle.suckDown()")
- rpc.new("drop", "return turtle.drop()")
- rpc.new("craft", "return turtle.craft()")
- rpc.new("dropUp", "return turtle.dropUp()")
- rpc.new("dropDown", "return turtle.dropDown()")
- rpc.new("select", "local args = {...} return turtle.select(tonumber(args[1]))")
- rpc.new("getItemCount", "local args = {...} return turtle.getItemCount(tonumber(args[1]))")
- rpc.new("getItemSpace", "local args = {...} return turtle.getItemSpace(tonumber(args[1]))")
- rpc.new("refuel", "local args = {...} return turtle.refuel(tonumber(args[1]))")
- rpc.new("transferTo", "local args = {...} return turtle.transferTo(tonumber(args[1]), tonumber(args[2]))")
- rpc.new("getFuelLevel", "return turtle.getFuelLevel()")
- end
- shell.run(".os/OS")
- term.setTextColor = oldTermSetTextColor
- term.setBackgroundColor = oldTermSetBGColor
- ]]
- local osBase = ".os/"
- local fileMetadataBase = osBase.."metadata/"
- local permBase = fileMetadataBase.."perms/"
- local ownerBase = fileMetadataBase.."owners/"
- local userBase = osBase.."users/"
- local logBase = osBase.."logs/"
- local PNPDriverBase = osBase.."PNP/"
- fs.makeDir(permBase)
- fs.makeDir(ownerBase)
- fs.makeDir(userBase)
- fs.makeDir(logBase)
- fs.makeDir(PNPDriverBase)
- fs.makeDir("bin")
- for i,v in pairs(programs) do
- if i ~= "turtleSettings" then
- local handle = fs.open("bin/"..i, "w")
- handle.write(v)
- handle.close()
- elseif turtle then
- local handle = fs.open("bin/"..i, "w")
- handle.write(v)
- handle.close()
- end
- end
- for i,v in pairs(drivers) do
- local handle = fs.open(fs.combine(PNPDriverBase, i), "w")
- handle.write(v)
- handle.close()
- end
- for i,v in pairs(sysFiles) do
- local handle = fs.open(i, "w")
- handle.write(v)
- handle.close()
- end
- fs.delete(shell.resolveProgram(shell.getRunningProgram()))
- os.reboot()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement