aboutsummaryrefslogtreecommitdiffstats
path: root/src/socket.asm
blob: c719948be1b879b97b083c0b27268cde9dda0e5c (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
; =============================================================================
; socket.asm - the kernel network stack + socket layer (SYS_NET).
;
; The kernel owns the link port: SLIP framing, IPv4, checksums, and the per-
; protocol logic all live here. Userland just does socket()/connect()/send()/
; recv()/close() via one syscall (DE = &netreq). No program touches SLIP or IP.
;
; Our address is 10.0.0.2. Incoming ICMP echo requests are auto-answered while
; any process pumps RX (recv/poll), so the Game Boy responds to pings for real.
;
; Phase 1: ICMP (echo).  UDP and TCP build on the same frame/checksum core.
; =============================================================================
INCLUDE "include/gbos.inc"

; ---- socket entry layout ----------------------------------------------------
DEF SK_TYPE    EQU 0     ; 0 = free
DEF SK_RIP     EQU 1     ; 4  remote IP
DEF SK_RPORT   EQU 5     ; 2  remote port
DEF SK_LPORT   EQU 7     ; 2  local port
DEF SK_HASRX   EQU 9     ; 1  rxbuf holds a datagram
DEF SK_RXLEN   EQU 10    ; 1  payload length
DEF SK_SRCIP   EQU 11    ; 4  sender IP
DEF SK_SRCPORT EQU 15    ; 2  sender port
; TCP bookkeeping MUST stay below offset 256: the field accessors do
; `add SK_x` as an 8-bit immediate, so any constant >=256 is silently
; truncated (e.g. 305 -> 49) and lands *inside* RXBUF, where an incoming
; segment's payload then overwrites the connection's STATE/seq numbers -
; corrupting every multi-segment TCP receive. Keep STATE/SND/RCV ahead of
; the big RXBUF; RXBUF is only ever based via a 16-bit-safe add.
DEF SK_STATE   EQU 17    ; 1  TCP state (see TCP_* below)
DEF SK_SND     EQU 18    ; 4  snd_nxt (our next sequence number)
DEF SK_RCV     EQU 22    ; 4  rcv_nxt (next sequence we expect from peer)
DEF SK_OWNER   EQU 26    ; 1  pid that created this socket (freed when it dies)
DEF SK_RXBUF   EQU 27    ; 288 payload (holds a DHCP reply, or a max segment)
DEF SK_SIZE    EQU 315
DEF TCP_MSS    EQU 200

; TCP connection states
DEF TCP_CLOSED  EQU 0
DEF TCP_SYNSENT EQU 1
DEF TCP_ESTAB   EQU 2
DEF TCP_FINWAIT EQU 3
DEF TCP_DONE    EQU 4
DEF TCP_LISTEN  EQU 5    ; passive open: waiting for a SYN (net_op_listen)
DEF TCP_SYNRCVD EQU 6    ; SYN+ACK sent, waiting for the handshake's final ACK
; TCP flags
DEF TF_FIN EQU $01
DEF TF_SYN EQU $02
DEF TF_RST EQU $04
DEF TF_PSH EQU $08
DEF TF_ACK EQU $10

SECTION "net_bss", WRAM0
wSockTab::     DS MAX_SOCKS * SK_SIZE
wNetOurIP::    DS 4
wNetReq::      DS NR_SIZE
wNetSockPtr::  DS 2
wNetIhl::      DS 1
wNetSeq::      DS 1
wNetEchoId::   DS 2       ; ICMP echo identifier: unique per boot + per host.
                          ; A fixed id (the old $1234) made every GB's ping
                          ; flow identical across boots/sessions, colliding in
                          ; upstream NAT conntrack (keyed on icmp id) - replies
                          ; were silently dropped until the stale entry expired.
wNetTx::       DS 320      ; tx build buffer
wNetRxBuf::    DS 320      ; rx frame assembly / parse
wNetRxLen::    DS 2        ; 16-bit: frames can exceed 255 bytes (DHCP/BOOTP)
wNetRxEsc::    DS 1
wNetInFrame:: DS 1        ; net_pump: currently inside a SLIP frame?
wConRing::    DS 64       ; console-input ring: non-framed bytes from the link
                          ; (link-injected console input, e.g. gbhub 'type').
                          ; One net_pump drains a whole serial burst into here
                          ; at once, so it must hold a full injected command
                          ; line - 16 was too small (dropped bytes, merged
                          ; lines). Size MUST stay a power of two (mask below).
wConHead::    DS 1
wConTail::    DS 1
wNetUdpPort::  DS 2      ; scratch: UDP dst port being demuxed
wNetTO::       DS 3      ; recv timeout counter (net_pump clobbers registers)
wNetRxRem::    DS 1      ; recv: bytes left in RXBUF after a clamped delivery
wNetRxOff::    DS 1      ; tcp_buffer_data: append offset (unread bytes)
wNetTcpInOrd:: DS 1      ; tcp_in: did this segment start exactly at rcv_nxt?
wNetTcpFlags:: DS 1      ; TCP flags for the segment being built
wNetTcpDlen::  DS 1      ; TCP payload length for the segment being built
wNetTcpIn::    DS 1      ; incoming TCP flags
wNetTcpDoff::  DS 1      ; incoming data offset (from frame start)
wNetTcpDlen2:: DS 1      ; incoming payload length
wNetTcpTh::    DS 1      ; TCP header length of the segment being built (20/24)

SECTION "socket", ROM0

; net_init - clear the socket table and set our IP (called at boot).
net_init::
    ld hl, wSockTab
    ld bc, MAX_SOCKS * SK_SIZE
.clr
    xor a
    ld [hl+], a
    dec bc
    ld a, b
    or c
    jr nz, .clr
    xor a
    ld [wNetOurIP+0], a         ; 0.0.0.0 until DHCP assigns an address
    ld [wNetOurIP+1], a
    ld [wNetOurIP+2], a
    ld [wNetOurIP+3], a
    ld [wNetRxLen], a
    ld [wNetRxLen+1], a
    ld [wNetRxEsc], a
    ld [wNetInFrame], a
    ld [wConHead], a
    ld [wConTail], a
    ld [wNetSeq], a
    ldh a, [rDIV]               ; per-boot echo id seed (refined at DHCP lease)
    ld [wNetEchoId], a
    cpl
    ld [wNetEchoId+1], a
    ret

; con_push(A) - queue a console-input byte (dropped if the ring is full)
con_push::
    ld b, a
    ld a, [wConTail]
    inc a
    and 63
    ld c, a
    ld a, [wConHead]
    cp c
    ret z                       ; full -> drop
    ld a, [wConTail]
    ld e, a
    ld d, 0
    ld hl, wConRing
    add hl, de
    ld [hl], b
    ld a, c
    ld [wConTail], a
    ret

; con_pop -> A = byte, CF set if the ring is empty
con_pop::
    ld a, [wConHead]
    ld b, a
    ld a, [wConTail]
    cp b
    jr nz, .have
    scf
    ret
.have
    ld a, b
    ld e, a
    ld d, 0
    ld hl, wConRing
    add hl, de
    ld c, [hl]
    ld a, b
    inc a
    and 63
    ld [wConHead], a
    ld a, c
    and a                       ; CF = 0
    ret

; net_setip - store our IPv4 address (from wNetReq.NR_IP). Used by the DHCP
; client once it has a lease.
net_op_setip:
    ld a, [wNetReq+NR_IP+0]
    ld [wNetOurIP+0], a
    ld a, [wNetReq+NR_IP+1]
    ld [wNetOurIP+1], a
    ld a, [wNetReq+NR_IP+2]
    ld [wNetOurIP+2], a
    ld a, [wNetReq+NR_IP+3]
    ld [wNetOurIP+3], a
    ld [wNetEchoId], a          ; echo id hi = our host octet (distinct per GB)
    ldh a, [rDIV]               ; lo = timer noise at lease time (distinct per
    ld [wNetEchoId+1], a        ; boot - DHCP timing varies with the network)
    xor a
    ret

; -----------------------------------------------------------------------------
; low-level link port (byte at a time). Preserve BC/DE/HL; use A only.
net_putbyte:                    ; A = byte to transmit
    ld [rSB], a
    ld a, $81
    ld [rSC], a
.w
    ld a, [rSC]
    bit 7, a
    jr nz, .w
    ret

net_getbyte_nb:                 ; -> A = byte, CF set if none
    ld a, $80
    ld [rSC], a
    ld a, [rSC]
    bit 7, a
    jr z, .got
    scf
    ret
.got
    ld a, [rSB]
    and a                       ; CF = 0
    ret

; -----------------------------------------------------------------------------
; net_slip_send(HL = buf, DE = len) - transmit a SLIP frame (len may exceed 255).
net_slip_send:
    ld a, SLIP_END
    call net_putbyte
.loop
    ld a, d
    or e
    jr z, .end
    ld a, [hl+]
    cp SLIP_END
    jr z, .esc_end
    cp SLIP_ESC
    jr z, .esc_esc
    call net_putbyte
.cont
    dec de
    jr .loop
.esc_end
    ld a, SLIP_ESC
    call net_putbyte
    ld a, SLIP_ESC_END
    call net_putbyte
    jr .cont
.esc_esc
    ld a, SLIP_ESC
    call net_putbyte
    ld a, SLIP_ESC_ESC
    call net_putbyte
    jr .cont
.end
    ld a, SLIP_END
    call net_putbyte
    ret

; -----------------------------------------------------------------------------
; net_sum(HL = buf, B = len, DE = seed) -> DE = folded 16-bit one's-complement
; sum (RFC 1071), carry-folded each add. len <= 255. Used to chain a pseudo-
; header into a segment checksum.
net_sum:
.loop
    ld a, b
    cp 2
    jr c, .tail
    ld a, [hl+]                 ; high byte
    ld c, a
    ld a, [hl+]                 ; low byte
    add e
    ld e, a
    ld a, c
    adc d
    ld d, a
    jr nc, .nc1
    inc de
.nc1
    dec b
    dec b
    jr .loop
.tail
    ld a, b
    or a
    ret z
    ld a, [hl]                  ; last odd byte -> high half
    add d
    ld d, a
    ret nc
    inc e
    ret nz
    inc d
    ret

; net_cksum(HL, B, DE=seed) -> HL = inverted 16-bit checksum.
net_cksum:
    call net_sum
    ld a, d
    cpl
    ld h, a
    ld a, e
    cpl
    ld l, a
    ret

; -----------------------------------------------------------------------------
; net_sock_ptr(A = sockid) -> HL = &wSockTab[A]  (clobbers B, DE)
net_sock_ptr:
    ld hl, wSockTab
    or a
    ret z
    ld b, a
    ld de, SK_SIZE
.l
    add hl, de
    dec b
    jr nz, .l
    ret

; =============================================================================
; sys_net(DE = &netreq) -> A = result
; =============================================================================
sys_net::
    ld hl, wNetReq              ; copy the request out of process RAM
    ld b, NR_SIZE
.cp
    ld a, [de]
    ld [hl+], a
    inc de
    dec b
    jr nz, .cp
    ld a, [wNetReq + NR_OP]
    cp NET_SOCKET
    jp z, net_op_socket
    cp NET_CONNECT
    jp z, net_op_connect
    cp NET_SEND
    jp z, net_op_send
    cp NET_RECV
    jp z, net_op_recv
    cp NET_CLOSE
    jp z, net_op_close
    cp NET_BIND
    jp z, net_op_bind
    cp NET_POLL
    jp z, net_op_poll
    cp NET_SETIP
    jp z, net_op_setip
    cp NET_RECVNB
    jp z, net_op_recvnb
    cp NET_LISTEN
    jp z, net_op_listen
    cp NET_ACCEPT
    jp z, net_op_accept
    ld a, $FF
    ret

; ---- listen(sock, port) - passive open ---------------------------------------
; Sockets demux on LOCAL PORT alone (net_find_tcp), so a listener and its
; connection are the same socket: the SYN fills in RIP/RPORT and the socket
; becomes the connection. One connection at a time, re-armed by listening
; again after close - which is all a 4-socket table can honestly promise.
net_op_listen:
    call listen_port_free       ; CF if another socket already holds the port
    jr nc, .ok
    ld a, $FF                   ; "address already in use": refuse loudly. Two
    ret                         ; sockets on one port silently black-hole the
                                ; second listener - demux takes the first match
.ok
    ld a, [wNetReq + NR_SOCK]
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    ld a, l
    add SK_LPORT
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [wNetReq + NR_PORT]
    ld [hl+], a
    ld a, [wNetReq + NR_PORT + 1]
    ld [hl], a
    call sock_ptr_hl            ; drop anything left over from a previous
    ld a, l                     ; connection on this socket
    add SK_HASRX
    ld l, a
    ld a, h
    adc 0
    ld h, a
    xor a
    ld [hl+], a                 ; HASRX = 0
    ld [hl], a                  ; RXLEN = 0 (SK_RXLEN = SK_HASRX + 1)
    ld a, TCP_LISTEN
    call sock_state_set
    xor a
    ret

; listen_port_free -> CF set if a socket OTHER than this one is already bound
; to the requested local port.
listen_port_free:
    ld c, 0
.l
    ld a, [wNetReq + NR_SOCK]
    cp c
    jr z, .nx                   ; ourselves: fine
    ld a, c
    call net_sock_ptr
    ld a, [hl]
    or a
    jr z, .nx                   ; free slot
    ld a, l
    add SK_LPORT
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [wNetReq + NR_PORT]
    cp [hl]
    jr nz, .nx
    inc hl
    ld a, [wNetReq + NR_PORT + 1]
    cp [hl]
    jr nz, .nx
    scf
    ret
.nx
    inc c
    ld a, c
    cp MAX_SOCKS
    jr c, .l
    or a
    ret

; ---- accept(sock) -> A = 0 connected / $FE not yet ---------------------------
; Never blocks: one pump per call, exactly like recv_nb. A server that owns its
; main loop (httpd) keeps polling the keyboard and stays killable; a kernel-side
; blocking accept would wedge the process forever on a quiet port.
net_op_accept:
    ld a, [wNetReq + NR_SOCK]
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    call net_pump
    ld a, [wNetReq + NR_SOCK]   ; tcp_in moves wNetSockPtr; restore ours
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    call sock_ptr_hl
    ld a, l
    add SK_STATE
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    cp TCP_ESTAB
    jr z, .up
    cp TCP_DONE                 ; opened and closed between two polls: still a
    jr z, .up                   ; connection - let the app read its buffer/EOF
    ld a, $FE
    ret
.up
    xor a
    ret

; ---- bind(sock, port) - set local port -----------------------------------
net_op_bind:
    ld a, [wNetReq + NR_SOCK]
    call net_sock_ptr
    ld a, l
    add SK_LPORT
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [wNetReq + NR_PORT]
    ld [hl+], a
    ld a, [wNetReq + NR_PORT + 1]
    ld [hl], a
    xor a
    ret

; ---- socket(type) -> A = sockid or $FF ---------------------------------------
net_op_socket:
    ld c, 0
.scan
    ld a, c
    call net_sock_ptr           ; HL = &sock[c]
    ld a, [hl]
    or a                        ; SK_TYPE == 0 (free)?
    jr z, .free
    inc c
    ld a, c
    cp MAX_SOCKS
    jr c, .scan
    ld a, $FF                   ; table full
    ret
.free
    ld a, [wNetReq + NR_SOCK]   ; requested type
    ld [hl], a                  ; SK_TYPE
    push hl
    ld a, l                     ; clear SK_HASRX
    add SK_HASRX
    ld l, a
    ld a, h
    adc 0
    ld h, a
    xor a
    ld [hl], a
    call CurPid                 ; NB: clobbers HL, so take the pid *before*
    ld b, a                     ; addressing the field (see SockReleaseOwner)
    pop hl
    ld a, l                     ; remember who owns it
    add SK_OWNER
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld [hl], b
    ld a, c                     ; return sockid
    ret

; CurPid -> A = the running process's pid
CurPid:
    ld a, [wCurProc]
    add PROC_PID
    ld l, a
    ld a, [wCurProc+1]
    adc 0
    ld h, a
    ld a, [hl]
    ret

; =============================================================================
; SockReleaseOwner - free every socket owned by pid wExitMyPid.
;
; Sockets are a global table of 4; a process that dies without close()ing (a
; kill(1), or any crash) used to hold its slot until reboot, so killing irc/nc
; a few times left the box unable to open a socket at all. exit and kill both
; call this where they reparent children.
; =============================================================================
SockReleaseOwner::
    ld c, 0
.l
    ld a, c
    call net_sock_ptr           ; HL = &sock[c]
    ld a, [hl]
    or a
    jr z, .nx                   ; already free
    push hl
    ld a, l
    add SK_OWNER
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [wExitMyPid]
    cp [hl]
    pop hl
    jr nz, .nx
    xor a
    ld [hl], a                  ; SK_TYPE = free
.nx
    inc c
    ld a, c
    cp MAX_SOCKS
    jr c, .l
    ret

; ---- connect(sock, ip, port) - set remote (+ TCP handshake) ---------------
net_op_connect:
    ld a, [wNetReq + NR_SOCK]
    call net_sock_ptr           ; HL = &sock
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    ld a, l
    add SK_RIP
    ld l, a
    ld a, h
    adc 0
    ld h, a                     ; HL = &sock.RIP
    ld de, wNetReq + NR_IP
    ld b, 6                     ; 4 IP + 2 port (contiguous: RIP then RPORT)
.cp
    ld a, [de]
    ld [hl+], a
    inc de
    dec b
    jr nz, .cp
    call sock_ptr_hl
    ld a, [hl]                  ; SK_TYPE
    cp SOCK_TCP
    jp z, tcp_connect
    xor a
    ret

; ---- close(sock) -------------------------------------------------------------
net_op_close:
    ld a, [wNetReq + NR_SOCK]
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    ld a, [hl]                  ; SK_TYPE
    cp SOCK_TCP
    jp z, tcp_close
    call sock_ptr_hl
    xor a
    ld [hl], a                  ; SK_TYPE = free
    ret

; ---- poll - pump RX once (answers pings) -------------------------------------
net_op_poll:
    call net_pump
    xor a
    ret

; ---- send(sock, buf, len) ----------------------------------------------------
net_op_send:
    ld a, [wNetReq + NR_SOCK]
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    ld a, [hl]                  ; SK_TYPE
    cp SOCK_ICMP
    jp z, icmp_send
    cp SOCK_UDP
    jp z, udp_send
    cp SOCK_TCP
    jp z, tcp_data_send
    ld a, $FF
    ret

; ---- recvnb(sock, buf, maxlen) -> A = len / $FE (nothing yet) / 0 (TCP EOF) --
; One pump, no blocking: programs that need their own (wall-clock) timeout -
; ping, most of all - loop recvnb+msleep instead of sitting in net_op_recv's
; pump-counted wait, which at native speed can block for minutes if a reply
; is lost (e.g. a host that rate-limits ICMP).
net_op_recvnb:
    ld a, [wNetReq + NR_SOCK]
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    call net_pump
    ld a, [wNetReq+NR_SOCK]     ; tcp_in may have moved wNetSockPtr; restore
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    call sock_has_rx
    jp nz, net_op_recv.got      ; deliver exactly like a blocking recv
    call sock_ptr_hl            ; TCP peer closed + nothing buffered -> EOF
    ld a, l
    add SK_STATE
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    cp TCP_DONE
    jr nz, .none
    xor a                       ; EOF -> 0, same as net_op_recv
    ret
.none
    ld a, $FE                   ; nothing buffered yet
    ret

; ---- recv(sock, buf, maxlen) -> A = len or $FF (timeout) ---------------------
net_op_recv:
    ld a, [wNetReq + NR_SOCK]
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    xor a                       ; 24-bit timeout counter in WRAM (net_pump
    ld [wNetTO], a              ; clobbers BC/DE/HL, so we can't count in regs)
    ld [wNetTO+1], a
    ld [wNetTO+2], a
.wait
    call net_pump
    ld a, [wNetReq+NR_SOCK]     ; tcp_in may have moved wNetSockPtr; restore ours
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    call sock_has_rx            ; nz if a datagram is buffered
    jr nz, .got
    call sock_ptr_hl            ; TCP peer closed + no data -> EOF (return 0)
    ld a, l
    add SK_STATE
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    cp TCP_DONE
    jr z, .eof
    ld hl, wNetTO
    inc [hl]
    jr nz, .wait                ; low byte didn't wrap -> spin (no yield)
    call SchedYield             ; every 256 pumps, yield to the scheduler
    inc hl
    inc [hl]
    jr nz, .wait
    inc hl
    inc [hl]
    ld a, [hl]
    cp 250                      ; timeout after ~250*65536 pumps
    jr c, .wait
    ld a, $FF
    ret
.eof
    xor a                       ; connection closed, no data -> 0 bytes (EOF)
    ret
.got
    ; copy sock.RXBUF -> process NR_BUF, len = min(sock.RXLEN, caller maxlen).
    ;
    ; The clamp is not optional: a TCP segment can be up to 208 bytes here, so
    ; copying RXLEN blindly overran any caller whose buffer was smaller and
    ; silently smashed its locals/stack (a 96-byte buffer + a 200-byte reply =
    ; a hung process). Deliver what fits, keep the tail for the next recv.
    call sock_ptr_hl            ; HL = &sock
    push hl
    ld a, l
    add SK_RXLEN
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]                  ; RXLEN
    ld c, a                     ; C = bytes buffered
    ld b, a                     ; B = keep the untruncated total
    pop hl
    ld a, [wNetReq+NR_LEN]      ; caller's maxlen
    or a
    jr z, .toosmall             ; maxlen 0: refuse rather than corrupt
    cp c
    jr nc, .fits                ; maxlen >= buffered -> deliver it all
    ld c, a                     ; else deliver exactly maxlen
.fits
    ; source IP -> wNetReq.NR_IP (returned to caller via buffer? no - copy to caller req is skipped; give src via NR_IP in kernel copy only)
    push bc
    push hl
    ; dst = process buf pointer
    ld a, [wNetReq + NR_BUF]
    ld e, a
    ld a, [wNetReq + NR_BUF + 1]
    ld d, a                     ; DE = process buf
    ld a, l
    add SK_RXBUF
    ld l, a
    ld a, h
    adc 0
    ld h, a                     ; HL = &sock.RXBUF
    ld a, c
    or a
    jr z, .nocopy
.cpl
    ld a, [hl+]
    ld [de], a
    inc de
    dec c
    jr nz, .cpl
.nocopy
    pop hl                      ; &sock
    pop bc                      ; B = bytes buffered, C = bytes delivered
    ld a, b
    sub c
    jr nz, .partial             ; caller's buffer was too small for all of it
    ; fully drained: clear HASRX *and* RXLEN. RXLEN is the append offset for
    ; the next segment (tcp_buffer_data), so leaving it stale makes every
    ; later segment look too big to fit and the connection stalls out.
    push hl
    ld a, l
    add SK_RXLEN
    ld l, a
    ld a, h
    adc 0
    ld h, a
    xor a
    ld [hl], a
    pop hl
    ld a, l
    add SK_HASRX
    ld l, a
    ld a, h
    adc 0
    ld h, a
    xor a
    ld [hl], a
    ld a, c                     ; return length
    ret
.toosmall
    ld a, $FE                   ; nothing delivered, nothing consumed
    ret
.partial
    ; A = leftover bytes. Shift them down to the front of RXBUF and leave
    ; HASRX set, so the next recv() returns the rest of the segment.
    ld [wNetRxRem], a
    ld a, l
    add SK_RXBUF
    ld l, a
    ld a, h
    adc 0
    ld h, a                     ; HL = &RXBUF
    ld d, h
    ld e, l                     ; DE = dst = &RXBUF
    ld a, l
    add c
    ld l, a
    ld a, h
    adc 0
    ld h, a                     ; HL = src = &RXBUF + delivered
    ld a, [wNetRxRem]
    ld b, a                     ; B = leftover count (1..255)
.shift
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .shift
    call sock_ptr_hl
    ld a, l
    add SK_RXLEN
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [wNetRxRem]
    ld [hl], a                  ; RXLEN = leftover (HASRX stays set)
    ld a, [wNetReq+NR_LEN]      ; delivered exactly maxlen
    ret

; sock_ptr_hl -> HL = current socket pointer (from wNetSockPtr)
sock_ptr_hl:
    ld a, [wNetSockPtr]
    ld l, a
    ld a, [wNetSockPtr+1]
    ld h, a
    ret

; sock_has_rx -> Z clear (nz) if the current socket has a buffered datagram
sock_has_rx:
    call sock_ptr_hl
    ld a, l
    add SK_HASRX
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    or a
    ret

; =============================================================================
; icmp_send - build + transmit an ICMP echo request from the current socket.
; =============================================================================
icmp_send:
    ; IP header (20 bytes)
    ld a, $45
    ld [wNetTx+0], a
    xor a
    ld [wNetTx+1], a
    ld [wNetTx+2], a            ; total len hi
    ld a, [wNetReq+NR_LEN]
    add 28
    ld [wNetTx+3], a            ; total len lo = 28 + payload
    xor a
    ld [wNetTx+4], a
    ld [wNetTx+5], a            ; id
    ld [wNetTx+6], a
    ld [wNetTx+7], a            ; flags/frag
    ld a, 64
    ld [wNetTx+8], a           ; ttl
    ld a, 1
    ld [wNetTx+9], a           ; proto ICMP
    xor a
    ld [wNetTx+10], a
    ld [wNetTx+11], a          ; ip cksum
    ld a, [wNetOurIP+0]
    ld [wNetTx+12], a
    ld a, [wNetOurIP+1]
    ld [wNetTx+13], a
    ld a, [wNetOurIP+2]
    ld [wNetTx+14], a
    ld a, [wNetOurIP+3]
    ld [wNetTx+15], a
    ; dst IP = sock.RIP
    call sock_ptr_hl
    ld a, l
    add SK_RIP
    ld l, a
    ld a, h
    adc 0
    ld h, a                     ; HL = &sock.RIP
    ld de, wNetTx+16
    ld b, 4
.dip
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .dip
    ; ICMP header (8 bytes) at wNetTx+20
    ld a, 8
    ld [wNetTx+20], a          ; type = echo request
    xor a
    ld [wNetTx+21], a          ; code
    ld [wNetTx+22], a
    ld [wNetTx+23], a          ; cksum
    ld a, [wNetEchoId]
    ld [wNetTx+24], a          ; id (unique per boot + host, set by net_setip)
    ld a, [wNetEchoId+1]
    ld [wNetTx+25], a
    xor a
    ld [wNetTx+26], a          ; seq hi
    ld a, [wNetSeq]
    inc a
    ld [wNetSeq], a
    ld [wNetTx+27], a          ; seq lo
    ; payload from process buf
    ld a, [wNetReq+NR_BUF]
    ld l, a
    ld a, [wNetReq+NR_BUF+1]
    ld h, a
    ld de, wNetTx+28
    ld a, [wNetReq+NR_LEN]
    ld b, a
    or a
    jr z, .nopl
.cppl
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .cppl
.nopl
    ; ICMP checksum over 8 + payload
    ld a, [wNetReq+NR_LEN]
    add 8
    ld b, a
    ld hl, wNetTx+20
    ld de, 0
    call net_cksum
    ld a, h
    ld [wNetTx+22], a
    ld a, l
    ld [wNetTx+23], a
    ; IP checksum over 20
    ld hl, wNetTx
    ld b, 20
    ld de, 0
    call net_cksum
    ld a, h
    ld [wNetTx+10], a
    ld a, l
    ld [wNetTx+11], a
    ; transmit: 28 + payload
    ld a, [wNetReq+NR_LEN]
    add 28
    ld e, a
    ld d, 0
    ld hl, wNetTx
    call net_slip_send
    xor a
    ret

; =============================================================================
; udp_send - build + transmit a UDP datagram from the current socket.
; =============================================================================
udp_send:
    ld a, $45
    ld [wNetTx+0], a
    xor a
    ld [wNetTx+1], a
    ld a, [wNetReq+NR_LEN]
    add 28                      ; 20 IP + 8 UDP + payload
    ld [wNetTx+3], a            ; IP total length low
    ld a, 0
    adc 0
    ld [wNetTx+2], a            ; IP total length high (carry, for DHCP)
    xor a
    ld [wNetTx+4], a
    ld [wNetTx+5], a
    ld [wNetTx+6], a
    ld [wNetTx+7], a
    ld a, 64
    ld [wNetTx+8], a
    ld a, 17
    ld [wNetTx+9], a           ; proto UDP
    xor a
    ld [wNetTx+10], a
    ld [wNetTx+11], a
    ld a, [wNetOurIP+0]
    ld [wNetTx+12], a
    ld a, [wNetOurIP+1]
    ld [wNetTx+13], a
    ld a, [wNetOurIP+2]
    ld [wNetTx+14], a
    ld a, [wNetOurIP+3]
    ld [wNetTx+15], a
    ; dst IP = sock.RIP
    call sock_ptr_hl
    ld a, l
    add SK_RIP
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld de, wNetTx+16
    ld b, 4
.dip
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .dip
    ; UDP header at wNetTx+20: src port = SK_LPORT
    call sock_ptr_hl
    ld a, l
    add SK_LPORT
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl+]
    ld [wNetTx+20], a
    ld a, [hl]
    ld [wNetTx+21], a
    ; dst port = SK_RPORT
    call sock_ptr_hl
    ld a, l
    add SK_RPORT
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl+]
    ld [wNetTx+22], a
    ld a, [hl]
    ld [wNetTx+23], a
    ; length = 8 + payload
    xor a
    ld [wNetTx+24], a
    ld a, [wNetReq+NR_LEN]
    add 8
    ld [wNetTx+25], a
    xor a
    ld [wNetTx+26], a          ; cksum = 0
    ld [wNetTx+27], a
    ; payload from process buf
    ld a, [wNetReq+NR_BUF]
    ld l, a
    ld a, [wNetReq+NR_BUF+1]
    ld h, a
    ld de, wNetTx+28
    ld a, [wNetReq+NR_LEN]
    ld b, a
    or a
    jr z, .nopl
