diff --git a/build.cfg b/build.cfg index 3205c5b..74ab824 100755 --- a/build.cfg +++ b/build.cfg @@ -8,7 +8,8 @@ modules/lib/io.lua modules/drivers/vt52.lua modules/lib/print.lua modules/drivers/kbd.lua -modules/drivers/net.lua +modules/lib/cdlib.lua +modules/net/copper.0.lua modules/lib/readline.lua modules/lib/shutil.lua modules/lib/sha256.lua diff --git a/modules/lib/cdlib.lua b/modules/lib/cdlib.lua new file mode 100644 index 0000000..23aeef0 --- /dev/null +++ b/modules/lib/cdlib.lua @@ -0,0 +1,31 @@ +-- cdlib by t20kdc, from https://github.com/20kdc/OC-Copper/blob/master/cdlib.lua +-- modified for PsychOS by Izaya +_G.cdlib = {} +function cdlib.encodeName(name) + if name:len() > 256 then error("Bad name (l>256)") end + if name == "" then error("No name") end + return string.char(name:len() - 1) .. name +end +function cdlib.decodeName(message) + if message:len() < 2 then return end + local nlen = message:byte(1) + 1 + local fnam = message:sub(2, nlen + 1) + if fnam:len() < nlen then return end + return fnam, message:sub(nlen + 2) +end +function cdlib.decodeNoHops(data) + local src, data = cdlib.decodeName(data) + if not src then return end + local dst, data = cdlib.decodeName(data) + if not dst then return end + return src, dst, data +end +function cdlib.encode(hops, src, dst, data) + return string.char(hops) .. cdlib.encodeName(src) .. cdlib.encodeName(dst) .. data +end +function cdlib.decode(d) + if d:len() < 3 then return end + local src, dst, data = cdlib.decodeNoHops(d:sub(2)) + if not data then return end + return d:byte(1), src, dst, data +end diff --git a/modules/net/copper.0.lua b/modules/net/copper.0.lua new file mode 100644 index 0000000..21f509d --- /dev/null +++ b/modules/net/copper.0.lua @@ -0,0 +1,45 @@ +net = {} +net.id = computer.address():sub(1,8) +net.np = 4957 +net.tm = {} +function net.send(id,po,msg) -- id, port, message + event.push("sendmsg",id,po,msg) +end +if cdlib then +spawn("copper.0 daemon",function() print(pcall(function () + local pt = {} + for a,t in component.list("modem") do + table.insert(net.tm,component.proxy(a)) + component.proxy(a).open(net.np) + end + while true do + local ev = {event.pull()} + if ev[1] == "rsendmsg" then + dst,data = ev[2],ev[3] + for k,v in ipairs(net.tm) do + v.broadcast(net.np,"copper",cdlib.encode(0,net.id,dst,data)) + end + elseif ev[1] == "modem_message" and ev[4] == net.np and ev[6] == "copper" then + local hops,src,dst,data = cdlib.decode(ev[7]) + if not pt[ev[7]:sub(2)] then + pt[ev[7]:sub(2)] = os.time() + if dst == net.id then + event.push("net_rmsg",src,data) + else + for k,v in ipairs(net.tm) do + v.broadcast(net.np,cdlib.encode(hops+1,src,dst,data)) + end + end + end + end + if #pt > 63 then + local cot = os.time() + for k,v in pairs(pt) do + if v < cot-5 then + pt[k] = nil + end + end + end + end +end)) end) +end