aboutsummaryrefslogtreecommitdiffstats
path: root/c/netd.c
diff options
context:
space:
mode:
Diffstat (limited to 'c/netd.c')
-rw-r--r--c/netd.c47
1 files changed, 47 insertions, 0 deletions
diff --git a/c/netd.c b/c/netd.c
new file mode 100644
index 0000000..36435d4
--- /dev/null
+++ b/c/netd.c
@@ -0,0 +1,47 @@
+#include "netlib.h"
+/* netd - a minimal IP stack over SLIP. Milestone A: answer ICMP echo (ping).
+ Our address is 10.0.0.2; the SLIP peer (gateway) is 10.0.0.1.
+
+ Everything is done on raw byte arrays so endianness is explicit (network
+ byte order = big-endian): field[hi], field[lo]. */
+
+/* Internet checksum (RFC 1071): 16-bit one's-complement sum with carry fold. */
+static unsigned int cksum(unsigned char *d, unsigned char len) {
+ unsigned int sum = 0, w;
+ unsigned char i = 0;
+ while ((unsigned char)(i + 1) < len) {
+ w = ((unsigned int)d[i] << 8) | d[i + 1];
+ sum += w; if (sum < w) sum++;
+ i += 2;
+ }
+ if (len & 1) { w = (unsigned int)d[len - 1] << 8; sum += w; if (sum < w) sum++; }
+ return ~sum;
+}
+
+void main(void) {
+ unsigned char pkt[128];
+ unsigned char len, ihl, i, t;
+ unsigned int c;
+ puts("netd: IP/ICMP up (10.0.0.2)"); nl();
+ for (;;) {
+ len = slip_recv((char *)pkt, 127);
+ if (len < 28) continue; /* IP(20) + ICMP(8) minimum */
+ if ((pkt[0] >> 4) != 4) continue; /* IPv4 only */
+ ihl = (pkt[0] & 0x0f) << 2;
+ if (pkt[9] != 1) continue; /* protocol 1 = ICMP */
+ if (pkt[ihl] != 8) continue; /* ICMP type 8 = echo request */
+
+ /* turn the request into a reply, in place */
+ for (i = 0; i < 4; i++) { t = pkt[12 + i]; pkt[12 + i] = pkt[16 + i]; pkt[16 + i] = t; }
+ pkt[8] = 64; /* reset TTL */
+ pkt[ihl] = 0; /* ICMP type -> echo reply */
+ pkt[ihl + 2] = 0; pkt[ihl + 3] = 0; /* recompute ICMP checksum */
+ c = cksum(pkt + ihl, (unsigned char)(len - ihl));
+ pkt[ihl + 2] = (unsigned char)(c >> 8); pkt[ihl + 3] = (unsigned char)c;
+ pkt[10] = 0; pkt[11] = 0; /* recompute IP header checksum */
+ c = cksum(pkt, ihl);
+ pkt[10] = (unsigned char)(c >> 8); pkt[11] = (unsigned char)c;
+
+ slip_send((char *)pkt, len);
+ }
+}