.cppl
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .cppl
.nopl
    ; UDP checksum with pseudo-header: sum(src+dst IP) + proto + udplen, then seg
    ld hl, wNetTx+12
    ld b, 8
    ld de, 0
    call net_sum               ; DE = IP-address sum
    ld a, e
    add 17                     ; + protocol
    ld e, a
    ld a, d
    adc 0
    ld d, a
    ld a, [wNetReq+NR_LEN]
    add 8                      ; + udp length
    add e
    ld e, a
    ld a, d
    adc 0
    ld d, a                    ; DE = pseudo-header seed
    ld a, [wNetReq+NR_LEN]
    add 8
    ld b, a
    ld hl, wNetTx+20
    call net_cksum             ; HL = inverted checksum
    ld a, h
    or l
    jr nz, .cknz
    ld hl, $FFFF               ; 0 means "no checksum" -> send all-ones
.cknz
    ld a, h
    ld [wNetTx+26], a
    ld a, l
    ld [wNetTx+27], a
    ; IP checksum
    ld hl, wNetTx
    ld b, 20
    ld de, 0
    call net_cksum
    ld a, h
    ld [wNetTx+10], a
    ld a, l
    ld [wNetTx+11], a
    ld a, [wNetReq+NR_LEN]
    add 28
    ld e, a
    ld a, 0
    adc 0
    ld d, a
    ld hl, wNetTx
    call net_slip_send
    xor a
    ret

