-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path60-network.lua
More file actions
1701 lines (1621 loc) · 74.7 KB
/
Copy path60-network.lua
File metadata and controls
1701 lines (1621 loc) · 74.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- TODO: fix user:password@domain URIs (uncommon but part of spec)
local function parseURI(uri)
local info = {scheme = ""}
for c in uri:gmatch "." do
if info.fragment then
if c:match "[%w%-%._~%%@:/!%$&'%(%)%*%+,;=/?]" then info.fragment = info.fragment .. c
else error("Invalid URI", 3) end
elseif info.query then
if c == "#" then info.fragment = ""
elseif c:match "[%w%-%._~%%@:/!%$&'%(%)%*%+,;=/?]" then info.query = info.query .. c
else error("Invalid URI", 3) end
elseif info.path then
if c == "/" and info.path == "/" and not info.host then info.path, info.host = nil, ""
elseif c == "?" then info.query = ""
elseif c == "#" then info.fragment = ""
elseif c:match "[%w%-%._~%%@:/!%$&'%(%)%*%+,;=/]" then info.path = info.path .. c
else error("Invalid URI", 3) end
elseif info.port then
if tonumber(c) then info.port = info.port .. c
elseif c == "/" then info.path = "/"
else error("Invalid URI", 3) end
elseif info.host then
if c == "@" and not info.user then info.user, info.host = info.host, ""
elseif c == ":" then info.port = ""
elseif c == "/" then info.path = "/"
elseif c:match "[%w%-%._~%%/!%$&'%(%)%*%+,;=]" then info.host = info.host .. c
else error("Invalid URI", 3) end
else
if c == ":" then info.path = ""
elseif c:match(info.scheme == "" and "[%a%+%-%.]" or "[%w%+%-%.]") then info.scheme = info.scheme .. c
else error("Invalid URI", 3) end
end
end
if info.port then info.port = tonumber(info.port) end
return info
end
local function ipToNumber(ip)
if ip:match "^%d+$" then return tonumber(ip)
elseif ip:match "^%d+%.%d+$" then return tonumber(ip:match "^%d+") * 0x1000000 + tonumber(ip:match "^%d+%.(%d+)")
elseif ip:match "^%d+%.%d+%.%d+$" then return tonumber(ip:match "^(%d+)") * 0x1000000 + tonumber(ip:match "^%d+%.(%d+)") * 0x10000 + tonumber(ip:match "^%d+%.%d+%.(%d+)")
elseif ip:match "^%d+%.%d+%.%d+%.%d+$" then return tonumber(ip:match "^(%d+)") * 0x1000000 + tonumber(ip:match "^%d+%.(%d+)") * 0x10000 + tonumber(ip:match "^%d+%.%d+%.(%d+)") * 0x100 + tonumber(ip:match "^%d+%.%d+%.%d+%.(%d+)")
else error("Invalid IP address", 2) end
end
local function numberToIP(num)
if not num then return nil end
return ("%d.%d.%d.%d"):format(bit32.band(bit32.rshift(num, 24), 0xFF), bit32.band(bit32.rshift(num, 16), 0xFF), bit32.band(bit32.rshift(num, 8), 0xFF), bit32.band(num, 0xFF))
end
local function randomString(len)
local s = ""
for i = 1, len do s = s .. string.char(math.random(0, 255)) end
return s
end
local function prefixToMask(num) return bit32.bnot(2^(32-num)-1) end
local function maskToPrefix(mask)
local n = 0
while bit32.btest(mask, 0x80000000) do mask, n = bit32.lshift(mask, 1), n + 1 end
return n
end
local function checkModem(node)
if not node then error("No such device") end
for _, v in pairs(node.drivers) do if v.type == "modem" then return node end end
error("Not a modem")
end
local nextHandleID = 0
--#region Network stack implementation
local ipconfig = {}
local routes = {maxn = 0, [0] = {}}
local arptable = {}
local protocols = {send = {}, recv = {}}
local openSockets = {}
local openSocketIDs = {}
local pdpListeners = {}
local networkListeners = setmetatable({}, {__mode = "k"})
local waiting = {arp = {}, socket = {}}
local usedMessageIDs = {}
--[[
socket object:
* ip: IP address of the remote host
* port: Port of the remote host
* localPort: Receive port on the local host
* id: ID of the socket/handle
* sendSeq: last sequence acknowledged by peer [SND.UNA]
* sendSeqNext: next sender sequence to peer [SND.NXT]
* sendSeqMax: maximum sequence to peer (for window) [SND.WND]
- on close, this is set to the sequence for the FIN message
* recvSeq: next expected received sequence from peer [RCV.NXT]
* recvSeqMax: maximum sequence from peer (for window) [RCV.WND]
* status: status of socket (listening, syn-sent, syn-received, connected, fin-wait, closing, close-wait [LAST-ACK], time-wait, closed)
* nextUpdate: time that the next update can be triggered
* process?: process that opened the socket
* retryCount: number of retries in the current state
* error?: an error status if something went wrong
* outQueue: list of messages that were sent but not ACKed
* nextAck?: whether the next timer should be for sending an ACK
* buffer: data queue for the socket (string)
]]
-- TODO: Make a final decision on whether to use channels for PSP ports.
-- There's a limit on open channels, so that would arbitrarily limit
-- the number of sockets that could be open at once, much below the
-- port exhaustion limit. However, putting everything on the same
-- channel may cause too much chatter on the channel.
local function tryClose(socket, port)
local devices = {}
for k in pairs(socket.devices) do devices[k] = true end
if openSockets[port] and openSockets[port].listen and openSockets[port].listen.process == socket.process then
for k in pairs(openSockets[port].listen.devices) do devices[k] = nil end
end
if openSockets[port] then
for _, s in pairs(openSockets[port]) do
if s.process == socket.process then
for k in pairs(s.devices) do devices[k] = nil end
end
end
end
for k in pairs(devices) do hardware.call(socket.process, hardware.get(k), "close", port) end
end
function protocols.send.link(info, destination, message)
expect(2, destination, "number", "nil")
expect.field(info, "device", "table")
local obj = {
PhoenixNetworking = true,
type = "link",
source = os.computerID(),
destination = destination,
payload = message
}
if destination == os.computerID() then os.queueEvent("modem_message", info.device.id, info.outPort or 0, info.inPort or 0, obj, 0)
else hardware.call(info.process or KERNEL, info.device, "transmit", info.outPort or 0, info.inPort or 0, obj) end
end
function protocols.send.arp_request(info, ip)
expect.field(info, "device", "table")
expect(2, ip, "string")
hardware.call(info.process or KERNEL, info.device, "transmit", 0, 0, {
PhoenixNetworking = true,
type = "arp",
reply = false,
source = os.computerID(),
sourceIP = ipconfig[info.device.uuid] and numberToIP(ipconfig[info.device.uuid].ip),
destinationIP = ip
})
end
function protocols.send.arp_reply(info, destination, destIP)
expect.field(info, "device", "table")
expect(2, destination, "number")
expect(3, destIP, "string", "nil")
hardware.call(info.process or KERNEL, info.device, "transmit", 0, 0, {
PhoenixNetworking = true,
type = "arp",
reply = true,
source = os.computerID(),
sourceIP = numberToIP(ipconfig[info.device.uuid].ip),
destination = destination,
destinationIP = destIP
})
end
function protocols.send.internet(info, destination, message, ttl, callback)
expect(2, destination, "number")
local msg = {PhoenixNetworking = true, type = "internet", hopsLeft = ttl or 15, payload = message, destination = numberToIP(destination)}
local id = randomString(32)
msg.messageID = id
--usedMessageIDs[id] = os.epoch "utc"
local v
for i = routes.maxn, 0, -1 do if routes[i] then
for _, rt in ipairs(routes[i]) do
if bit32.band(rt.source, rt.sourceNetmask) == bit32.band(destination, rt.sourceNetmask) and
(not v or maskToPrefix(rt.sourceNetmask) > maskToPrefix(v.sourceNetmask)) then v = rt end
end
end end
if not v then
local res = protocols.recv.control({}, {
PhoenixNetworking = true,
messageType = "unreachable",
error = "No route to host",
payload = msg
})
if callback then callback() end
return res
end
if v.action == "unicast" and ipconfig[v.device.uuid] and ipconfig[v.device.uuid].up then
info.device = v.device
msg.source = numberToIP(ipconfig[v.device.uuid].ip)
if arptable[v.device.uuid] and arptable[v.device.uuid][v.destination] then
local res = protocols.send.link(info, arptable[v.device.uuid][v.destination], msg)
if callback then callback() end
return res
end
local sent = false
local timer
local function arp_reply(_, ip, dest)
if not sent and ipToNumber(ip) == v.destination then
sent = true
protocols.send.link(info, dest, msg)
if callback then callback() end
end
if sent then for i, f in ipairs(waiting.arp) do if f == arp_reply then table.remove(waiting.arp, i) break end end end
end
local function timer_func(ev)
if ev[2] == timer then
if not sent then
protocols.recv.control({}, {
PhoenixNetworking = true,
messageType = "unreachable",
error = "No route to host",
payload = msg
})
if callback then callback() end
end
sent = true
for i, w in ipairs(eventHooks.timer) do if w == timer_func then table.remove(eventHooks.timer, i) break end end
for i, f in ipairs(waiting.arp) do if f == arp_reply then table.remove(waiting.arp, i) break end end
end
end
waiting.arp[#waiting.arp+1] = arp_reply
protocols.send.arp_request(info, numberToIP(v.destination))
eventHooks.timer = eventHooks.timer or {}
eventHooks.timer[#eventHooks.timer+1] = timer_func
timer = os.startTimer(2)
return
elseif v.action == "broadcast" and ipconfig[v.device.uuid] and ipconfig[v.device.uuid].up then
info.device = v.device
msg.source = numberToIP(ipconfig[v.device.uuid].ip)
local res = protocols.send.link(info, nil, msg)
if callback then callback() end
return res
elseif v.action == "local" and ipconfig[v.device.uuid] and ipconfig[v.device.uuid].up then
info.device = v.device
msg.source = numberToIP(ipconfig[v.device.uuid].ip)
if arptable[v.device.uuid] and arptable[v.device.uuid][destination] then
local res = protocols.send.link(info, arptable[v.device.uuid][destination], msg)
if callback then callback() end
return res
end
local sent = false
local timer
local function arp_reply(_, ip, dest)
if not sent and ipToNumber(ip) == destination then
sent = true
protocols.send.link(info, dest, msg)
if callback then callback() end
end
if sent then for i, f in ipairs(waiting.arp) do if f == arp_reply then table.remove(waiting.arp, i) break end end end
end
local function timer_func(ev)
if ev[2] == timer then
if not sent then
protocols.recv.control({}, {
PhoenixNetworking = true,
messageType = "unreachable",
error = "No route to host",
payload = msg
})
if callback then callback() end
end
sent = true
for i, w in ipairs(eventHooks.timer) do if w == timer_func then table.remove(eventHooks.timer, i) break end end
end
end
waiting.arp[#waiting.arp+1] = arp_reply
protocols.send.arp_request(info, numberToIP(destination))
eventHooks.timer = eventHooks.timer or {}
eventHooks.timer[#eventHooks.timer+1] = timer_func
timer = os.startTimer(2)
return
elseif v.action == "unreachable" then
local res = protocols.recv.control({}, {
PhoenixNetworking = true,
messageType = "unreachable",
error = "Destination unreachable",
payload = msg
})
if callback then callback() end
return res
elseif v.action == "prohibit" then
local res = protocols.recv.control({}, {
PhoenixNetworking = true,
messageType = "unreachable",
error = "Prohibited",
payload = msg
})
if callback then callback() end
return res
elseif v.action == "blackhole" then
if callback then callback() end
return
end
end
function protocols.send.control(info, destination, type, err, packet, ttl)
expect(3, type, "string")
expect(4, err, "string", "nil")
return protocols.send.internet(info, destination, {
PhoenixNetworking = true,
type = "control",
messageType = type,
error = err,
payload = packet
}, ttl)
end
protocols.send.socket = {}
local socketUpdate
function protocols.send.socket.connect(info, ip, port, socket)
for i = 1, 16384 do
local p = math.random(49152, 65535)
if not openSockets[p] or not openSockets[p][port] then socket.localPort = p break end
end
if not socket.localPort then error("Too many open sockets") end
socket.id = nextHandleID
nextHandleID = nextHandleID + 1
socket.ip = ip
socket.port = port
socket.sendSeq = math.floor(math.random()*0x10000000000)
socket.sendSeqNext = socket.sendSeq + 2
socket.sendSeqMax = socket.sendSeq + 256
socket.status = "syn-sent"
info.outPort = port
info.inPort = socket.localPort
networkListeners[socket] = function(p)
if p.type == "control" and p.payload.destination == numberToIP(ip) then
socket.status = "error"
socket.error = p.error
return true
end
return false
end
protocols.send.internet(info, ip, {
PhoenixNetworking = true,
type = "socket",
sequence = socket.sendSeqNext - 1,
windowSize = 256,
synchronize = true
}, nil, function()
socket.devices = {[info.device.uuid] = true}
local ok, err = pcall(hardware.call, info.process or KERNEL, info.device, "open", socket.localPort)
if not ok then
-- Trim some lingering time-wait sockets early to reclaim ports
local open = {}
for port, list in pairs(openSockets) do for replyPort, socket in pairs(list) do open[#open+1] = port .. " -> " .. replyPort end end
syslog.debug("Purging open channels", table.concat(open, ", "))
socketUpdate(true)
ok, err = pcall(hardware.call, info.process or KERNEL, info.device, "open", socket.localPort)
if not ok then
protocols.send.internet(info, ip, {
PhoenixNetworking = true,
type = "socket",
sequence = socket.sendSeqNext,
windowSize = 0,
reset = true
})
socket.status = "error"
socket.error = err
return false
end
end
socket.nextUpdate = os.epoch "utc" + 5000
socket.process = info.process
socket.retryCount = 0
openSockets[socket.localPort] = openSockets[socket.localPort] or {}
openSockets[socket.localPort][port] = socket
openSocketIDs[socket.id] = socket
end)
end
function protocols.send.socket.data(info, message, socket)
info.outPort = socket.port
info.inPort = socket.localPort
message.PhoenixNetworking = true
message.type = "socket"
if not message.sequence then
message.sequence = socket.sendSeqNext
socket.sendSeqNext = socket.sendSeqNext + 1
end
message.acknowledgement = message.acknowledgement or (socket.recvSeq - 1)
socket.nextAck = nil
if not message.final then message.windowSize = 256 end -- TODO: adjustable?
return protocols.send.internet(info, socket.ip, message)
end
function protocols.send.socket.ack(info, num, socket)
--if socket.lastAck and os.epoch "utc" - socket.lastAck < 50 then return end
socket.lastAck = os.epoch "utc"
return protocols.send.socket.data(info, {acknowledgement = num}, socket)
end
function protocols.send.socket.reset(info, ip, port, seq, ack, inPort)
info.outPort = port
info.inPort = inPort or port
return protocols.send.internet(info, ip, {
PhoenixNetworking = true,
type = "socket",
sequence = seq,
acknowledgement = ack,
reset = true
})
end
function protocols.send.datagram(info, ip, sourcePort, port, message)
info.outPort = port
info.inPort = sourcePort or math.random(49152, 65535)
return protocols.send.internet(info, ip, {
PhoenixNetworking = true,
type = "datagram",
message = message
})
end
local function socket_read(socket, mode, ...)
mode = mode or "*l"
if type(mode) ~= "string" and type(mode) ~= "number" then error("bad argument (expected string or number, got " .. type(mode) .. ")", 2) end
if socket.buffer == "" then return nil end
mode = mode:gsub("^%*", "")
if mode == "a" then
local str = socket.buffer
socket.buffer = ""
return str
elseif mode == "l" then
local str, pos = socket.buffer:match "^([^\n]*)\n?()"
if str then
socket.buffer = socket.buffer:sub(pos)
if select("#", ...) > 0 then return str, socket_read(socket, ...)
else return str end
else return nil end
elseif mode == "L" then
local str, pos = socket.buffer:match "^([^\n]*\n?)()"
if str then
socket.buffer = socket.buffer:sub(pos)
if select("#", ...) > 0 then return str, socket_read(socket, ...)
else return str end
else return nil end
elseif mode == "n" then
local str, pos = socket.buffer:match "(%d+)()"
if str then
socket.buffer = socket.buffer:sub(pos)
if select("#", ...) > 0 then return tonumber(str), socket_read(socket, ...)
else return tonumber(str) end
else return nil end
elseif type(mode) == "number" then
local str = socket.buffer:sub(1, mode)
socket.buffer = socket.buffer:sub(mode + 1)
if select("#", ...) > 0 then return str, socket_read(socket, ...)
else return str end
else error("bad argument (invalid mode '" .. mode .. "')", 2) end
end
local function socket_write(socket, data, ...)
data = tostring(data)
socket.outQueue[socket.sendSeqNext] = data
protocols.send.socket.data({}, {payload = data}, socket)
if select("#", ...) > 0 then return socket_write(socket, ...) end
end
function syscalls.__socketcall(process, thread, id, method, ...)
local socket = openSocketIDs[id]
if not socket then error("No such socket") end
local realProcess = process
while process ~= socket.process do
if process == nil then error("No such socket") end
process = processes[process.parent or -1]
end
if method == "close" then
socket.sendSeqMax = socket.sendSeqNext
protocols.send.socket.data({}, {final = true}, socket)
socket.status = "fin-wait"
elseif method == "read" then return socket_read(socket, ...)
elseif method == "write" then return socket_write(socket, ...)
elseif method == "transfer" then socket.process = realProcess
else error("No such method") end
end
function syscalls.__datagramcall(process, thread, port, id, method, ...)
local listener = pdpListeners[port]
local realProcess = process
while process ~= listener.process do
if process == nil then error("No such socket") end
process = processes[process.parent or -1]
end
local socket
if listener.listen then
for _, v in pairs(listener.open) do if v.id == id then socket = v break end end
if not socket then error("No socket found for ID") end
else socket = listener end
if method == "close" then
-- TODO: close channels properly
if listener.listen then
for k, v in pairs(listener.open) do if v.id == id then listener.open[k] = nil break end end
else
pdpListeners[port] = nil
end
elseif method == "read" then
local v = socket[1]
socket.n = socket.n - 1
for i = 1, socket.n do socket[i] = socket[i+1] end
return v
elseif method == "write" then return protocols.send.datagram({process = process}, socket.sourceIP, port, socket.port, ...)
elseif method == "transfer" then listener.process = realProcess
else error("No such method") end
end
local do_syscall = do_syscall
local function makePSPHandle(socket)
local obj = setmetatable({id = socket.id}, {__name = "socket"})
function obj:localIP()
return socket.localIP
end
function obj:status()
if socket.status == "listening" or socket.status == "syn-sent" or socket.status == "syn-received" then return "connecting"
elseif socket.status == "connected" or socket.buffer ~= "" then return "open"
elseif socket.status == "error" then return "error", socket.error
else return "closed" end
end
function obj:read(mode, ...)
if socket.status ~= "connected" and socket.status ~= "close-wait" and socket.status ~= "fin-wait" and socket.status ~= "closed" then error("attempt to read from a " .. socket.status .. " handle", 2) end
return do_syscall("__socketcall", socket.id, "read", mode, ...)
end
function obj:write(data, ...)
if socket.status ~= "connected" then error("attempt to write to a " .. socket.status .. " handle", 2) end
return do_syscall("__socketcall", socket.id, "write", data, ...)
end
function obj:close()
if socket.status == "closing" or socket.status == "fin-wait" or socket.status == "closed" then return end
if not (socket.status == "listening" or socket.status == "syn-sent" or socket.status == "syn-received" or socket.status == "connected") then error("attempt to close a " .. socket.status .. " handle", 2) end
return do_syscall("__socketcall", socket.id, "close")
end
function obj:transfer()
return do_syscall("__socketcall", socket.id, "transfer")
end
return obj
end
local function makePDPHandle(socket, port)
local obj = setmetatable({id = socket.id}, {__name = "socket"})
function obj:localIP()
return numberToIP(socket.localIP)
end
function obj:status()
return "open"
end
function obj:read(mode, ...)
return do_syscall("__datagramcall", port, socket.id, "read", mode, ...)
end
function obj:write(data, ...)
return do_syscall("__datagramcall", port, socket.id, "write", data, ...)
end
function obj:close()
return do_syscall("__datagramcall", port, socket.id, "close")
end
function obj:transfer()
return do_syscall("__datagramcall", port, socket.id, "transfer")
end
return obj
end
-- prefilled entries in info: channel, replyChannel, device
function protocols.recv.link(info, message)
expect.field(message, "source", "number")
expect.field(message, "destination", "number")
expect.field(message, "payload", "table")
syslog.debug("Received link message from", message.source, "to", message.destination)
if message.destination ~= os.computerID() then return end
info.sourceID = message.source
assert(message.payload.PhoenixNetworking)
expect.field(message.payload, "type", "string")
if not protocols.recv[message.payload.type] then error("Unknown protocol '" .. message.payload.type .. "'") end
return protocols.recv[message.payload.type](info, message.payload)
end
function protocols.recv.arp(info, message)
expect.field(message, "source", "number")
expect.field(message, "reply", "boolean")
syslog.debug("Received arp message from", message.source)
if not message.reply and message.destinationIP and message.sourceIP ~= message.destinationIP then
local ip = ipToNumber(expect.field(message, "destinationIP", "string"))
if ipconfig[info.device.uuid] and ipconfig[info.device.uuid].ip == ip then
protocols.send.arp_reply(info, message.source, message.sourceIP)
end
end
if message.sourceIP then
local ip = ipToNumber(expect.field(message, "sourceIP", "string"))
arptable[info.device.uuid] = arptable[info.device.uuid] or {}
arptable[info.device.uuid][ip] = message.source
-- copy the table so we don't skip any if the function modifies the table
local tmp = {}
for i, v in ipairs(waiting.arp) do tmp[i] = v end
for _, v in ipairs(tmp) do v(v, message.sourceIP, message.source) end
end
end
function protocols.recv.internet(info, message)
info.sourceIP = ipToNumber(expect.field(message, "source", "string"))
local dest = ipToNumber(expect.field(message, "destination", "string"))
info.localIP = dest
syslog.debug("Received internet message from", message.source, "to", message.destination)
expect.field(message, "payload", "table")
if usedMessageIDs[expect.field(message, "messageID", "number", "string")] then return end
usedMessageIDs[message.messageID] = os.epoch "utc"
if not ipconfig[info.device.uuid] or ipconfig[info.device.uuid].ip ~= dest then
local retval = false
for _, v in pairs(networkListeners) do retval = v(message) or retval end
return retval
end
if not arptable[info.device.uuid] or not arptable[info.device.uuid][info.sourceIP] then
arptable[info.device.uuid] = arptable[info.device.uuid] or {}
arptable[info.device.uuid][info.sourceIP] = info.sourceID
-- copy the table so we don't skip any if the function modifies the table
local tmp = {}
for i, v in ipairs(waiting.arp) do tmp[i] = v end
for _, v in ipairs(tmp) do v(v, info.sourceIP, info.sourceID) end
end
info.ipPacket = message
assert(message.payload.PhoenixNetworking)
expect.field(message.payload, "type", "string")
if not protocols.recv[message.payload.type] then error("Unknown protocol '" .. message.payload.type .. "'") end
return protocols.recv[message.payload.type](info, message.payload)
end
function protocols.recv.control(info, message)
expect.field(message, "messageType", "string")
syslog.debug("Received control message", message.messageType)
local retval = false
if message.messageType == "ping" then protocols.send.control({device = info.device}, info.sourceIP, "pong", nil, info.ipPacket)
else for _, v in pairs(networkListeners) do retval = v{type = "control", messageType = message.messageType, error = message.error, payload = message.payload, sender = numberToIP(info.sourceIP)} or retval end end
return retval
end
local function safe_serialize(v)
local ok, res = pcall(serialize, v)
if ok then return res else return tostring(v) end
end
function protocols.recv.socket(info, message)
expect.field(message, "sequence", "number")
expect.field(message, "acknowledgement", "number", "nil")
expect.field(message, "windowSize", "number", "nil")
expect.field(message, "payload", "string", "nil")
if info.channel == 0 or info.replyChannel == 0 then syslog.debug("Received socket event on channel 0; discarding.") return end
local socket = (openSockets[info.channel] or {})[info.replyChannel] or (openSockets[info.channel] or {}).listen
if not socket then
if message.acknowledgement then protocols.send.socket.reset(info, info.sourceIP, info.replyChannel, message.acknowledgement, nil, info.channel)
else protocols.send.socket.reset(info, info.sourceIP, info.replyChannel, 0, message.sequence + (message.windowSize or 0), info.channel) end
return
end
do
local s = {}
for k, v in pairs(socket) do if k ~= "process" then s[k] = v end end
syslog.debug("Received socket message:", safe_serialize(message), "\nSocket info:", safe_serialize(s))
end
if socket.status == "listening" then
if message.reset then return end
if message.acknowledgement then
protocols.send.socket.reset(info, info.sourceIP, info.replyChannel, message.acknowledgement, nil, info.channel)
return
end
if not message.synchronize then return end
socket.ip = info.sourceIP
socket.localIP = numberToIP(info.localIP)
socket.port = info.replyChannel
socket.recvSeq = message.sequence + 1
socket.recvSeqMax = socket.recvSeq + (message.windowSize or 0)
socket.sendSeq = math.floor(math.random()*0x10000000000)
socket.sendSeqNext = socket.sendSeq + 2
socket.sendSeqMax = socket.sendSeq + (message.windowSize or 0)
socket.status = "syn-received"
socket.nextUpdate = os.epoch "utc" + 5000
socket.retryCount = 0
openSockets[info.channel][info.replyChannel] = socket
openSockets[info.channel].listen = nil
protocols.send.internet({inPort = info.channel, outPort = info.replyChannel}, socket.ip, {
PhoenixNetworking = true,
type = "socket",
sequence = socket.sendSeqNext - 1,
acknowledgement = socket.recvSeq,
windowSize = 256,
synchronize = true
})
elseif socket.status == "syn-sent" then
if message.reset then
socket.status = "error"
socket.error = "Connection refused"
openSockets[info.channel][info.replyChannel] = nil
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "error"}} end
return true
end
if not message.synchronize or not message.acknowledgement or message.acknowledgement < socket.sendSeq then
protocols.send.socket.reset(info, info.sourceIP, info.replyChannel, message.acknowledgement, nil, info.channel)
socket.status = "error"
socket.error = "Connection refused"
openSockets[info.channel][info.replyChannel] = nil
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "error"}} end
return true
end
socket.localIP = numberToIP(info.localIP)
socket.status = "connected"
socket.sendSeq = message.acknowledgement
socket.sendSeqMax = socket.sendSeq + 256
socket.recvSeq = message.sequence + 1
socket.recvSeqMax = socket.recvSeq + (message.windowSize or 0)
socket.outQueue = {}
socket.nextUpdate = os.epoch "utc" + 2000
protocols.send.socket.ack({}, socket.recvSeq, socket)
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "connected"}} end
return true
else
if message.sequence < socket.recvSeq --[[or message.sequence > socket.recvSeqMax]] then
syslog.debug("Sequence out of range")
if message.reset then
socket.status = "error"
socket.error = "Connection reset by peer"
openSockets[info.channel][info.replyChannel] = nil
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "error"}} end
return true
else
protocols.send.socket.ack({}, socket.recvSeq, socket)
return
end
end
if message.reset then
syslog.debug("Received reset")
if socket.status == "syn-received" then
socket.status = "listening"
return
elseif socket.status == "connected" or socket.status == "fin-wait" then
socket.status = "error"
socket.error = "Connection reset by peer"
openSockets[info.channel][info.replyChannel] = nil
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "error"}} end
return true
else
socket.status = "closed"
openSockets[info.channel][info.replyChannel] = nil
tryClose(socket, info.channel)
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "closed"}} end
return true
end
end
if message.synchronize then
protocols.send.socket.reset(info, info.sourceIP, info.replyChannel, message.acknowledgement, nil, info.channel)
socket.status = "error"
socket.error = "Connection reset by host"
openSockets[info.channel][info.replyChannel] = nil
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "error"}} end
return true
end
local retval
if not message.acknowledgement then syslog.debug("No acknowledgement") return end
if socket.status == "syn-received" then
if message.acknowledgement >= socket.sendSeq and message.acknowledgement <= socket.sendSeqNext then
socket.status = "connected"
socket.outQueue = {}
socket.nextUpdate = os.epoch "utc" + 2000
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"network_request", {uri = socket.uri, ip = numberToIP(info.sourceIP), handle = makePSPHandle(socket)}} end
retval = true
else
protocols.send.socket.reset(info, info.sourceIP, info.replyChannel, message.acknowledgement, nil, info.channel)
socket.status = "error"
socket.error = "Connection reset by host"
openSockets[info.channel][info.replyChannel] = nil
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "error"}} end
return true
end
elseif socket.status == "close-wait" then
--syslog.log({}, "close-wait", info.channel, info.replyChannel, message.acknowledgement, socket.sendSeqMax)
if message.acknowledgement == socket.sendSeqMax then
syslog.debug("Socket closed")
socket.status = "closed"
openSockets[info.channel][info.replyChannel] = nil
tryClose(socket, info.channel)
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "closed"}} end
return true
end
elseif socket.status == "time-wait" then
if message.final then
protocols.send.socket.ack({}, message.sequence, socket)
socket.nextUpdate = os.epoch "utc" + 10000
return
end
else
if message.acknowledgement > socket.sendSeq and message.acknowledgement <= socket.sendSeqNext then
for i = socket.sendSeq, message.acknowledgement do socket.outQueue[i] = nil end
socket.sendSeq = message.acknowledgement
if message.windowSize and socket.status ~= "fin-wait" and socket.status ~= "closing" then socket.sendSeqMax = socket.sendSeq + message.windowSize end
end
if socket.status == "fin-wait" then
if message.acknowledgement == socket.sendSeqMax then
if not message.final then
protocols.send.socket.reset(info, info.sourceIP, info.replyChannel, message.acknowledgement, nil, info.channel)
socket.status = "error"
socket.error = "Connection reset by host"
openSockets[info.channel][info.replyChannel] = nil
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "error"}} end
return true
end
socket.status = "time-wait"
socket.nextUpdate = os.epoch "utc" + 10000
end
elseif socket.status == "closing" then
if message.acknowledgement == socket.sendSeqMax then
socket.status = "time-wait"
socket.nextUpdate = os.epoch "utc" + 10000
end
end
end
if socket.status == "connected" and message.sequence == socket.recvSeq then
if message.payload then
socket.buffer = socket.buffer .. message.payload
socket.nextAck = true
socket.nextUpdate = os.epoch "utc" + 100
if socket.process then
syslog.debug("Sending data event to PID " .. socket.process.id)
socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_data_ready", {id = socket.id}}
end
retval = true
end
socket.recvSeq = socket.recvSeq + 1
end
if message.final then
syslog.debug("Got final message")
socket.recvSeq = message.sequence + 1
if socket.status == "syn-received" or socket.status == "connected" then
socket.sendSeqMax = socket.sendSeqNext
protocols.send.socket.data({}, {
final = true,
acknowledgement = message.sequence
}, socket)
socket.status = "close-wait"
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "closed"}} end
return true
elseif socket.status == "fin-wait" then
protocols.send.socket.ack({}, message.sequence, socket)
if message.acknowledgement ~= socket.sendSeqMax then
socket.status = "closing"
else
socket.status = "time-wait"
socket.nextUpdate = os.epoch "utc" + 10000
end
else
protocols.send.socket.ack({}, message.sequence, socket)
end
syslog.debug(socket.status)
end
return retval
end
end
-- This function is called every second, handling any timed updates that may be necessary for sockets.
function socketUpdate(force)
local time = os.epoch "utc"
local event = false
for port, list in pairs(openSockets) do for replyPort, socket in pairs(list) do
if time >= socket.nextUpdate then
if socket.status == "syn-sent" then
socket.status = "error"
socket.error = "Connection timed out (syn-sent)"
openSockets[port][replyPort] = nil
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "error"}} event = true end
elseif socket.status == "syn-received" then
socket.retryCount = socket.retryCount + 1
if socket.retryCount > 3 then
socket.status = "error"
socket.error = "Connection timed out (syn-received)"
openSockets[port][replyPort] = nil
if socket.process then socket.process.eventQueue[#socket.process.eventQueue+1] = {"handle_status_change", {id = socket.id, status = "error"}} event = true end
else
-- TODO: resend syn+ack packet
socket.nextUpdate = os.epoch "utc" + 2000
end
elseif socket.status == "connected" then
for i = socket.sendSeq + 1, socket.sendSeqNext - 1 do
if socket.outQueue[i] then
protocols.send.socket.data({}, {
sequence = i,
payload = socket.outQueue[i]
}, socket)
end
end
if socket.nextAck then
protocols.send.socket.ack({}, socket.recvSeq - 1, socket)
socket.nextAck = nil
end
socket.nextUpdate = os.epoch "utc" + 2000
elseif socket.status == "fin-wait" then
elseif socket.status == "close-wait" then
end
elseif socket.status == "time-wait" and (time >= socket.nextUpdate or force) then
syslog.debug("Time wait finished on port " .. port)
socket.status = "closed"
openSockets[port][replyPort] = nil
if replyPort ~= "listen" then tryClose(socket, port) end
end
end end
return event
end
function protocols.recv.datagram(info, message)
if not pdpListeners[info.channel] then
syslog.debug("Received spurious PDP message on port " .. info.channel .. ", discarding.")
return
end
local listener = pdpListeners[info.channel]
if listener.listen then
local socket = listener.open[info.sourceIP]
if socket then
socket.n = socket.n + 1
socket[socket.n] = message.message
listener.process.eventQueue[#listener.process.eventQueue+1] = {"handle_data_ready", {id = socket.id}}
else
listener.open[info.sourceIP] = {
id = nextHandleID,
sourceIP = info.sourceIP,
localIP = info.localIP,
port = info.replyChannel,
n = 1,
message.message
}
nextHandleID = nextHandleID + 1
listener.process.eventQueue[#listener.process.eventQueue+1] = {"network_request", {uri = listener.uri, ip = numberToIP(info.sourceIP), handle = makePDPHandle(listener.open[info.sourceIP], info.channel)}}
end
else
listener.n = listener.n + 1
listener[listener.n] = message.message
listener.process.eventQueue[#listener.process.eventQueue+1] = {"handle_data_ready", {id = listener.id}}
end
return true
end
eventHooks.modem_message = eventHooks.modem_message or {}
eventHooks.modem_message[#eventHooks.modem_message+1] = function(ev)
if type(ev[5]) == "table" and ev[5].PhoenixNetworking and type(ev[5].type) == "string" and protocols.recv[ev[5].type] then
local node = getNodeById(ev[2]) or hardware.get(ev[2])
if not node then
syslog.log({level = "notice", module = "Network"}, "Received network event for device ID " .. ev[2] .. ", but no device node was found; ignoring")
return
end
if not ipconfig[node.uuid] or not ipconfig[node.uuid].up then return end
syslog.debug(ev[2], safe_serialize(ev[5]))
local ok, err = pcall(protocols.recv[ev[5].type], {channel = ev[3], replyChannel = ev[4], device = node}, ev[5])
if not ok then syslog.log({level = "debug", module = "Network"}, "Network event errored while processing:", err)
else return err end
end
end
local socketTimer = os.startTimer(1)
eventHooks.timer = eventHooks.timer or {}
eventHooks.timer[#eventHooks.timer+1] = function(ev)
if ev[2] == socketTimer then
socketTimer = os.startTimer(1)
--syslog.debug("Triggering socket timer")
return socketUpdate()
end
end
local function pspHandler(process, options)
-- TODO: implement device filtering
local uri = parseURI(options.url)
if not uri.port then error("No port specified") end
local ip = ipToNumber(uri.host)
local port = uri.port
local socket = {process = process, buffer = ""}
protocols.send.socket.connect({process = process}, ip, port, socket)
return makePSPHandle(socket)
end
local function pdpHandler(process, options)
local uri = parseURI(options.url)
if not uri.port then error("No port specified") end
local localPort
for i = 1, 16384 do
local p = math.random(49152, 65535)
if not pdpListeners[p] then localPort = p break end
end
if not localPort then error("Too many open sockets") end
local ip = ipToNumber(uri.host)
local port = uri.port
local socket = {
process = process,
id = nextHandleID,
sourceIP = ip,
port = port,