Computercraft/src/main/programs/lib/networking.lua
2024-06-01 21:27:46 +02:00

111 lines
2.6 KiB
Lua
Executable File

basic_functions = require("lib.basic-functions")
hash = require("lib.hash")
--aes = require("lib.aes") --aes does not yet work with require
os.loadAPI("bos/lib/aes.lua")
function create_keyfile()
basic_functions.clear_display()
write("Please enter shared secret for networking: ")
local pw_hash = hash.digestStr(read("*") .. "salty salt")
basic_functions.write_to_file("bos/files/networking-key.txt", pw_hash)
basic_functions.clear_display()
end
local function get_keyfile()
local pw_hash = basic_functions.read_file_oneline("bos/files/networking-key.txt")
return pw_hash
end
local function setup()
own_label = os.computerLabel()
peripheral.find("modem", rednet.open)
if not fs.exists "bos/files/networking-key.txt" then
create_keyfile()
end
end
--[[
String target ist label des Computers. zb "computer1", "miner1", "farmer1", etc
String message ist einfach der Text der Übertragen werden soll
]]
function send_message(to, what, payload)
setup()
local keyfile = get_keyfile()
local msg_table = {}
msg_table[0] = own_label
msg_table[1] = to
msg_table[2] = what
msg_table[3] = payload
local enc_msg = aes.encrypt(keyfile, textutils.serialize(msg_table))
rednet.broadcast(enc_msg)
end
function send_file(to, origin_path, target_path)
setup()
local keyfile = get_keyfile()
local payload_table = {}
print("sending " .. origin_path .. " to " .. to)
local file_content = basic_functions.read_file_all(origin_path)
payload_table[0] = target_path
payload_table[1] = file_content
send_message(to, "file_transfer", payload_table)
sleep(0.5)
end
function receive_message()
setup()
local keyfile = get_keyfile()
local id, rec_msg, prot = rednet.receive()
local pcall_success, decr_msg = pcall(aes.decrypt, keyfile, rec_msg)
if pcall_success and decr_msg ~= nil then
local rec_table = textutils.unserialize(decr_msg)
local from = rec_table[0]
local to = rec_table[1]
local what = rec_table[2]
local payload = rec_table[3]
if to == own_label or to == "all" then
if what == "file_transfer" then
basic_functions.write_to_file(payload[0], payload[1])
return "event: file transfer received"
elseif what == "execute_script" then
shell.run(payload)
return
elseif what == "script_command" then
return rec_table[3]
end
return rec_table
end
else
return "event: unencrypted message"
end
end
return {
send_message = send_message,
send_file = send_file,
receive_message = receive_message,
}