; =============================================================================
; net_pump - read available serial bytes, assemble SLIP frames, process each.
; Non-blocking: returns when the link has no more bytes ready.
; =============================================================================
net_pump::
.next
    call net_getbyte_nb
    ret c                       ; no byte ready
    cp SLIP_END
    jr z, .delim
    ld c, a                     ; save byte
    ld a, [wNetInFrame]
    or a
    jr nz, .inframe
    ld a, c                     ; outside a frame -> console input
    call con_push
    jr .next
.inframe
    ld a, [wNetRxEsc]
    or a
    jr nz, .escaped
    ld a, c
    cp SLIP_ESC
    jr z, .setesc
    jr .store
.escaped
    ld a, c
    cp SLIP_ESC_END
    jr nz, .notend
    ld c, SLIP_END
.notend
    ld a, c
    cp SLIP_ESC_ESC
    jr nz, .noteesc
    ld c, SLIP_ESC
.noteesc
    xor a
    ld [wNetRxEsc], a
    ld a, c
    jr .store2
.setesc
    ld a, 1
    ld [wNetRxEsc], a
    jr .next
.store
    ld a, c
.store2
    ld c, a                     ; C = byte to store
    ; index = wNetRxLen (16-bit); drop if >= 320 (buffer size)
    ld a, [wNetRxLen+1]
    or a
    jr z, .instore              ; high 0 -> index < 256, room
    cp 1
    jr nz, .next                ; high >= 2 -> overflow, drop
    ld a, [wNetRxLen]
    cp 64                       ; high 1 -> room iff low < 64 (index < 320)
    jr nc, .next
.instore
    ld a, [wNetRxLen]
    ld e, a
    ld a, [wNetRxLen+1]
    ld d, a
    ld hl, wNetRxBuf
    add hl, de
    ld a, c
    ld [hl], a
    ld a, [wNetRxLen]           ; index++
    inc a
    ld [wNetRxLen], a
    jp nz, .next
    ld a, [wNetRxLen+1]
    inc a
    ld [wNetRxLen+1], a
    jp .next
.delim
    ; 0xC0 delimiter: end the current frame (process it) or start a new one.
    xor a
    ld [wNetRxEsc], a
    ld a, [wNetInFrame]
    or a
    jr z, .startframe
    ld a, [wNetRxLen]
    ld hl, wNetRxLen+1
    or [hl]
    jr z, .resetframe           ; empty frame
    call process_frame
.resetframe
    xor a
    ld [wNetInFrame], a
    ld [wNetRxLen], a
    ld [wNetRxLen+1], a
    ret                         ; one frame per pump
.startframe
    ld a, 1
    ld [wNetInFrame], a
    xor a
    ld [wNetRxLen], a
    ld [wNetRxLen+1], a
    jp .next

; -----------------------------------------------------------------------------
; process_frame - IPv4 demux of the frame in wNetRxBuf (wNetRxLen bytes).
process_frame:
    ld a, [wNetRxBuf]
    and $F0
    cp $40
    ret nz                      ; not IPv4
    ld a, [wNetRxBuf]
    and $0F
    add a, a
    add a, a
    ld [wNetIhl], a             ; ihl in bytes
    ld a, [wNetRxBuf+9]         ; protocol
    cp 1
    jp z, icmp_in
    cp 17
    jp z, udp_in
    cp 6
    jp z, tcp_in
    ret

; -----------------------------------------------------------------------------
; icmp_in - handle an inbound ICMP message.
icmp_in:
    ld a, [wNetIhl]
    ld e, a
    ld d, 0
    ld hl, wNetRxBuf
    add hl, de                  ; HL = &icmp
    ld a, [hl]                  ; type
    cp 8
    jr z, icmp_request
    or a                        ; type 0 = echo reply
    jr z, icmp_reply
    ret

; incoming echo request -> answer it in place
icmp_request:
    ld a, [wNetIhl]
    ld e, a
    ld d, 0
    ld hl, wNetRxBuf
    add hl, de                  ; HL = &icmp
    xor a
    ld [hl+], a                 ; type = 0
    inc hl                      ; skip code
    xor a
    ld [hl+], a
    ld [hl], a                  ; cksum = 0
    call net_swap_ip
    ; icmp cksum over (rxlen - ihl)
    ld a, [wNetIhl]
    ld e, a
    ld d, 0
    ld hl, wNetRxBuf
    add hl, de                  ; HL = &icmp
    ld a, [wNetRxLen]
    sub e
    ld b, a
    ld de, 0
    push hl
    call net_cksum              ; HL = cksum
    pop de                      ; DE = &icmp
    ld a, e
    add 2
    ld e, a
    ld a, d
    adc 0
    ld d, a                     ; DE = &icmp+2
    ld a, h
    ld [de], a
    inc de
    ld a, l
    ld [de], a
    ; IP cksum
    xor a
    ld [wNetRxBuf+10], a
    ld [wNetRxBuf+11], a
    ld a, [wNetIhl]
    ld b, a
    ld hl, wNetRxBuf
    ld de, 0
    call net_cksum
    ld a, h
    ld [wNetRxBuf+10], a
    ld a, l
    ld [wNetRxBuf+11], a
    ; send it back
    ld a, [wNetRxLen]
    ld e, a
    ld a, [wNetRxLen+1]
    ld d, a
    ld hl, wNetRxBuf
    call net_slip_send
    ret

; incoming echo reply -> deliver to the first ICMP socket
icmp_reply:
    ld c, 0
.scan
    ld a, c
    call net_sock_ptr           ; HL = &sock
    ld a, [hl]
    cp SOCK_ICMP
    jr z, .deliver
    inc c
    ld a, c
    cp MAX_SOCKS
    jr c, .scan
    ret                         ; no ICMP socket
.deliver
    ; HL = &sock. payload = wNetRxBuf + ihl + 8, len = rxlen - ihl - 8
    push hl
    ; set HASRX = 1
    ld a, l
    add SK_HASRX
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, 1
    ld [hl], a
    pop hl
    ; SRCIP = wNetRxBuf[12..15]
    push hl
    ld a, l
    add SK_SRCIP
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld de, wNetRxBuf+12
    ld b, 4
.sip
    ld a, [de]
    ld [hl+], a
    inc de
    dec b
    jr nz, .sip
    pop hl
    ; RXLEN + RXBUF
    ld a, [wNetIhl]
    add 8
    ld e, a
    ld d, 0                     ; DE = ihl+8 (payload offset)
    ld a, [wNetRxLen]
    sub e
    ld c, a                     ; C = payload length
    push hl
    ld a, l
    add SK_RXLEN
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, c
    ld [hl], a                  ; RXLEN
    pop hl
    ; copy payload
    ld a, l
    add SK_RXBUF
    ld l, a
    ld a, h
    adc 0
    ld h, a                     ; HL = &sock.RXBUF (dest)
    push hl
    ld hl, wNetRxBuf
    add hl, de                  ; HL = &payload (src)
    pop de                      ; DE = dest
    ld a, c
    or a
    ret z
.cp
    ld a, [hl+]
    ld [de], a
    inc de
    dec c
    jr nz, .cp
    ret

; -----------------------------------------------------------------------------
; udp_in - deliver an inbound UDP datagram to the socket bound to its dst port.
udp_in:
    ld a, [wNetIhl]
    add 2
    ld e, a
    ld d, 0
    ld hl, wNetRxBuf
    add hl, de                  ; HL = &udp.dstport
    ld a, [hl+]
    ld [wNetUdpPort], a
    ld a, [hl]
    ld [wNetUdpPort+1], a
    call net_find_udp           ; HL = &sock, CF if none
    ret c
    ; deliver: HASRX=1, SRCIP, RXLEN + RXBUF (payload after ihl+8)
    push hl
    ld a, l
    add SK_HASRX
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, 1
    ld [hl], a
    pop hl
    push hl
    ld a, l
    add SK_SRCIP
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld de, wNetRxBuf+12
    ld b, 4
.sip
    ld a, [de]
    ld [hl+], a
    inc de
    dec b
    jr nz, .sip
    pop hl
    ; payload offset = ihl + 8, length = rxlen - ihl - 8
    ld a, [wNetIhl]
    add 8
    ld e, a
    ld d, 0
    ld a, [wNetRxLen]
    sub e
    ld c, a                     ; C = payload length
    push hl
    ld a, l
    add SK_RXLEN
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, c
    ld [hl], a
    pop hl
    ld a, l
    add SK_RXBUF
    ld l, a
    ld a, h
    adc 0
    ld h, a                     ; HL = &sock.RXBUF (dest)
    push hl
    ld hl, wNetRxBuf
    add hl, de                  ; HL = &payload (src)
    pop de                      ; DE = dest
    ld a, c
    or a
    ret z
.cp
    ld a, [hl+]
    ld [de], a
    inc de
    dec c
    jr nz, .cp
    ret

; net_find_udp -> HL = &UDP socket bound to wNetUdpPort, CF set if none
net_find_udp:
    ld c, 0
.l
    ld a, c
    call net_sock_ptr           ; HL = &sock (clobbers B, DE)
    ld a, [hl]
    cp SOCK_UDP
    jr nz, .nx
    push hl
    ld a, l
    add SK_LPORT
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [wNetUdpPort]
    cp [hl]
    jr nz, .nomatch
    inc hl
    ld a, [wNetUdpPort+1]
    cp [hl]
    jr nz, .nomatch
    pop hl                      ; match
    or a                        ; CF = 0
    ret
.nomatch
    pop hl
.nx
    inc c
    ld a, c
    cp MAX_SOCKS
    jr c, .l
    scf
    ret

; net_swap_ip - swap the src/dst IP fields of the frame in wNetRxBuf
net_swap_ip:
    ld hl, wNetRxBuf+12
    ld de, wNetRxBuf+16
    ld b, 4
.l
    ld a, [hl]
    ld c, a
    ld a, [de]
    ld [hl+], a
    ld a, c
    ld [de], a
    inc de
    dec b
    jr nz, .l
    ret

; =============================================================================
; TCP - a minimal client: 3-way handshake, in-order data, FIN close. No
; retransmission (the GB<->host link is lossless; the host's real TCP handles
; the internet side). One rx segment buffered per socket at a time.
; =============================================================================

; sk_field_to(A = socket field offset, DE = dest, B = count) - copy from socket
sk_field_to:
    push bc
    push de
    ld c, a
    call sock_ptr_hl
    ld a, l
    add c
    ld l, a
    ld a, h
    adc 0
    ld h, a
    pop de
    pop bc
.l
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .l
    ret

; sk_add_snd/sk_add_rcv(A = amount) - add to the 32-bit big-endian seq field
sk_add_snd:
    ld c, SK_SND
    jr sk_add_seq
sk_add_rcv:
    ld c, SK_RCV
sk_add_seq:
    ld b, a
    call sock_ptr_hl
    ld a, l
    add c
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, l
    add 3
    ld l, a
    ld a, h
    adc 0
    ld h, a                     ; HL = &field[3] (LSB)
    ld a, [hl]
    add b
    ld [hl], a
    ret nc
    dec hl
    inc [hl]
    ret nz
    dec hl
    inc [hl]
    ret nz
    dec hl
    inc [hl]
    ret

; sk_seq_in_order -> Z set iff the incoming segment's SEQ == rcv_nxt.
; A retransmitted (or out-of-order) segment fails this; accepting it anyway
; would render the same data twice AND over-advance rcv_nxt, after which every
; ACK we send is beyond the peer's snd_nxt - real stacks then drop our data
; segments (RFC 793 bogus-ACK rule) and the session wedges silently.
sk_seq_in_order:
    ld a, [wNetIhl]
    add 4
    ld e, a
    ld d, 0
    ld hl, wNetRxBuf
    add hl, de                  ; HL = &their_seq (big-endian, 4 bytes)
    push hl
    call sock_ptr_hl
    ld a, l
    add SK_RCV
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld d, h
    ld e, l                     ; DE = &rcv_nxt
    pop hl
    ld b, 4
.cmp
    ld a, [de]
    cp [hl]
    ret nz                      ; mismatch -> NZ
    inc de
    inc hl
    dec b
    jr nz, .cmp
    ret                         ; all 4 equal -> Z (from dec b)

; sk_set_rcv_from_seq(A = addend) - rcv_nxt = their_seq(from packet) + addend
sk_set_rcv_from_seq:
    push af
    ld a, [wNetIhl]
    add 4
    ld e, a
    ld d, 0
    ld hl, wNetRxBuf
    add hl, de                  ; HL = &their_seq
    push hl
    call sock_ptr_hl
    ld a, l
    add SK_RCV
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld d, h
    ld e, l                     ; DE = &SK_RCV
    pop hl                      ; HL = &their_seq
    ld a, [hl+]
    ld [de], a
    inc de
    ld a, [hl+]
    ld [de], a
    inc de
    ld a, [hl+]
    ld [de], a
    inc de
    ld a, [hl]
    ld [de], a
    pop af
    call sk_add_rcv
    ret

; net_find_tcp -> HL = &TCP socket bound to wNetUdpPort, CF set if none
net_find_tcp:
    ld c, 0
.l
    ld a, c
    call net_sock_ptr
    ld a, [hl]
    cp SOCK_TCP
    jr nz, .nx
    push hl
    ld a, l
    add SK_LPORT
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [wNetUdpPort]
    cp [hl]
    jr nz, .nomatch
    inc hl
    ld a, [wNetUdpPort+1]
    cp [hl]
    jr nz, .nomatch
    pop hl
    or a
    ret
.nomatch
    pop hl
.nx
    inc c
    ld a, c
    cp MAX_SOCKS
    jr c, .l
    scf
    ret

; tcp_peer_is_current -> Z if the segment in wNetRxBuf came from the peer this
; socket is already talking to (same source IP *and* source port). Sockets
; demux on local port alone, so a second client's SYN reaches the same socket
; as the connection in progress; only this tells them apart.
tcp_peer_is_current:
    call sock_ptr_hl
    ld a, l
    add SK_RIP
    ld e, a
    ld a, h
    adc 0
    ld d, a                     ; DE = &SK_RIP (SK_RPORT follows it)
    ld hl, wNetRxBuf + 12       ; source IP in the IP header
    ld b, 4
.ip
    ld a, [de]
    cp [hl]
    ret nz
    inc de
    inc hl
    dec b
    jr nz, .ip
    ld a, [wNetIhl]             ; source port in the TCP header
    ld l, a
    ld h, 0
    ld bc, wNetRxBuf
    add hl, bc
    ld a, [de]
    cp [hl]
    ret nz
    inc de
    inc hl
    ld a, [de]
    cp [hl]
    ret

; tcp_send_seg - build+send a segment from the current socket. wNetTcpFlags =
; flags, wNetTcpDlen = payload length (payload read from wNetReq.NR_BUF). A SYN
; also carries an MSS option so the peer never sends us an oversized segment.
tcp_send_seg:
    ld a, [wNetTcpFlags]
    and TF_SYN
    ld a, 20
    jr z, .th
    ld a, 24
.th
    ld [wNetTcpTh], a
    ld a, $45
    ld [wNetTx+0], a
    xor a
    ld [wNetTx+1], a
    ld [wNetTx+2], a
    ld a, [wNetTcpTh]
    add 20
    ld b, a
    ld a, [wNetTcpDlen]
    add b
    ld [wNetTx+3], a            ; total = 20 + thlen + dlen
    xor a
    ld [wNetTx+4], a
    ld [wNetTx+5], a
    ld [wNetTx+6], a
    ld [wNetTx+7], a
    ld a, 64
    ld [wNetTx+8], a
    ld a, 6
    ld [wNetTx+9], a
    xor a
    ld [wNetTx+10], a
    ld [wNetTx+11], a
    ld a, [wNetOurIP+0]
    ld [wNetTx+12], a
    ld a, [wNetOurIP+1]
    ld [wNetTx+13], a
    ld a, [wNetOurIP+2]
    ld [wNetTx+14], a
    ld a, [wNetOurIP+3]
    ld [wNetTx+15], a
    ld a, SK_RIP
    ld de, wNetTx+16
    ld b, 4
    call sk_field_to
    ld a, SK_LPORT
    ld de, wNetTx+20
    ld b, 2
    call sk_field_to
    ld a, SK_RPORT
    ld de, wNetTx+22
    ld b, 2
    call sk_field_to
    ld a, SK_SND
    ld de, wNetTx+24
    ld b, 4
    call sk_field_to
    ld a, SK_RCV
    ld de, wNetTx+28
    ld b, 4
    call sk_field_to
    ld a, [wNetTcpTh]
    cp 24
    ld a, $50
    jr nz, .doff
    ld a, $60
.doff
    ld [wNetTx+32], a
    ld a, [wNetTcpFlags]
    ld [wNetTx+33], a
    ld a, 2
    ld [wNetTx+34], a           ; window = 512
    xor a
    ld [wNetTx+35], a
    ld [wNetTx+36], a
    ld [wNetTx+37], a
    ld [wNetTx+38], a
    ld [wNetTx+39], a
    ld a, [wNetTcpTh]
    cp 24
    jr nz, .nomss
    ld a, 2
    ld [wNetTx+40], a           ; MSS option kind
    ld a, 4
    ld [wNetTx+41], a           ; length
    xor a
    ld [wNetTx+42], a
    ld a, TCP_MSS
    ld [wNetTx+43], a
.nomss
    ld a, [wNetTcpDlen]
    or a
    jr z, .nodata
    ld a, [wNetTcpTh]
    add 20
    ld e, a
    ld d, 0
    ld hl, wNetTx
    add hl, de
    ld d, h
    ld e, l                     ; DE = payload dest
    ld a, [wNetReq+NR_BUF]
    ld l, a
    ld a, [wNetReq+NR_BUF+1]
    ld h, a
    ld a, [wNetTcpDlen]
    ld b, a
.cpd
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .cpd
.nodata
    ld hl, wNetTx+12            ; TCP checksum: pseudo-header + segment
    ld b, 8
    ld de, 0
    call net_sum
    ld a, e
    add 6
    ld e, a
    ld a, d
    adc 0
    ld d, a
    ld a, [wNetTcpTh]
    ld b, a
    ld a, [wNetTcpDlen]
    add b                       ; tcplen = thlen + dlen
    add e
    ld e, a
    ld a, d
    adc 0
    ld d, a
    ld a, [wNetTcpTh]
    ld b, a
    ld a, [wNetTcpDlen]
    add b
    ld b, a                     ; B = tcplen
    ld hl, wNetTx+20
    call net_cksum
    ld a, h
    ld [wNetTx+36], a
    ld a, l
    ld [wNetTx+37], a
    ld hl, wNetTx
    ld b, 20
    ld de, 0
    call net_cksum
    ld a, h
    ld [wNetTx+10], a
    ld a, l
    ld [wNetTx+11], a
    ld a, [wNetTcpTh]
    add 20
    ld b, a
    ld a, [wNetTcpDlen]
    add b
    ld e, a
    ld a, 0
    adc 0
    ld d, a
    ld hl, wNetTx
    call net_slip_send
    ret

; sock_state_set(A = state) - store SK_STATE for the current socket
sock_state_set:
    ld b, a
    call sock_ptr_hl
    ld a, l
    add SK_STATE
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, b
    ld [hl], a
    ret

; tcp_connect - handshake for the current socket (SYN -> SYN-ACK -> ACK)
tcp_connect:
    call sock_ptr_hl            ; SK_SND = 1000
    ld a, l
    add SK_SND
    ld l, a
    ld a, h
    adc 0
    ld h, a
    xor a
    ld [hl+], a
    ld [hl+], a
    ld a, 3
    ld [hl+], a
    ld a, $E8
    ld [hl], a
    call sock_ptr_hl            ; SK_RCV = 0
    ld a, l
    add SK_RCV
    ld l, a
    ld a, h
    adc 0
    ld h, a
    xor a
    ld [hl+], a
    ld [hl+], a
    ld [hl+], a
    ld [hl], a
    call sock_ptr_hl            ; HASRX = 0
    ld a, l
    add SK_HASRX
    ld l, a
    ld a, h
    adc 0
    ld h, a
    xor a
    ld [hl], a
    ld a, TCP_SYNSENT
    call sock_state_set
    ld a, TF_SYN               ; send SYN (with MSS)
    ld [wNetTcpFlags], a
    xor a
    ld [wNetTcpDlen], a
    call tcp_send_seg
    ld a, 1
    call sk_add_snd
    xor a                      ; wait for ESTABLISHED
    ld [wNetTO], a
    ld [wNetTO+1], a
    ld [wNetTO+2], a
.wait
    call net_pump
    ld a, [wNetReq+NR_SOCK]
    call net_sock_ptr
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    call sock_ptr_hl
    ld a, l
    add SK_STATE
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    cp TCP_ESTAB
    jr z, .ok
    ld hl, wNetTO
    inc [hl]
    jr nz, .wait
    call SchedYield
    inc hl
    inc [hl]
    jr nz, .wait
    inc hl
    inc [hl]
    ld a, [hl]
    cp 250
    jr c, .wait
    ld a, $FF
    ret
.ok
    xor a
    ret

; tcp_data_send - net_send for a TCP socket (PSH|ACK + advance snd_nxt)
tcp_data_send:
    ld a, TF_PSH | TF_ACK
    ld [wNetTcpFlags], a
    ld a, [wNetReq+NR_LEN]
    ld [wNetTcpDlen], a
    call tcp_send_seg
    ld a, [wNetReq+NR_LEN]
    call sk_add_snd
    xor a
    ret

; tcp_close - net_close for a TCP socket (FIN, brief settle, free)
tcp_close:
    call sock_ptr_hl
    ld a, l
    add SK_STATE
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    cp TCP_ESTAB
    jr nz, .free                ; only FIN if we were established
    ld a, TF_FIN | TF_ACK
    ld [wNetTcpFlags], a
    xor a
    ld [wNetTcpDlen], a
    call tcp_send_seg
    ld a, 1
    call sk_add_snd
    ld a, TCP_FINWAIT
    call sock_state_set
    ; Settle: pump for the peer's FIN/ACK - but STOP as soon as it arrives.
    ; Always burning the whole budget keeps the socket in FINWAIT for ~a
    ; second, and a server that closes and re-listens (httpd) drops the next
    ; client's SYN in that window, so every request after the first paid a
    ; TCP SYN retransmit (~1s) before it was even accepted.
    ld b, 8
.settle
    ld de, 8000
.s2
    call net_pump
    call sock_ptr_hl
    ld a, l
    add SK_STATE
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    cp TCP_DONE
    jr z, .free                 ; peer closed too: nothing left to wait for
    dec de
    ld a, d
    or e
    jr nz, .s2
    dec b
    jr nz, .settle
.free
    call sock_ptr_hl
    xor a
    ld [hl], a                  ; SK_TYPE = free
    ret

; tcp_rx_fits -> CF set if this segment cannot be buffered without destroying
; data the application has not read yet. RXLEN is a single byte, so the usable
; capacity is 255 (RXBUF itself is 288) - any total that carries out of 8 bits
; does not fit. The caller then drops the segment and re-ACKs its old rcv_nxt,
; so the peer retransmits once we have drained. Dropping is correct TCP and
; cannot deadlock; silently overwriting unread bytes (what we used to do) is
; data corruption the application can never detect.
tcp_rx_fits:
    call sock_ptr_hl
    ld a, l
    add SK_RXLEN
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld c, [hl]                  ; C = bytes still unread
    ld a, [wNetTcpDlen2]
    cp 209
    jr c, .len
    ld a, 208
.len
    add c                       ; carry => unread + new > 255: no room
    ret

; tcp_buffer_data - append the current segment's payload to the socket rx slot
; (the app may still owe us a read of an earlier segment; see tcp_rx_fits).
tcp_buffer_data:
    call sock_ptr_hl
    ld a, l
    add SK_RXLEN
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    ld [wNetRxOff], a           ; append at the end of the unread bytes
    ld a, [wNetTcpDlen2]
    cp 209
    jr c, .oklen
    ld a, 208
.oklen
    ld c, a
    ld a, [wNetRxOff]
    add c
    ld [hl], a                  ; RXLEN = unread + new
    call sock_ptr_hl
    ld a, l
    add SK_HASRX
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, 1
    ld [hl], a
    call sock_ptr_hl
    ld a, l
    add SK_RXBUF
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [wNetRxOff]
    add l
    ld e, a
    ld a, 0
    adc h
    ld d, a                     ; DE = dest = &RXBUF + unread
    ld a, [wNetTcpDoff]
    ld l, a
    ld h, 0
    ld bc, wNetRxBuf
    add hl, bc                  ; HL = src
    ld a, c
    ; (C from wNetRxBuf low byte is irrelevant; use fresh length)
    ld a, [wNetTcpDlen2]
    cp 209
    jr c, .cplen
    ld a, 208
.cplen
    ld c, a
    or a
    ret z
.cp
    ld a, [hl+]
    ld [de], a
    inc de
    dec c
    jr nz, .cp
    ret

; tcp_in - the receive state machine for the matching TCP socket
tcp_in:
    ld a, [wNetIhl]
    add 2
    ld e, a
    ld d, 0
    ld hl, wNetRxBuf
    add hl, de
    ld a, [hl+]
    ld [wNetUdpPort], a
    ld a, [hl]
    ld [wNetUdpPort+1], a
    call net_find_tcp
    ret c
    ld a, l
    ld [wNetSockPtr], a
    ld a, h
    ld [wNetSockPtr+1], a
    ld a, [wNetIhl]             ; incoming flags
    add 13
    ld e, a
    ld d, 0
    ld hl, wNetRxBuf
    add hl, de
    ld a, [hl]
    ld [wNetTcpIn], a
    call sock_ptr_hl           ; current state
    ld a, l
    add SK_STATE
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    cp TCP_SYNSENT
    jr z, .synsent
    cp TCP_LISTEN
    jp z, .listen
    cp TCP_SYNRCVD
    jp z, .synrcvd
    cp TCP_ESTAB
    jp z, .estab
    cp TCP_FINWAIT
    jp z, .estab                ; still ACK data/FIN while closing
    ret
.synsent
    ld a, [wNetTcpIn]
    and TF_SYN
    ret z
    ld a, 1                     ; rcv_nxt = their_seq + 1
    call sk_set_rcv_from_seq
    ld a, TF_ACK
    ld [wNetTcpFlags], a
    xor a
    ld [wNetTcpDlen], a
    call tcp_send_seg
    ld a, TCP_ESTAB
    call sock_state_set
    ret
.listen
    ; A SYN arriving at a listening socket: learn the peer from the packet,
    ; answer SYN+ACK. Reached again if the peer retransmits its SYN (our
    ; SYN+ACK was lost), which is why SND is re-seeded here rather than
    ; advanced - the reply must always carry the same ISN.
    ld a, [wNetTcpIn]
    and TF_SYN
    ret z                       ; nothing else opens a connection
    call sock_ptr_hl            ; peer IP <- the IP header's source address
    ld a, l
    add SK_RIP
    ld e, a
    ld a, h
    adc 0
    ld d, a
    ld hl, wNetRxBuf + 12
    ld b, 4
.cpip
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .cpip
    call sock_ptr_hl            ; peer port <- the TCP header's source port
    ld a, l
    add SK_RPORT
    ld e, a
    ld a, h
    adc 0
    ld d, a
    ld a, [wNetIhl]
    ld l, a
    ld h, 0
    ld bc, wNetRxBuf
    add hl, bc
    ld a, [hl+]
    ld [de], a
    inc de
    ld a, [hl]
    ld [de], a
    call sock_ptr_hl            ; our ISN = 2000 (big-endian, like tcp_connect)
    ld a, l
    add SK_SND
    ld l, a
    ld a, h
    adc 0
    ld h, a
    xor a
    ld [hl+], a
    ld [hl+], a
    ld a, $07
    ld [hl+], a
    ld a, $D0
    ld [hl], a
    ld a, 1                     ; rcv_nxt = their_seq + 1
    call sk_set_rcv_from_seq
    ld a, TF_SYN | TF_ACK
    ld [wNetTcpFlags], a
    xor a
    ld [wNetTcpDlen], a
    call tcp_send_seg
    ld a, 1                     ; the SYN we just sent consumes a sequence
    call sk_add_snd
    ld a, TCP_SYNRCVD
    call sock_state_set
    ret
.synrcvd
    ld a, [wNetTcpIn]
    and TF_SYN
    jr z, .sr_ack
    call tcp_peer_is_current
    jr z, .listen               ; our peer resent its SYN: redo the SYN+ACK
    ret                         ; a *different* client knocking while we are
                                ; mid-handshake: drop it. It retransmits, and
                                ; we take it once we are listening again -
                                ; treating it as a retransmission instead
                                ; hands this socket to the newcomer and leaves
                                ; the first client waiting for a reply that
                                ; can never come.
.sr_ack
    ld a, [wNetTcpIn]
    and TF_ACK
    ret z
    ld a, TCP_ESTAB
    call sock_state_set
    ; fall through: the handshake's ACK may already carry the request
.estab
    ; data offset (frame-relative) = ihl + (tcp[12]>>4)*4
    ld a, [wNetIhl]
    add 12
    ld e, a
    ld d, 0
    ld hl, wNetRxBuf
    add hl, de
    ld a, [hl]
    and $F0
    swap a
    add a, a
    add a, a                    ; tcphdrlen
    ld c, a
    ld a, [wNetIhl]
    add c
    ld [wNetTcpDoff], a
    ld a, [wNetRxLen]           ; datalen = rxlen - dataoff
    ld b, a
    ld a, [wNetTcpDoff]
    ld c, a
    ld a, b
    sub c
    ld [wNetTcpDlen2], a
    ; Decide in-order-ness ONCE, here, before rcv_nxt moves: the FIN check
    ; below needs the answer too, and by then rcv_nxt has advanced past this
    ; segment's seq so re-testing would always say "out of order".
    call sk_seq_in_order
    ld a, 0
    jr nz, .oo
    inc a
.oo
    ld [wNetTcpInOrd], a
    ld a, [wNetTcpDlen2]
    or a
    jr z, .checkfin
    ; Only accept data that starts exactly at rcv_nxt. A dup/out-of-order
    ; segment is dropped, but re-ACKed with our current rcv_nxt so the peer
    ; converges instead of retransmitting forever.
    ld a, [wNetTcpInOrd]
    or a
    jr z, .reack
    call tcp_rx_fits
    jr c, .reack                ; no room for it yet: make the peer resend
    call tcp_buffer_data
    ld a, [wNetTcpDlen2]
    call sk_add_rcv
    ld a, TF_ACK
    ld [wNetTcpFlags], a
    xor a
    ld [wNetTcpDlen], a
    call tcp_send_seg
.checkfin
    ld a, [wNetTcpIn]
    and TF_FIN
    ret z
    ; A FIN that sits past a gap is NOT end-of-stream: accepting it here (we
    ; used to, unconditionally) marks the socket DONE and recv reports EOF,
    ; silently truncating the transfer at the hole. Re-ACK instead, so the
    ; peer retransmits what we missed and the real FIN arrives in order.
    ld a, [wNetTcpInOrd]
    or a
    jr z, .reack
    ld a, 1
    call sk_add_rcv
    ld a, TF_ACK
    ld [wNetTcpFlags], a
    xor a
    ld [wNetTcpDlen], a
    call tcp_send_seg
    ld a, TCP_DONE
    call sock_state_set
    ret
.reack
    ld a, TF_ACK                ; dup segment: repeat our ACK, take no data
    ld [wNetTcpFlags], a
    xor a
    ld [wNetTcpDlen], a
    call tcp_send_seg
    ret