mail archive of the barebox mailing list
 help / color / mirror / Atom feed
* [RFC PATCH 1/5] net: Add a function to retrieve UDP connection
@ 2022-08-09 13:20 Jules Maselbas
  2022-08-09 13:20 ` [RFC PATCH 2/5] net: Implement source port randomization Jules Maselbas
                   ` (3 more replies)
  0 siblings, 4 replies; 7+ messages in thread
From: Jules Maselbas @ 2022-08-09 13:20 UTC (permalink / raw)
  To: barebox; +Cc: Jules Maselbas

Add a function that search for a UDP connection based on it's source
port. This function can be easily extended to do the same for TCP.

Signed-off-by: Jules Maselbas <jmaselbas@kalray.eu>
---
 net/net.c | 29 ++++++++++++++++++++---------
 1 file changed, 20 insertions(+), 9 deletions(-)

diff --git a/net/net.c b/net/net.c
index eae45e1843..c01bf49b92 100644
--- a/net/net.c
+++ b/net/net.c
@@ -36,6 +36,22 @@ IPaddr_t net_gateway;
 static IPaddr_t net_nameserver;
 static char *net_domainname;
 
+static LIST_HEAD(connection_list);
+
+static struct net_connection *net_ip_get_con(int proto, uint16_t port)
+{
+	struct net_connection *con;
+
+	list_for_each_entry(con, &connection_list, list) {
+		if (con->proto != proto)
+			continue;
+		if (con->proto == IPPROTO_UDP && ntohs(con->udp->uh_sport) == port)
+			return con;
+	}
+
+	return NULL;
+}
+
 void net_set_nameserver(IPaddr_t nameserver)
 {
 	net_nameserver = nameserver;
@@ -358,8 +374,6 @@ IPaddr_t net_get_gateway(void)
 	return net_gateway;
 }
 
-static LIST_HEAD(connection_list);
-
 static struct net_connection *net_new(struct eth_device *edev, IPaddr_t dest,
 				      rx_handler_f *handler, void *ctx)
 {
@@ -587,15 +601,12 @@ static int net_handle_udp(unsigned char *pkt, int len)
 	struct iphdr *ip = (struct iphdr *)(pkt + ETHER_HDR_SIZE);
 	struct net_connection *con;
 	struct udphdr *udp;
-	int port;
 
 	udp = (struct udphdr *)(ip + 1);
-	port = ntohs(udp->uh_dport);
-	list_for_each_entry(con, &connection_list, list) {
-		if (con->proto == IPPROTO_UDP && port == ntohs(con->udp->uh_sport)) {
-			con->handler(con->priv, pkt, len);
-			return 0;
-		}
+	con = net_ip_get_con(IPPROTO_UDP, ntohs(udp->uh_dport));
+	if (con) {
+		con->handler(con->priv, pkt, len);
+		return 0;
 	}
 	return -EINVAL;
 }
-- 
2.17.1




^ permalink raw reply	[flat|nested] 7+ messages in thread

* [RFC PATCH 2/5] net: Implement source port randomization
  2022-08-09 13:20 [RFC PATCH 1/5] net: Add a function to retrieve UDP connection Jules Maselbas
@ 2022-08-09 13:20 ` Jules Maselbas
  2022-08-09 13:20 ` [RFC PATCH 3/5] net: Add simple TCP support Jules Maselbas
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 7+ messages in thread
From: Jules Maselbas @ 2022-08-09 13:20 UTC (permalink / raw)
  To: barebox; +Cc: Jules Maselbas

The source port can now be randomized for UDP connections in the range
32768 to 65535. The port number selection follows the Algorithm 1 as
described by the RFC6056, and goes as follow: A random port number is
generated, if the port is already taken then it search forward for the
next available port.

Note from the RFC6056:
      random() is a function that returns a 32-bit pseudo-random
      unsigned integer number.  Note that the output needs to be
      unpredictable, and typical implementations of POSIX random()
      function do not necessarily meet this requirement.  See [RFC4086]
      for randomness requirements for security.

This implementation uses random32 which might not meet the randomness
requirements. The random32 call can be easily replaced by a better
suited pseudo-random number generator when availabe.

Signed-off-by: Jules Maselbas <jmaselbas@kalray.eu>
---
 net/net.c | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)

diff --git a/net/net.c b/net/net.c
index c01bf49b92..9f799f252d 100644
--- a/net/net.c
+++ b/net/net.c
@@ -310,18 +310,31 @@ static int init_net_poll(void)
 }
 device_initcall(init_net_poll);
 
-static uint16_t net_udp_new_localport(void)
+static uint16_t net_new_localport(int proto)
 {
-	static uint16_t localport;
+	const uint16_t min_port = 32768;
+	const uint16_t max_port = 65535;
+	const uint16_t num_port = max_port - min_port + 1;
+	uint16_t localport;
 
-	localport++;
+	/* port randomization with the Algorithm 1 as defined in RFC6056 */
+	localport = min_port + random32() % num_port;
 
-	if (localport < 1024)
-		localport = 1024;
+	while (net_ip_get_con(proto, localport) != NULL) {
+		if (localport == max_port)
+			localport = min_port;
+		else
+			localport++;
+	}
 
 	return localport;
 }
 
+static uint16_t net_udp_new_localport(void)
+{
+	return net_new_localport(IPPROTO_UDP);
+}
+
 IPaddr_t net_get_serverip(void)
 {
 	IPaddr_t ip;
-- 
2.17.1




^ permalink raw reply	[flat|nested] 7+ messages in thread

* [RFC PATCH 3/5] net: Add simple TCP support
  2022-08-09 13:20 [RFC PATCH 1/5] net: Add a function to retrieve UDP connection Jules Maselbas
  2022-08-09 13:20 ` [RFC PATCH 2/5] net: Implement source port randomization Jules Maselbas
@ 2022-08-09 13:20 ` Jules Maselbas
  2022-08-12  7:04   ` Sascha Hauer
  2022-08-09 13:20 ` [RFC PATCH 4/5] Add irc command Jules Maselbas
  2022-08-09 13:20 ` [RFC PATCH 5/5] Add tcpdump command Jules Maselbas
  3 siblings, 1 reply; 7+ messages in thread
From: Jules Maselbas @ 2022-08-09 13:20 UTC (permalink / raw)
  To: barebox; +Cc: Jules Maselbas

This is a very simple TCP implementation that only support connecting
to servers (passive open and listen are not supported).

This also doesn't handle multiples segments and the TCP window size is
smaller than the MTU, this will hopefully make the sender only send one
segment at a time.

Signed-off-by: Jules Maselbas <jmaselbas@kalray.eu>
---
 common/misc.c |  12 +-
 include/net.h | 118 +++++++++++++++
 net/net.c     | 406 ++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 531 insertions(+), 5 deletions(-)

diff --git a/common/misc.c b/common/misc.c
index 0f6de3e9e5..30e94f5a8b 100644
--- a/common/misc.c
+++ b/common/misc.c
@@ -57,6 +57,13 @@ const char *strerror(int errnum)
 	case	EPROBE_DEFER	: str = "Requested probe deferral"; break;
 	case	ELOOP		: str = "Too many symbolic links encountered"; break;
 	case	ENODATA		: str = "No data available"; break;
+#ifdef CONFIG_NET
+	case	ENETRESET	: str = "Network dropped connection because of reset"; break;
+	case	ECONNABORTED	: str = "Software caused connection abort"; break;
+	case	ECONNRESET	: str = "Connection reset by peer"; break;
+	case	ENOBUFS		: str = "No buffer space available"; break;
+	case	ECONNREFUSED	: str = "Connection refused"; break;
+#endif
 #if 0 /* These are probably not needed */
 	case	ENOTBLK		: str = "Block device required"; break;
 	case	EFBIG		: str = "File too large"; break;
@@ -79,11 +86,6 @@ const char *strerror(int errnum)
 	case	EAFNOSUPPORT	: str = "Address family not supported by protocol"; break;
 	case	EADDRINUSE	: str = "Address already in use"; break;
 	case	EADDRNOTAVAIL	: str = "Cannot assign requested address"; break;
-	case	ENETRESET	: str = "Network dropped connection because of reset"; break;
-	case	ECONNABORTED	: str = "Software caused connection abort"; break;
-	case	ECONNRESET	: str = "Connection reset by peer"; break;
-	case	ENOBUFS		: str = "No buffer space available"; break;
-	case	ECONNREFUSED	: str = "Connection refused"; break;
 	case	EHOSTDOWN	: str = "Host is down"; break;
 	case	EALREADY	: str = "Operation already in progress"; break;
 	case	EINPROGRESS	: str = "Operation now in progress"; break;
diff --git a/include/net.h b/include/net.h
index b50b6e76c8..76b64ccb21 100644
--- a/include/net.h
+++ b/include/net.h
@@ -143,6 +143,7 @@ struct ethernet {
 #define PROT_VLAN	0x8100		/* IEEE 802.1q protocol		*/
 
 #define IPPROTO_ICMP	 1	/* Internet Control Message Protocol	*/
+#define IPPROTO_TCP	 6	/* Transmission Control Protocol	*/
 #define IPPROTO_UDP	17	/* User Datagram Protocol		*/
 
 #define IP_BROADCAST    0xffffffff /* Broadcast IP aka 255.255.255.255 */
@@ -171,6 +172,67 @@ struct udphdr {
 	uint16_t	uh_sum;		/* udp checksum */
 } __attribute__ ((packed));
 
+/* pseudo header for checksum */
+struct psdhdr {
+	uint32_t	saddr;
+	uint32_t	daddr;
+	uint16_t	proto;
+	uint16_t	ttlen;
+} __attribute__ ((packed));
+
+struct tcphdr {
+	uint16_t	src;	/* source port */
+	uint16_t	dst;	/* destination port */
+	uint32_t	seq;	/* sequence number */
+	uint32_t	ack;	/* acknowledge number */
+	uint16_t 	doff_flag;	/* data offset and flags */
+#define TCP_DOFF_MASK	0xf
+#define TCP_DOFF_SHIFT	12
+#define TCP_FLAG_FIN	BIT(0)
+#define TCP_FLAG_SYN	BIT(1)
+#define TCP_FLAG_RST	BIT(2)
+#define TCP_FLAG_PSH	BIT(3)
+#define TCP_FLAG_ACK	BIT(4)
+#define TCP_FLAG_URG	BIT(5)
+#define TCP_FLAG_ECE	BIT(6)
+#define TCP_FLAG_CWR	BIT(7)
+#define TCP_FLAG_NS	BIT(8)
+#define TCP_FLAG_MASK	0x1ff
+	uint16_t	wnd;	/* window size */
+	uint16_t	sum;	/* header and data checksum */
+	uint16_t	urp;	/* urgent pointer (if URG is set) */
+	/* The options start here. */
+} __attribute__ ((packed));
+
+enum tcp_state {
+	TCP_CLOSED = 0,
+	TCP_LISTEN,
+	TCP_SYN_SENT,
+	TCP_SYN_RECV,
+	TCP_ESTABLISHED,
+	TCP_FIN_WAIT1,
+	TCP_FIN_WAIT2,
+	TCP_TIME_WAIT,
+	TCP_CLOSE_WAIT,
+	TCP_LAST_ACK,
+	TCP_CLOSING,
+};
+
+/* Transmission Control Block */
+struct tcb {
+	uint32_t snd_una;
+	uint32_t snd_nxt;
+	uint32_t snd_wnd;
+	uint16_t snd_urp;
+	uint32_t snd_wl1;
+	uint32_t snd_wl2;
+	uint32_t rcv_nxt;
+	uint32_t rcv_wnd;
+	uint16_t rcv_urp;
+	uint32_t iss;
+	uint32_t irs;
+};
+
 /*
  *	Address Resolution Protocol (ARP) header.
  */
@@ -264,6 +326,13 @@ struct eth_device *net_route(IPaddr_t ip);
 /* Do the work */
 void net_poll(void);
 
+static inline size_t net_tcp_data_offset(struct tcphdr *tcp)
+{
+	uint16_t doff;
+	doff = ntohs(tcp->doff_flag) >> TCP_DOFF_SHIFT;
+	return doff * sizeof(uint32_t);
+}
+
 static inline struct iphdr *net_eth_to_iphdr(char *pkt)
 {
 	return (struct iphdr *)(pkt + ETHER_HDR_SIZE);
@@ -274,6 +343,11 @@ static inline struct udphdr *net_eth_to_udphdr(char *pkt)
 	return (struct udphdr *)(net_eth_to_iphdr(pkt) + 1);
 }
 
+static inline struct tcphdr *net_eth_to_tcphdr(char *pkt)
+{
+	return (struct tcphdr *)(net_eth_to_iphdr(pkt) + 1);
+}
+
 static inline struct icmphdr *net_eth_to_icmphdr(char *pkt)
 {
 	return (struct icmphdr *)(net_eth_to_iphdr(pkt) + 1);
@@ -295,8 +369,28 @@ static inline int net_eth_to_udplen(char *pkt)
 	return ntohs(udp->uh_ulen) - 8;
 }
 
+static inline char *net_eth_to_tcp_payload(char *pkt)
+{
+	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
+	return ((char *)tcp) + net_tcp_data_offset(tcp);
+}
+
+static inline int net_eth_to_iplen(char *pkt)
+{
+	struct iphdr *ip = net_eth_to_iphdr(pkt);
+	return ntohs(ip->tot_len) - sizeof(struct iphdr);
+}
+
+static inline int net_eth_to_tcplen(char *pkt)
+{
+	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
+	return net_eth_to_iplen(pkt) - net_tcp_data_offset(tcp);
+}
+
 int net_checksum_ok(unsigned char *, int);	/* Return true if cksum OK	*/
 uint16_t net_checksum(unsigned char *, int);	/* Calculate the checksum	*/
+int tcp_checksum_ok(struct iphdr *ip, struct tcphdr *tcp, int len);
+uint16_t tcp_checksum(struct iphdr *ip, struct tcphdr *tcp, int len);
 
 /*
  * The following functions are a bit ugly, but necessary to deal with
@@ -459,12 +553,18 @@ struct net_connection {
 	struct ethernet *et;
 	struct iphdr *ip;
 	struct udphdr *udp;
+	struct tcphdr *tcp;
 	struct eth_device *edev;
 	struct icmphdr *icmp;
 	unsigned char *packet;
 	struct list_head list;
 	rx_handler_f *handler;
 	int proto;
+	int state;
+	int ret;
+	union {
+		struct tcb tcb;
+	};
 	void *priv;
 };
 
@@ -480,6 +580,13 @@ struct net_connection *net_udp_eth_new(struct eth_device *edev, IPaddr_t dest,
                                        uint16_t dport, rx_handler_f *handler,
                                        void *ctx);
 
+struct net_connection *net_tcp_new(IPaddr_t dest, uint16_t dport,
+		rx_handler_f *handler, void *ctx);
+
+struct net_connection *net_tcp_eth_new(struct eth_device *edev, IPaddr_t dest,
+                                       uint16_t dport, rx_handler_f *handler,
+                                       void *ctx);
+
 struct net_connection *net_icmp_new(IPaddr_t dest, rx_handler_f *handler,
 		void *ctx);
 
@@ -497,6 +604,17 @@ static inline void *net_udp_get_payload(struct net_connection *con)
 		sizeof(struct udphdr);
 }
 
+static inline void *net_tcp_get_payload(struct net_connection *con)
+{
+	return con->packet + sizeof(struct ethernet) + sizeof(struct iphdr) +
+		net_tcp_data_offset(con->tcp);
+}
+
+int net_tcp_listen(struct net_connection *con);
+int net_tcp_open(struct net_connection *con);
+int net_tcp_send(struct net_connection *con, int len);
+int net_tcp_close(struct net_connection *con);
+
 int net_udp_send(struct net_connection *con, int len);
 int net_icmp_send(struct net_connection *con, int len);
 
diff --git a/net/net.c b/net/net.c
index 9f799f252d..855bb8e4c2 100644
--- a/net/net.c
+++ b/net/net.c
@@ -47,6 +47,8 @@ static struct net_connection *net_ip_get_con(int proto, uint16_t port)
 			continue;
 		if (con->proto == IPPROTO_UDP && ntohs(con->udp->uh_sport) == port)
 			return con;
+		if (con->proto == IPPROTO_TCP && ntohs(con->tcp->src) == port)
+			return con;
 	}
 
 	return NULL;
@@ -99,6 +101,31 @@ uint16_t net_checksum(unsigned char *ptr, int len)
 	return xsum & 0xffff;
 }
 
+uint16_t tcp_checksum(struct iphdr *ip, struct tcphdr *tcp, int len)
+{
+	uint32_t xsum;
+	struct psdhdr pseudo;
+	size_t hdrsize = net_tcp_data_offset(tcp);
+
+	pseudo.saddr = ip->saddr;
+	pseudo.daddr = ip->daddr;
+	pseudo.proto = htons(ip->protocol);
+	pseudo.ttlen = htons(hdrsize + len);
+
+	xsum = net_checksum((void *)&pseudo, sizeof(struct psdhdr));
+	xsum += net_checksum((void *)tcp, hdrsize + len);
+
+	while (xsum > 0xffff)
+		xsum = (xsum & 0xffff) + (xsum >> 16);
+
+	return xsum;
+}
+
+int tcp_checksum_ok(struct iphdr *ip, struct tcphdr *tcp, int len)
+{
+	return tcp_checksum(ip, tcp, len) == 0xffff;
+}
+
 IPaddr_t getenv_ip(const char *name)
 {
 	IPaddr_t ip;
@@ -335,6 +362,11 @@ static uint16_t net_udp_new_localport(void)
 	return net_new_localport(IPPROTO_UDP);
 }
 
+static uint16_t net_tcp_new_localport(void)
+{
+	return net_new_localport(IPPROTO_TCP);
+}
+
 IPaddr_t net_get_serverip(void)
 {
 	IPaddr_t ip;
@@ -422,6 +454,7 @@ static struct net_connection *net_new(struct eth_device *edev, IPaddr_t dest,
 	con->et = (struct ethernet *)con->packet;
 	con->ip = (struct iphdr *)(con->packet + ETHER_HDR_SIZE);
 	con->udp = (struct udphdr *)(con->packet + ETHER_HDR_SIZE + sizeof(struct iphdr));
+	con->tcp = (struct tcphdr *)(con->packet + ETHER_HDR_SIZE + sizeof(struct iphdr));
 	con->icmp = (struct icmphdr *)(con->packet + ETHER_HDR_SIZE + sizeof(struct iphdr));
 	con->handler = handler;
 
@@ -452,6 +485,30 @@ out:
 	return ERR_PTR(ret);
 }
 
+struct net_connection *net_tcp_eth_new(struct eth_device *edev, IPaddr_t dest,
+				       uint16_t dport, rx_handler_f *handler,
+				       void *ctx)
+{
+	struct net_connection *con = net_new(edev, dest, handler, ctx);
+	uint16_t doff;
+
+	if (IS_ERR(con))
+		return con;
+
+	con->proto = IPPROTO_TCP;
+	con->state = TCP_CLOSED;
+	con->tcp->src = htons(net_tcp_new_localport());
+	con->tcp->dst = htons(dport);
+	con->tcp->seq = 0;
+	con->tcp->ack = 0;
+	doff = sizeof(struct tcphdr) / sizeof(uint32_t);
+	con->tcp->doff_flag = htons(doff << TCP_DOFF_SHIFT);
+	con->tcp->urp = 0;
+	con->ip->protocol = IPPROTO_TCP;
+
+	return con;
+}
+
 struct net_connection *net_udp_eth_new(struct eth_device *edev, IPaddr_t dest,
 				       uint16_t dport, rx_handler_f *handler,
 				       void *ctx)
@@ -475,6 +532,12 @@ struct net_connection *net_udp_new(IPaddr_t dest, uint16_t dport,
 	return net_udp_eth_new(NULL, dest, dport, handler, ctx);
 }
 
+struct net_connection *net_tcp_new(IPaddr_t dest, uint16_t dport,
+		rx_handler_f *handler, void *ctx)
+{
+	return net_tcp_eth_new(NULL, dest, dport, handler, ctx);
+}
+
 struct net_connection *net_icmp_new(IPaddr_t dest, rx_handler_f *handler,
 		void *ctx)
 {
@@ -514,6 +577,167 @@ int net_udp_send(struct net_connection *con, int len)
 	return net_ip_send(con, sizeof(struct udphdr) + len);
 }
 
+static int tcp_send(struct net_connection *con, int len, uint16_t flags)
+{
+	size_t hdr_size = net_tcp_data_offset(con->tcp);
+
+	con->tcp->doff_flag &= ~htons(TCP_FLAG_MASK);
+	con->tcp->doff_flag |= htons(flags);
+	con->tcp->sum = 0;
+	con->tcp->sum = ~tcp_checksum(con->ip, con->tcp, len);
+
+	return net_ip_send(con, hdr_size + len);
+}
+
+int net_tcp_send(struct net_connection *con, int len)
+{
+	struct tcb *tcb = &con->tcb;
+	uint16_t flag = 0;
+
+	if (con->proto != IPPROTO_TCP)
+		return -EPROTOTYPE;
+	switch (con->state) {
+	case TCP_CLOSED:
+		return -ENOTCONN;
+	case TCP_LISTEN:
+		/* TODO: proceed as open */
+		break;
+	case TCP_SYN_SENT:
+	case TCP_SYN_RECV:
+		/* queue request or "error:  insufficient resources". */
+		break;
+	case TCP_ESTABLISHED:
+	case TCP_CLOSE_WAIT:
+		/* proceed */
+		break;
+	case TCP_FIN_WAIT1:
+	case TCP_FIN_WAIT2:
+	case TCP_TIME_WAIT:
+	case TCP_LAST_ACK:
+	case TCP_CLOSING:
+		return -ESHUTDOWN;
+	}
+
+	con->tcp->seq = htonl(tcb->snd_nxt);
+	tcb->snd_nxt += len;
+	flag |= TCP_FLAG_PSH;
+	if (1 || ntohl(con->tcp->ack) < con->tcb.rcv_nxt) {
+		flag |= TCP_FLAG_ACK;
+		con->tcp->ack = htonl(con->tcb.rcv_nxt);
+	} else {
+		con->tcp->ack = 0;
+	}
+
+	return tcp_send(con, len, flag);
+}
+
+int net_tcp_listen(struct net_connection *con)
+{
+	if (con->proto != IPPROTO_TCP)
+		return -EPROTOTYPE;
+
+	con->state = TCP_LISTEN;
+	return -1;
+}
+
+int net_tcp_open(struct net_connection *con)
+{
+	struct tcphdr *tcp = net_eth_to_tcphdr(con->packet);
+	struct tcb *tcb = &con->tcb;
+	int ret;
+
+	if (con->proto != IPPROTO_TCP)
+		return -EPROTOTYPE;
+	switch (con->state) {
+	case TCP_CLOSED:
+	case TCP_LISTEN:
+		break;
+	case TCP_SYN_SENT:
+	case TCP_SYN_RECV:
+	case TCP_ESTABLISHED:
+	case TCP_FIN_WAIT1:
+	case TCP_FIN_WAIT2:
+	case TCP_TIME_WAIT:
+	case TCP_CLOSE_WAIT:
+	case TCP_LAST_ACK:
+	case TCP_CLOSING:
+		return -EISCONN;
+	}
+
+	/* use a window smaller than the MTU, as only one tcp segment packet
+	 * can be received at time */
+	tcb->rcv_wnd = 1024;
+	tcb->snd_wnd = 0;
+	tcb->iss = random32() + (get_time_ns() >> 10);
+	con->state = TCP_SYN_SENT;
+
+	tcp->wnd = htons(tcb->rcv_wnd);
+	tcp->seq = htonl(tcb->iss);
+	tcb->snd_una = tcb->iss;
+	tcb->snd_nxt = tcb->iss + 1;
+	ret = tcp_send(con, 0, TCP_FLAG_SYN);
+	if (ret)
+		return ret;
+
+	ret = wait_on_timeout(6000 * MSECOND, con->state == TCP_ESTABLISHED);
+	if (ret)
+		return -ETIMEDOUT;
+
+	return con->ret; // TODO: return 0 ?
+}
+
+int net_tcp_close(struct net_connection *con)
+{
+	struct tcphdr *tcp = net_eth_to_tcphdr(con->packet);
+	struct tcb *tcb = &con->tcb;
+	int ret;
+
+	if (con->proto != IPPROTO_TCP)
+		return -EPROTOTYPE;
+	switch (con->state) {
+	case TCP_CLOSED:
+		return -ENOTCONN;
+	case TCP_LISTEN:
+	case TCP_SYN_SENT:
+		con->state = TCP_CLOSED;
+		return 0;
+		break;
+	case TCP_SYN_RECV:
+	case TCP_ESTABLISHED:
+		/* wait for pending send */
+		con->state = TCP_FIN_WAIT1;
+		break;
+	case TCP_FIN_WAIT1:
+	case TCP_FIN_WAIT2:
+		/* error: connection closing */
+		return -1;
+	case TCP_TIME_WAIT:
+	case TCP_LAST_ACK:
+	case TCP_CLOSING:
+		/* error: connection closing */
+		return -1;
+	case TCP_CLOSE_WAIT:
+		/* queue close request after pending sends */
+		con->state = TCP_LAST_ACK;
+		break;
+	}
+
+	tcp->seq = htonl(tcb->snd_nxt);
+	tcp->ack = htonl(tcb->rcv_nxt);
+	tcb->snd_nxt += 1;
+	ret = tcp_send(con, 0, TCP_FLAG_FIN | TCP_FLAG_ACK);
+	if (ret)
+		return ret;
+
+	ret = wait_on_timeout(1000 * MSECOND, con->state == TCP_CLOSED);
+	if (ret)
+		return -ETIMEDOUT;
+
+	net_unregister(con);
+
+	return con->ret; // TODO: return 0 ?
+}
+
 int net_icmp_send(struct net_connection *con, int len)
 {
 	con->icmp->checksum = ~net_checksum((unsigned char *)con->icmp,
@@ -624,6 +848,186 @@ static int net_handle_udp(unsigned char *pkt, int len)
 	return -EINVAL;
 }
 
+static int net_handle_tcp(unsigned char *pkt, int len)
+{
+	size_t min_size = ETHER_HDR_SIZE + sizeof(struct iphdr);
+	struct net_connection *con;
+	struct iphdr *ip = net_eth_to_iphdr(pkt);
+	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
+	struct tcb *tcb;
+	uint16_t flag;
+	uint16_t doff;
+	uint32_t tcp_len;
+	uint32_t seg_len;
+	uint32_t seg_ack;
+	uint32_t seg_seq;
+	uint32_t seg_last;
+	uint32_t rcv_wnd;
+	uint32_t rcv_nxt;
+	int seg_accept = 0;
+
+	if (len < (min_size + sizeof(struct tcphdr)))
+		goto bad;
+	flag = ntohs(tcp->doff_flag) & TCP_FLAG_MASK;
+	doff = net_tcp_data_offset(tcp);
+	if (doff < sizeof(struct tcphdr))
+		goto bad;
+	if (len < (min_size + doff))
+		goto bad;
+
+	seg_ack = ntohl(tcp->ack);
+	seg_seq = ntohl(tcp->seq);
+	tcp_len = net_eth_to_tcplen(pkt);
+	seg_len = tcp_len;
+	seg_len += !!(flag & TCP_FLAG_FIN);
+	seg_len += !!(flag & TCP_FLAG_SYN);
+
+	if (!tcp_checksum_ok(ip, tcp, tcp_len))
+		goto bad;
+
+	con = net_ip_get_con(IPPROTO_TCP, ntohs(tcp->dst));
+	if (con == NULL)
+		goto bad;
+	tcb = &con->tcb;
+
+	/* segment arrives */
+	seg_last = seg_seq + seg_len - 1;
+	rcv_wnd = tcb->rcv_wnd;
+	rcv_nxt = tcb->rcv_nxt;
+
+	if (seg_len == 0 && rcv_wnd == 0)
+		seg_accept = seg_seq == rcv_nxt;
+	if (seg_len == 0 && rcv_wnd > 0)
+		seg_accept = rcv_nxt <= seg_seq && seg_seq < (rcv_nxt + rcv_wnd);
+	if (seg_len > 0 && rcv_wnd == 0)
+		seg_accept = 0; /* not acceptable */
+	if (seg_len > 0 && rcv_wnd > 0)
+		seg_accept = (rcv_nxt <= seg_seq && seg_seq < (rcv_nxt + rcv_wnd))
+			|| (rcv_nxt <= seg_last && seg_last < (rcv_nxt + rcv_wnd));
+
+	switch (con->state) {
+	case TCP_CLOSED:
+		if (flag & TCP_FLAG_RST) {
+			goto drop;
+		}
+		if (flag & TCP_FLAG_ACK) {
+			con->tcp->seq = 0;
+			con->tcp->ack = htonl(seg_seq + seg_len);
+			con->ret = tcp_send(con, 0, TCP_FLAG_RST | TCP_FLAG_ACK);
+		} else  {
+			con->tcp->seq = htonl(seg_ack);
+			con->ret = tcp_send(con, 0, TCP_FLAG_RST);
+		}
+		break;
+	case TCP_LISTEN:
+		/* TODO */
+		break;
+	case TCP_SYN_SENT:
+		if (flag & TCP_FLAG_ACK) {
+			if (seg_ack <= tcb->iss || seg_ack > tcb->snd_nxt) {
+				if (flag & TCP_FLAG_RST)
+					goto drop;
+				con->tcp->seq = htonl(seg_ack);
+				return tcp_send(con, 0, TCP_FLAG_RST);
+			}
+			if (tcb->snd_una > seg_ack || seg_ack > tcb->snd_nxt)
+				goto drop; /* unacceptable */
+		}
+		if (flag & TCP_FLAG_RST) {
+			con->state = TCP_CLOSED;
+			con->ret = -ENETRESET;
+			break;
+		}
+		if ((flag & TCP_FLAG_SYN) && !(flag & TCP_FLAG_RST)) {
+			tcb->irs = seg_seq;
+			tcb->rcv_nxt = seg_seq + 1;
+			if (flag & TCP_FLAG_ACK)
+				tcb->snd_una = seg_ack;
+			if (tcb->snd_una > tcb->iss) {
+				con->state = TCP_ESTABLISHED;
+				con->tcp->seq = htonl(tcb->snd_nxt);
+				con->tcp->ack = htonl(tcb->rcv_nxt);
+				con->ret = tcp_send(con, 0, TCP_FLAG_ACK);
+			} else {
+				con->state = TCP_SYN_RECV;
+				tcb->snd_nxt = tcb->iss + 1;
+				con->tcp->seq = htonl(tcb->iss);
+				con->tcp->ack = htonl(tcb->rcv_nxt);
+				con->ret = tcp_send(con, 0, TCP_FLAG_SYN | TCP_FLAG_ACK);
+			}
+		}
+		break;
+	case TCP_SYN_RECV:
+	case TCP_ESTABLISHED:
+		if (flag & TCP_FLAG_RST) {
+			/* TODO: if passive open then return to LISTEN */
+			con->state = TCP_CLOSED;
+			con->ret = -ECONNREFUSED;
+			break;
+		}
+		if (!seg_accept) {
+			/* segment is not acceptable, send an ack unless RST bit
+			 * is set (done above) */
+			con->tcp->seq = htonl(tcb->snd_nxt);
+			con->tcp->ack = htonl(tcb->rcv_nxt);
+			con->ret = tcp_send(con, 0, TCP_FLAG_ACK);
+			goto drop;
+		}
+		if (flag & TCP_FLAG_FIN && flag & TCP_FLAG_ACK)
+			con->state = TCP_CLOSE_WAIT;
+
+		if (flag & TCP_FLAG_ACK)
+			tcb->snd_una = seg_ack;
+
+		tcb->rcv_nxt += seg_len;
+		con->tcp->seq = htonl(tcb->snd_nxt);
+		if (seg_len) {
+			con->tcp->ack = htonl(tcb->rcv_nxt);
+			con->ret = tcp_send(con, 0, TCP_FLAG_ACK |
+					    /* send FIN+ACK if FIN is set */
+					    (flag & TCP_FLAG_FIN));
+		}
+		con->handler(con->priv, pkt, len);
+		break;
+	case TCP_FIN_WAIT1:
+		if (flag & TCP_FLAG_FIN)
+			con->state = TCP_CLOSING;
+		if (flag & TCP_FLAG_ACK)
+			tcb->snd_una = seg_ack;
+		/* fall-through */
+	case TCP_FIN_WAIT2:
+		tcb->rcv_nxt += seg_len;
+		con->tcp->seq = htonl(tcb->snd_nxt);
+		if (seg_len) {
+			con->tcp->ack = htonl(tcb->rcv_nxt);
+			con->ret = tcp_send(con, 0, TCP_FLAG_ACK);
+		}
+	case TCP_CLOSE_WAIT:
+		/* all segment queues should be flushed */
+		if (flag & TCP_FLAG_RST) {
+			con->state = TCP_CLOSED;
+			con->ret = -ENETRESET;
+			break;
+		}
+		break;
+	case TCP_CLOSING:
+		con->state = TCP_TIME_WAIT;
+	case TCP_LAST_ACK:
+	case TCP_TIME_WAIT:
+		if (flag & TCP_FLAG_RST) {
+			con->state = TCP_CLOSED;
+			con->ret = 0;
+		}
+		break;
+	}
+	return con->ret;
+drop:
+	return 0;
+bad:
+	net_bad_packet(pkt, len);
+	return 0;
+}
+
 static int ping_reply(struct eth_device *edev, unsigned char *pkt, int len)
 {
 	struct ethernet *et = (struct ethernet *)pkt;
@@ -711,6 +1115,8 @@ static int net_handle_ip(struct eth_device *edev, unsigned char *pkt, int len)
 		return net_handle_icmp(edev, pkt, len);
 	case IPPROTO_UDP:
 		return net_handle_udp(pkt, len);
+	case IPPROTO_TCP:
+		return net_handle_tcp(pkt, len);
 	}
 
 	return 0;
-- 
2.17.1




^ permalink raw reply	[flat|nested] 7+ messages in thread

* [RFC PATCH 4/5] Add irc command
  2022-08-09 13:20 [RFC PATCH 1/5] net: Add a function to retrieve UDP connection Jules Maselbas
  2022-08-09 13:20 ` [RFC PATCH 2/5] net: Implement source port randomization Jules Maselbas
  2022-08-09 13:20 ` [RFC PATCH 3/5] net: Add simple TCP support Jules Maselbas
@ 2022-08-09 13:20 ` Jules Maselbas
  2022-08-09 13:20 ` [RFC PATCH 5/5] Add tcpdump command Jules Maselbas
  3 siblings, 0 replies; 7+ messages in thread
From: Jules Maselbas @ 2022-08-09 13:20 UTC (permalink / raw)
  To: barebox; +Cc: Jules Maselbas

The irc command implement an IRC client, right here in barebox.
This could be used to ask help in case a user cannot boot linux...
More realistically this is an example of using the TCP support.

Signed-off-by: Jules Maselbas <jmaselbas@kalray.eu>
---
 commands/Kconfig  |   9 +
 commands/Makefile |   1 +
 commands/irc.c    | 572 ++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 582 insertions(+)
 create mode 100644 commands/irc.c

diff --git a/commands/Kconfig b/commands/Kconfig
index 86e4714849..5faf8eccc1 100644
--- a/commands/Kconfig
+++ b/commands/Kconfig
@@ -1244,6 +1244,15 @@ config CMD_PING
 
 	  Usage: ping DESTINATION
 
+config CMD_IRC
+	tristate
+	prompt "irc"
+	default n
+	help
+	  Simple IRC client
+
+	  Usage: irc [-n] DESTINATION [PORT]
+
 config CMD_TFTP
 	depends on FS_TFTP
 	tristate
diff --git a/commands/Makefile b/commands/Makefile
index b3b7bafe6b..ecdcfe9619 100644
--- a/commands/Makefile
+++ b/commands/Makefile
@@ -67,6 +67,7 @@ obj-$(CONFIG_USB_GADGET_SERIAL)	+= usbserial.o
 obj-$(CONFIG_CMD_GPIO)		+= gpio.o
 obj-$(CONFIG_CMD_UNCOMPRESS)	+= uncompress.o
 obj-$(CONFIG_CMD_I2C)		+= i2c.o
+obj-$(CONFIG_CMD_IRC)		+= irc.o
 obj-$(CONFIG_CMD_SPI)		+= spi.o
 obj-$(CONFIG_CMD_MIPI_DBI)	+= mipi_dbi.o
 obj-$(CONFIG_CMD_UBI)		+= ubi.o
diff --git a/commands/irc.c b/commands/irc.c
new file mode 100644
index 0000000000..b2b154b1dc
--- /dev/null
+++ b/commands/irc.c
@@ -0,0 +1,572 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+// SPDX-FileCopyrightText: 2022 Jules Maselbas <jmaselbas@kalray.eu>
+
+/* irc.c - IRC client */
+
+#include <common.h>
+#include <command.h>
+#include <net.h>
+#include <errno.h>
+#include <getopt.h>
+#include <linux/err.h>
+#include <linux/string.h>
+#include <linux/ctype.h>
+#include <readkey.h>
+#include <sched.h>
+#include <crc.h>
+#include <globalvar.h>
+
+static IPaddr_t	net_ip;
+
+static struct net_connection *con;
+
+static char chan[32];
+static char nick[32];
+static char input_line[128];
+
+static int redraw;
+LIST_HEAD(irc_log);
+static int irc_log_nb_msgs;
+
+struct msg_entry {
+	struct list_head list;
+	unsigned char type;
+	unsigned char flag;
+	char *msg;
+	char *nick;
+};
+
+enum type {
+	NONE = 0,
+	INFO = 1,
+	PART,
+	QUIT,
+	JOIN,
+	PRIV,
+	EMOT,
+};
+
+enum flag {
+	SELF = 1,
+	HIGH = 2,
+};
+
+const char *nickcolor[] = {
+	"\033[0m",  /* normal */
+	"\033[31m", /* red */
+	"\033[32m", /* green */
+	"\033[33m", /* yellow */
+	"\033[34m", /* blue */
+	"\033[35m", /* purple */
+	"\033[36m", /* cyan */
+	"\033[1;31m",
+	"\033[1;32m",
+	"\033[1;33m",
+	"\033[1;34m",
+	"\033[1;35m",
+	"\033[1;36m",
+};
+
+const char *color[] = {
+	[NONE] = "",
+	[INFO] = "\033[1;34m", /* blue */
+	[PART] = "\033[1;31m", /* red */
+	[QUIT] = "\033[1;31m", /* red */
+	[JOIN] = "\033[1;32m", /* green */
+	[PRIV] = "",
+	[EMOT] = "",
+};
+
+const char *prefix[] = {
+	[NONE] = "",
+	[INFO] = "-!-",
+	[PART] = "<--",
+	[QUIT] = "<--",
+	[JOIN] = "-->",
+	[PRIV] = "",
+	[EMOT] = "",
+};
+
+static int irc_send(const char *msg, int len);
+static int irc_pong(const char *txt);
+static int irc_ctcp(const char *dst, const char *act, const char *msg);
+
+static void irc_print_msg(struct msg_entry *msg)
+{
+	const char *inv = "";
+	const char *col = "";
+	const char *off = "";
+	const char *pre = prefix[msg->type];
+	uint32_t crc;
+
+	if (console_allow_color()) {
+		col = color[msg->type];
+		off = "\033[0m";
+
+		if (msg->type == PRIV || msg->type == EMOT) {
+			crc = crc32(0, msg->nick, strlen(msg->nick));
+			if (msg->flag & SELF)
+				col = "\033[1m";
+			else
+				col = nickcolor[crc % ARRAY_SIZE(nickcolor)];
+		}
+
+		if (msg->flag & HIGH)
+			inv = "\033[7m";
+	}
+
+	if (msg->type == PRIV)
+		printf("<%s%s%s%s> %s\n", inv, col, msg->nick, off, msg->msg);
+	else if (msg->type == EMOT)
+		printf(" * %s%s%s%s %s\n", inv, col, msg->nick, off, msg->msg);
+	else
+		printf("%s%s%s %s\n", col, pre, off, msg->msg);
+}
+
+static void irc_add_line(enum type type, enum flag flag, char *name, char *line)
+{
+	struct msg_entry *msg;
+
+	msg = malloc(sizeof(*msg));
+	if (!msg)
+		return;
+	msg->msg = line;
+	msg->type = type;
+	msg->flag = flag;
+	msg->nick = basprintf("%s", name ? name : "");
+
+	if (!(flag & SELF)) {
+		if (strstr(line, nick) != NULL)
+			msg->flag |= HIGH;
+	}
+
+	list_add_tail(&msg->list, &irc_log);
+	irc_log_nb_msgs++;
+	printf("\r\x1b[K");
+	irc_print_msg(msg);
+	printf("\r[%s] %s\x1b[K", nick, input_line);
+}
+
+static void irc_draw(void)
+{
+	struct msg_entry *msg;
+
+	clear();
+	printf("\r\x1b[K");
+	list_for_each_entry(msg, &irc_log, list) {
+		irc_print_msg(msg);
+	}
+	printf("\r[%s] %s\x1b[K", nick, input_line);
+}
+
+static void irc_recv(char *msg)
+{
+	char *nick = NULL, *host = NULL;
+	char *cmd = NULL, *chan = NULL, *arg = NULL;
+	char *text = NULL;
+	char **argp[] = { &cmd, &chan, &arg };
+	int argc = 0;
+	char *p = NULL, *l = NULL;
+	char t = NONE;
+
+	/* :<nick>!<user>@<host> */
+	if (msg[0] == ':') {
+		nick = ++msg;
+		if (!(p = strchr(msg, ' ')))
+			return;
+		*p = '\0';
+		msg = skip_spaces(p + 1);
+		if ((p = strchr(nick, '!'))) {
+			*p = '\0';
+			host = ++p;
+		}
+	}
+
+	if ((p = strchr(msg, ':'))) {
+		*p = '\0';
+		text = ++p;
+		if ((p = strchr(text, '\r')))
+			*p = '\0';
+	}
+
+	/* <cmd> [<chan> [<arg> ]]\0 */
+	while (argc < (ARRAY_SIZE(argp) - 1) && (p = strchr(msg, ' '))) {
+		*p = '\0';
+		*argp[argc++] = msg;
+		msg = ++p;
+	}
+	if (argc == (ARRAY_SIZE(argp) - 1))
+		*argp[argc] = msg;
+
+	if (!cmd || !strcmp("PONG", cmd)) {
+		return;
+	} else if (!strcmp("PING", cmd)) {
+		irc_pong(text);
+		return;
+	} else if (!nick || !host) {
+		t = INFO;
+		l = basprintf("%s%s", arg ? arg : "", text ? text : "");
+	} else if (!strcmp("ERROR", cmd)) {
+		t = INFO;
+		l = basprintf("error %s", text ? text : "unknown");
+	} else if (!strcmp("JOIN", cmd) && (chan || text)) {
+		if (text)
+			chan = text;
+		t = JOIN;
+		l = basprintf("%s(%s) has joined %s", nick, host, chan);
+	} else if (!strcmp("PART", cmd) && chan) {
+		t = PART;
+		l = basprintf("%s(%s) has left %s", nick, host, chan);
+	} else if (!strcmp("QUIT", cmd)) {
+		t = QUIT;
+		l = basprintf("%s(%s) has quit (%s)", nick, host, text ? text : "");
+	} else if (!strcmp("NICK", cmd) && text) {
+		t = INFO;
+		l = basprintf("%s changed nick to %s", nick, text);
+	} else if (!strcmp("NOTICE", cmd)) {
+		t = INFO;
+		l = basprintf("%s: %s", nick, text ? text : "");
+	} else if (!strcmp("PRIVMSG", cmd)) {
+		if (!text)
+			text = "";
+		if (!strncmp("\001ACTION", text, strlen("\001ACTION"))) {
+			text += strlen("\001ACTION");
+			if (text[0] == ' ')
+				text++;
+			if ((p = strchr(text, '\001')))
+				*p = '\0';
+			t = EMOT;
+			l = basprintf("%s", text);
+		} else if (!strncmp("\001VERSION", text, strlen("\001VERSION"))) {
+			irc_ctcp(nick, "VERSION", version_string);
+		} else if (!strncmp("\001CLIENTINFO", text, strlen("\001CLIENTINFO"))) {
+			irc_ctcp(nick, "CLIENTINFO", "ACTION VERSION");
+		} else {
+			t = PRIV;
+			l = basprintf("%s", text);
+		}
+	} else {
+		t = INFO;
+		l = basprintf("%s", cmd);
+	}
+
+	irc_add_line(t, 0, nick, l);
+}
+
+static int rem;
+
+static void tcp_handler(char *buf, int len)
+{
+	static char msg[512];
+	char *end, *eol;
+
+	if (!len)
+		return;
+
+	end = buf + len;
+
+	/* messages ends with CR LF "\r\n" */
+	while ((eol = memchr(buf, '\n', len))) {
+		*eol = '\0';
+		if (rem) {
+			strlcpy(msg + rem, buf, sizeof(msg) - rem);
+			irc_recv(msg);
+			rem = 0;
+		} else {
+			irc_recv(buf);
+		}
+		if (eol == end)
+			break;
+		len -= (eol - buf) + 1;
+		buf += (eol - buf) + 1;
+	}
+	if (buf < end) {
+		/* keep unterminated line (rem bytes) into the msg buffer */
+		size_t n = min_t(size_t, end - buf + 1, sizeof(msg) - rem);
+		rem += strlcpy(msg + rem, buf, n);
+	}
+
+	printf("\r[%s] %s", nick, input_line);
+}
+
+static void net_handler(void *ctx, char *pkt, unsigned len)
+{
+	struct iphdr *ip = net_eth_to_iphdr(pkt);
+
+	if (net_read_ip((void *)&ip->saddr) != net_ip) {
+		printf("bad ip !\n");
+		return;
+	}
+
+	tcp_handler(net_eth_to_tcp_payload(pkt), net_eth_to_tcplen(pkt));
+}
+
+static int irc_send(const char *msg, int len)
+{
+	char *buf = net_tcp_get_payload(con);
+
+	if (len > 0) {
+		memcpy(buf, msg, len);
+		return net_tcp_send(con, len);
+	}
+
+	return 0; /* nothing to do */
+}
+
+static int irc_priv_msg(char *dst, char *str)
+{
+	char *buf = net_tcp_get_payload(con);
+	int len;
+
+	len = snprintf(buf, 256, "PRIVMSG %s :%s\r\n", dst, str);
+	if (len <= 0)
+		return -1;
+	irc_add_line(PRIV, SELF, nick, basprintf("%s", str));
+	return net_tcp_send(con, len);
+}
+
+static int irc_pong(const char *txt)
+{
+	char *buf = net_tcp_get_payload(con);
+	int len;
+
+	len = snprintf(buf, 256, "PONG %s\r\n", txt);
+	if (len <= 0)
+		return -1;
+	return net_tcp_send(con, len);
+}
+
+static int irc_ctcp(const char *dst, const char *act, const char *msg)
+{
+	char *buf = net_tcp_get_payload(con);
+	int len;
+
+	len = snprintf(buf, 256, "NOTICE %s :\001%s %s \001\r\n", dst, act, msg);
+	if (len <= 0)
+		return -1;
+	return net_tcp_send(con, len);
+}
+
+static char msg[512];
+
+static int irc_input(char *buf)
+{
+	int len;
+	char *p;
+	char *k;
+
+	if (buf[0] == '\0')
+		return 0;
+	if (buf[0] != '/')
+		return irc_priv_msg(chan, buf);
+
+	len = 0;
+	p = strchr(buf, ' ');
+	p = (p != NULL) ? p + 1 : NULL;
+	switch (buf[1]) {
+	case 'j': /* join */
+		if (!p)
+			break;
+		len = snprintf(msg, sizeof(msg), "JOIN %s\r\n", p);
+		k = strchr(p, ' ');
+		if (k)
+			*k = '\0';
+		strlcpy(chan, p, sizeof(chan));
+		break;
+	case 'p': /* part */
+	case 'l': /* leave */
+		if (!p)
+			p = "leaving";
+		len = snprintf(msg, sizeof(msg), "PART %s :%s\r\n", chan, p);;
+		break;
+	case 'n': /* nick */
+		if (!p)
+			break;
+		len = snprintf(msg, sizeof(msg), "NICK %s\r\n", p);
+		strlcpy(nick, p, sizeof(nick));
+		break;
+	case 'm': /* me */
+		if (!p)
+			break;
+		len = snprintf(msg, sizeof(msg),
+			       "PRIVMSG %s :\001ACTION %s\001\r\n", chan, p);
+		irc_add_line(EMOT, SELF, nick, basprintf("%s", p));
+		break;
+	case 'w': /* wisper */
+		if (!p)
+			break;
+		k = strchr(p, ' ');
+		if (!k)
+			break;
+		*k = '\0';
+		return irc_priv_msg(p, k + 1);
+	case 'q': /* quit */
+		if (!p)
+			p = "quiting";
+		len = snprintf(msg, sizeof(msg), "QUIT :%s\r\n", p);
+		break;
+	default:
+		len = snprintf(msg, sizeof(msg), "%s\r\n", &buf[1]);
+		break;
+	}
+
+	return irc_send(msg, len);
+}
+
+static int irc_login(char *host, char *real)
+{
+	int len;
+
+	len = snprintf(msg, sizeof(msg),
+		       "NICK %s\r\n"
+		       "USER %s localhost %s :%s\r\n",  nick, nick, host, real);
+
+	return irc_send(msg, len);
+}
+
+static int irc_readline(char *buf, int len)
+{
+	int n, c;
+
+	memset(buf, 0, len);
+	printf("\r[%s] \x1b[K", nick);
+
+	for (n = 0; n < len; ) {
+		while (!tstc()) {
+			if (redraw) {
+				redraw = 0;
+				irc_draw();
+			}
+			net_poll();
+			resched();
+		}
+		c = getchar();
+		if (c < 0)
+			return (-1);
+		switch (c) {
+		case '\b':
+		case BB_KEY_DEL7:
+		case BB_KEY_DEL:
+			if (n > 0) {
+				buf[--n] = '\0';
+				printf("\b \b");
+			}
+			break;
+		default:
+			if (isascii(c) && isprint(c)) {
+				buf[n++] = c;
+				printf("%c", c);
+			}
+			break;
+		case BB_KEY_CLEAR_SCREEN:
+			redraw = 1;
+			break;
+		case '\r':
+		case '\n':
+			buf[n] = '\0';
+			return n;
+		case CTL_CH('c'):
+			buf[0] = '\0';
+			if (n == 0) {
+				printf("QUIT");
+				return -1;
+			}
+			return 0;
+		}
+	}
+	return n;
+}
+
+static int do_irc(int argc, char *argv[])
+{
+	int ret;
+	char *host, *p;
+	char *command = NULL;
+	uint16_t port = 6667;
+	int opt;
+
+	while ((opt = getopt(argc, argv, "c:n:")) > 0) {
+		switch (opt) {
+		case 'c':
+			command = optarg;
+			break;
+		case 'n':
+			strlcpy(nick, optarg, sizeof(nick));
+			break;
+		}
+	}
+	argv += optind;
+	argc -= optind;
+	if (argc < 1)
+		return COMMAND_ERROR_USAGE;
+	host = argv[0];
+	if ((p = strchr(host, '/'))) {
+		*p = '\0';
+		port = simple_strtoul(p + 1, NULL, 10);
+	}
+	if (argc > 1)
+		port = simple_strtoul(argv[1], NULL, 10);
+
+	ret = resolv(host, &net_ip);
+	if (ret) {
+		printf("Cannot resolve \"%s\": %s\n", host, strerror(-ret));
+		return ret;
+	}
+
+	con = net_tcp_new(net_ip, port, net_handler, NULL);
+	if (IS_ERR(con)) {
+		printf("net tcp new fail\n");
+		ret = PTR_ERR(con);
+		goto out;
+	}
+
+	ret = net_tcp_open(con);
+	if (ret) {
+		printf("net_tcp_open: %d\n", ret);
+		goto out;
+	}
+
+	redraw = 1;
+	rem = 0;
+	chan[0] = '\0';
+	if (nick[0] == '\0')
+		strlcpy(nick, "barebox", sizeof(nick));
+	irc_login(host, "barebox");
+
+	if (command)
+		irc_input(command);
+
+	while (con->state == TCP_ESTABLISHED) {
+		int len;
+		len = irc_readline(input_line, sizeof(input_line) - 1);
+		if (len < 0)
+			break;
+		if (irc_input(input_line) < 0)
+			break;
+		if (ctrlc()) {
+			ret = -EINTR;
+			break;
+		}
+	}
+	net_tcp_close(con);
+	net_poll();
+
+	ret = con->ret;
+out:
+	if (!IS_ERR(con))
+		net_unregister(con);
+
+	return ret;
+}
+BAREBOX_CMD_HELP_START(irc)
+BAREBOX_CMD_HELP_TEXT("Options:")
+BAREBOX_CMD_HELP_OPT ("-n NICK\t", "nick to use")
+BAREBOX_CMD_HELP_OPT ("-c COMMAND\t", "command to run after login")
+BAREBOX_CMD_HELP_END
+
+BAREBOX_CMD_START(irc)
+	.cmd		= do_irc,
+	BAREBOX_CMD_DESC("IRC client")
+	BAREBOX_CMD_OPTS("[-nc] DESTINATION[[/]PORT]")
+	BAREBOX_CMD_GROUP(CMD_GRP_NET)
+BAREBOX_CMD_END
-- 
2.17.1




^ permalink raw reply	[flat|nested] 7+ messages in thread

* [RFC PATCH 5/5] Add tcpdump command
  2022-08-09 13:20 [RFC PATCH 1/5] net: Add a function to retrieve UDP connection Jules Maselbas
                   ` (2 preceding siblings ...)
  2022-08-09 13:20 ` [RFC PATCH 4/5] Add irc command Jules Maselbas
@ 2022-08-09 13:20 ` Jules Maselbas
  3 siblings, 0 replies; 7+ messages in thread
From: Jules Maselbas @ 2022-08-09 13:20 UTC (permalink / raw)
  To: barebox; +Cc: Jules Maselbas

This a mirror of the ethlog command but this will only dump tcp traffic
to the console.

This tcpdump command could be merged with the ethlog, also this could
also evolve to dump udp and bad packets.

Signed-off-by: Jules Maselbas <jmaselbas@kalray.eu>
---
 commands/Kconfig   |  8 +++++
 commands/Makefile  |  1 +
 commands/tcpdump.c | 84 ++++++++++++++++++++++++++++++++++++++++++++++
 include/net.h      |  1 +
 net/net.c          | 10 ++++--
 5 files changed, 102 insertions(+), 2 deletions(-)
 create mode 100644 commands/tcpdump.c

diff --git a/commands/Kconfig b/commands/Kconfig
index 5faf8eccc1..cb27ce29ce 100644
--- a/commands/Kconfig
+++ b/commands/Kconfig
@@ -1289,6 +1289,14 @@ config CMD_ETHLOG
 
 	  Usage: ethlog [-r] [DEVICENAME]
 
+config CMD_TCPDUMP
+	tristate
+	prompt "tcpdump"
+	help
+	  dump tcp traffic.
+
+	  Usage: tcpdump [-r] [DEVICENAME]
+
 # end Network commands
 endmenu
 
diff --git a/commands/Makefile b/commands/Makefile
index ecdcfe9619..a09be2c8a3 100644
--- a/commands/Makefile
+++ b/commands/Makefile
@@ -104,6 +104,7 @@ obj-$(CONFIG_CMD_LN)		+= ln.o
 obj-$(CONFIG_CMD_CLK)		+= clk.o
 obj-$(CONFIG_CMD_KEYSTORE)	+= keystore.o
 obj-$(CONFIG_CMD_TFTP)		+= tftp.o
+obj-$(CONFIG_CMD_TCPDUMP)	+= tcpdump.o
 obj-$(CONFIG_CMD_FILETYPE)	+= filetype.o
 obj-$(CONFIG_CMD_BAREBOX_UPDATE)+= barebox-update.o
 obj-$(CONFIG_CMD_MIITOOL)	+= miitool.o
diff --git a/commands/tcpdump.c b/commands/tcpdump.c
new file mode 100644
index 0000000000..bcfe42a897
--- /dev/null
+++ b/commands/tcpdump.c
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: GPL-2.0-only
+// SPDX-FileCopyrightText: (c) 2022 Jules Maselbas <jmaselbas@kalray.eu>
+
+#include <common.h>
+#include <command.h>
+#include <complete.h>
+#include <environment.h>
+#include <getopt.h>
+#include <net.h>
+
+static void tcp_dump(struct eth_device *edev, void *pkt, int len)
+{
+	struct iphdr *ip = net_eth_to_iphdr(pkt);
+	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
+	uint16_t flag = ntohs(tcp->doff_flag) & TCP_FLAG_MASK;
+	int opt = net_tcp_data_offset(tcp) - sizeof(struct tcphdr);
+	char cksum[sizeof("0xffff")];
+	char flags[sizeof("FSRPAU")] = {};
+	char *f = flags;
+
+	if (flag & TCP_FLAG_FIN) *f++ = 'F';
+	if (flag & TCP_FLAG_SYN) *f++ = 'S';
+	if (flag & TCP_FLAG_RST) *f++ = 'R';
+	if (flag & TCP_FLAG_PSH) *f++ = 'P';
+	if (flag & TCP_FLAG_ACK) *f++ = 'A';
+	if (flag & TCP_FLAG_URG) *f++ = 'U';
+
+	snprintf(cksum, sizeof(cksum), "%#.4x", tcp_checksum(ip, tcp, len));
+	pr_debug("%pI4:%u > %pI4:%u [%s] cksum %#.4x (%s) seq %u ack %u win %u opt [%d] len %d\n",
+		&ip->saddr, ntohs(tcp->src), &ip->daddr, ntohs(tcp->dst),
+		flags, ntohs(tcp->sum),
+		tcp_checksum_ok(ip, tcp, len) ? "correct" : cksum,
+		ntohl(tcp->seq), ntohl(tcp->ack), ntohs(tcp->wnd),
+		opt, len);
+}
+
+static int do_tcpdump(int argc, char *argv[])
+{
+	struct eth_device *edev;
+	const char *edevname;
+	bool remove = false;
+	int opt;
+
+	while ((opt = getopt(argc, argv, "r")) > 0) {
+		switch (opt) {
+		case 'r':
+			remove = true;
+			break;
+		default:
+			return COMMAND_ERROR_USAGE;
+		}
+	}
+
+	if (optind == argc)
+		edevname = "eth0";
+	else
+		edevname = argv[optind];
+
+	edev = eth_get_byname(edevname);
+	if (!edev) {
+		printf("No such network device: %s\n", edevname);
+		return 1;
+	}
+
+	if (remove)
+		edev->tcp_dump = NULL;
+	else
+		edev->tcp_dump = tcp_dump;
+
+	return 0;
+}
+
+BAREBOX_CMD_HELP_START(tcpdump)
+BAREBOX_CMD_HELP_TEXT("Options:")
+BAREBOX_CMD_HELP_OPT("-r", "remove log handler from Ethernet interface")
+BAREBOX_CMD_HELP_END
+
+BAREBOX_CMD_START(tcpdump)
+	.cmd		= do_tcpdump,
+	BAREBOX_CMD_DESC("tcpdump - tool to get dump of TCP packets")
+	BAREBOX_CMD_OPTS("[-r] [device]")
+	BAREBOX_CMD_GROUP(CMD_GRP_NET)
+	BAREBOX_CMD_COMPLETE(eth_complete)
+BAREBOX_CMD_END
diff --git a/include/net.h b/include/net.h
index 76b64ccb21..ff9c7dc1f7 100644
--- a/include/net.h
+++ b/include/net.h
@@ -48,6 +48,7 @@ struct eth_device {
 				 int *length);
 	void (*rx_monitor) (struct eth_device*, void *packet, int length);
 	void (*tx_monitor) (struct eth_device*, void *packet, int length);
+	void (*tcp_dump) (struct eth_device*, void *packet, int length);
 
 	struct eth_device *next;
 	void *priv;
diff --git a/net/net.c b/net/net.c
index 855bb8e4c2..1717a0726f 100644
--- a/net/net.c
+++ b/net/net.c
@@ -586,6 +586,9 @@ static int tcp_send(struct net_connection *con, int len, uint16_t flags)
 	con->tcp->sum = 0;
 	con->tcp->sum = ~tcp_checksum(con->ip, con->tcp, len);
 
+	if (con->edev->tcp_dump)
+		con->edev->tcp_dump(con->edev, con->packet, len);
+
 	return net_ip_send(con, hdr_size + len);
 }
 
@@ -848,7 +851,7 @@ static int net_handle_udp(unsigned char *pkt, int len)
 	return -EINVAL;
 }
 
-static int net_handle_tcp(unsigned char *pkt, int len)
+static int net_handle_tcp(struct eth_device *edev, unsigned char *pkt, int len)
 {
 	size_t min_size = ETHER_HDR_SIZE + sizeof(struct iphdr);
 	struct net_connection *con;
@@ -890,6 +893,9 @@ static int net_handle_tcp(unsigned char *pkt, int len)
 		goto bad;
 	tcb = &con->tcb;
 
+	if (edev->tcp_dump)
+		edev->tcp_dump(edev, pkt, len);
+
 	/* segment arrives */
 	seg_last = seg_seq + seg_len - 1;
 	rcv_wnd = tcb->rcv_wnd;
@@ -1116,7 +1122,7 @@ static int net_handle_ip(struct eth_device *edev, unsigned char *pkt, int len)
 	case IPPROTO_UDP:
 		return net_handle_udp(pkt, len);
 	case IPPROTO_TCP:
-		return net_handle_tcp(pkt, len);
+		return net_handle_tcp(edev, pkt, len);
 	}
 
 	return 0;
-- 
2.17.1




^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: [RFC PATCH 3/5] net: Add simple TCP support
  2022-08-09 13:20 ` [RFC PATCH 3/5] net: Add simple TCP support Jules Maselbas
@ 2022-08-12  7:04   ` Sascha Hauer
  2022-08-12 16:17     ` Jules Maselbas
  0 siblings, 1 reply; 7+ messages in thread
From: Sascha Hauer @ 2022-08-12  7:04 UTC (permalink / raw)
  To: Jules Maselbas; +Cc: barebox

Hi Jules,

On Tue, Aug 09, 2022 at 03:20:19PM +0200, Jules Maselbas wrote:
> This is a very simple TCP implementation that only support connecting
> to servers (passive open and listen are not supported).
> 
> This also doesn't handle multiples segments and the TCP window size is
> smaller than the MTU, this will hopefully make the sender only send one
> segment at a time.

I am impressed how simple TCP support can be. I never even considered
trying to write TCP support from scratch.
My plan for TCP support was always to integrate some existing stack like
lwip into barebox to get a stack that has proven to work elsewhere. Also
IPv6 support is still a pending feature which is becoming more and more
interesting and we would get that for free with integrating an existing
IP stack.
Given that I am sceptical if we really want to follow the approach of
developping TCP from scratch.
Nevertheless it's really cool to see how simple it could be ;) Nice
stuff!

Sascha


> 
> Signed-off-by: Jules Maselbas <jmaselbas@kalray.eu>
> ---
>  common/misc.c |  12 +-
>  include/net.h | 118 +++++++++++++++
>  net/net.c     | 406 ++++++++++++++++++++++++++++++++++++++++++++++++++
>  3 files changed, 531 insertions(+), 5 deletions(-)
> 
> diff --git a/common/misc.c b/common/misc.c
> index 0f6de3e9e5..30e94f5a8b 100644
> --- a/common/misc.c
> +++ b/common/misc.c
> @@ -57,6 +57,13 @@ const char *strerror(int errnum)
>  	case	EPROBE_DEFER	: str = "Requested probe deferral"; break;
>  	case	ELOOP		: str = "Too many symbolic links encountered"; break;
>  	case	ENODATA		: str = "No data available"; break;
> +#ifdef CONFIG_NET
> +	case	ENETRESET	: str = "Network dropped connection because of reset"; break;
> +	case	ECONNABORTED	: str = "Software caused connection abort"; break;
> +	case	ECONNRESET	: str = "Connection reset by peer"; break;
> +	case	ENOBUFS		: str = "No buffer space available"; break;
> +	case	ECONNREFUSED	: str = "Connection refused"; break;
> +#endif
>  #if 0 /* These are probably not needed */
>  	case	ENOTBLK		: str = "Block device required"; break;
>  	case	EFBIG		: str = "File too large"; break;
> @@ -79,11 +86,6 @@ const char *strerror(int errnum)
>  	case	EAFNOSUPPORT	: str = "Address family not supported by protocol"; break;
>  	case	EADDRINUSE	: str = "Address already in use"; break;
>  	case	EADDRNOTAVAIL	: str = "Cannot assign requested address"; break;
> -	case	ENETRESET	: str = "Network dropped connection because of reset"; break;
> -	case	ECONNABORTED	: str = "Software caused connection abort"; break;
> -	case	ECONNRESET	: str = "Connection reset by peer"; break;
> -	case	ENOBUFS		: str = "No buffer space available"; break;
> -	case	ECONNREFUSED	: str = "Connection refused"; break;
>  	case	EHOSTDOWN	: str = "Host is down"; break;
>  	case	EALREADY	: str = "Operation already in progress"; break;
>  	case	EINPROGRESS	: str = "Operation now in progress"; break;
> diff --git a/include/net.h b/include/net.h
> index b50b6e76c8..76b64ccb21 100644
> --- a/include/net.h
> +++ b/include/net.h
> @@ -143,6 +143,7 @@ struct ethernet {
>  #define PROT_VLAN	0x8100		/* IEEE 802.1q protocol		*/
>  
>  #define IPPROTO_ICMP	 1	/* Internet Control Message Protocol	*/
> +#define IPPROTO_TCP	 6	/* Transmission Control Protocol	*/
>  #define IPPROTO_UDP	17	/* User Datagram Protocol		*/
>  
>  #define IP_BROADCAST    0xffffffff /* Broadcast IP aka 255.255.255.255 */
> @@ -171,6 +172,67 @@ struct udphdr {
>  	uint16_t	uh_sum;		/* udp checksum */
>  } __attribute__ ((packed));
>  
> +/* pseudo header for checksum */
> +struct psdhdr {
> +	uint32_t	saddr;
> +	uint32_t	daddr;
> +	uint16_t	proto;
> +	uint16_t	ttlen;
> +} __attribute__ ((packed));
> +
> +struct tcphdr {
> +	uint16_t	src;	/* source port */
> +	uint16_t	dst;	/* destination port */
> +	uint32_t	seq;	/* sequence number */
> +	uint32_t	ack;	/* acknowledge number */
> +	uint16_t 	doff_flag;	/* data offset and flags */
> +#define TCP_DOFF_MASK	0xf
> +#define TCP_DOFF_SHIFT	12
> +#define TCP_FLAG_FIN	BIT(0)
> +#define TCP_FLAG_SYN	BIT(1)
> +#define TCP_FLAG_RST	BIT(2)
> +#define TCP_FLAG_PSH	BIT(3)
> +#define TCP_FLAG_ACK	BIT(4)
> +#define TCP_FLAG_URG	BIT(5)
> +#define TCP_FLAG_ECE	BIT(6)
> +#define TCP_FLAG_CWR	BIT(7)
> +#define TCP_FLAG_NS	BIT(8)
> +#define TCP_FLAG_MASK	0x1ff
> +	uint16_t	wnd;	/* window size */
> +	uint16_t	sum;	/* header and data checksum */
> +	uint16_t	urp;	/* urgent pointer (if URG is set) */
> +	/* The options start here. */
> +} __attribute__ ((packed));
> +
> +enum tcp_state {
> +	TCP_CLOSED = 0,
> +	TCP_LISTEN,
> +	TCP_SYN_SENT,
> +	TCP_SYN_RECV,
> +	TCP_ESTABLISHED,
> +	TCP_FIN_WAIT1,
> +	TCP_FIN_WAIT2,
> +	TCP_TIME_WAIT,
> +	TCP_CLOSE_WAIT,
> +	TCP_LAST_ACK,
> +	TCP_CLOSING,
> +};
> +
> +/* Transmission Control Block */
> +struct tcb {
> +	uint32_t snd_una;
> +	uint32_t snd_nxt;
> +	uint32_t snd_wnd;
> +	uint16_t snd_urp;
> +	uint32_t snd_wl1;
> +	uint32_t snd_wl2;
> +	uint32_t rcv_nxt;
> +	uint32_t rcv_wnd;
> +	uint16_t rcv_urp;
> +	uint32_t iss;
> +	uint32_t irs;
> +};
> +
>  /*
>   *	Address Resolution Protocol (ARP) header.
>   */
> @@ -264,6 +326,13 @@ struct eth_device *net_route(IPaddr_t ip);
>  /* Do the work */
>  void net_poll(void);
>  
> +static inline size_t net_tcp_data_offset(struct tcphdr *tcp)
> +{
> +	uint16_t doff;
> +	doff = ntohs(tcp->doff_flag) >> TCP_DOFF_SHIFT;
> +	return doff * sizeof(uint32_t);
> +}
> +
>  static inline struct iphdr *net_eth_to_iphdr(char *pkt)
>  {
>  	return (struct iphdr *)(pkt + ETHER_HDR_SIZE);
> @@ -274,6 +343,11 @@ static inline struct udphdr *net_eth_to_udphdr(char *pkt)
>  	return (struct udphdr *)(net_eth_to_iphdr(pkt) + 1);
>  }
>  
> +static inline struct tcphdr *net_eth_to_tcphdr(char *pkt)
> +{
> +	return (struct tcphdr *)(net_eth_to_iphdr(pkt) + 1);
> +}
> +
>  static inline struct icmphdr *net_eth_to_icmphdr(char *pkt)
>  {
>  	return (struct icmphdr *)(net_eth_to_iphdr(pkt) + 1);
> @@ -295,8 +369,28 @@ static inline int net_eth_to_udplen(char *pkt)
>  	return ntohs(udp->uh_ulen) - 8;
>  }
>  
> +static inline char *net_eth_to_tcp_payload(char *pkt)
> +{
> +	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
> +	return ((char *)tcp) + net_tcp_data_offset(tcp);
> +}
> +
> +static inline int net_eth_to_iplen(char *pkt)
> +{
> +	struct iphdr *ip = net_eth_to_iphdr(pkt);
> +	return ntohs(ip->tot_len) - sizeof(struct iphdr);
> +}
> +
> +static inline int net_eth_to_tcplen(char *pkt)
> +{
> +	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
> +	return net_eth_to_iplen(pkt) - net_tcp_data_offset(tcp);
> +}
> +
>  int net_checksum_ok(unsigned char *, int);	/* Return true if cksum OK	*/
>  uint16_t net_checksum(unsigned char *, int);	/* Calculate the checksum	*/
> +int tcp_checksum_ok(struct iphdr *ip, struct tcphdr *tcp, int len);
> +uint16_t tcp_checksum(struct iphdr *ip, struct tcphdr *tcp, int len);
>  
>  /*
>   * The following functions are a bit ugly, but necessary to deal with
> @@ -459,12 +553,18 @@ struct net_connection {
>  	struct ethernet *et;
>  	struct iphdr *ip;
>  	struct udphdr *udp;
> +	struct tcphdr *tcp;
>  	struct eth_device *edev;
>  	struct icmphdr *icmp;
>  	unsigned char *packet;
>  	struct list_head list;
>  	rx_handler_f *handler;
>  	int proto;
> +	int state;
> +	int ret;
> +	union {
> +		struct tcb tcb;
> +	};
>  	void *priv;
>  };
>  
> @@ -480,6 +580,13 @@ struct net_connection *net_udp_eth_new(struct eth_device *edev, IPaddr_t dest,
>                                         uint16_t dport, rx_handler_f *handler,
>                                         void *ctx);
>  
> +struct net_connection *net_tcp_new(IPaddr_t dest, uint16_t dport,
> +		rx_handler_f *handler, void *ctx);
> +
> +struct net_connection *net_tcp_eth_new(struct eth_device *edev, IPaddr_t dest,
> +                                       uint16_t dport, rx_handler_f *handler,
> +                                       void *ctx);
> +
>  struct net_connection *net_icmp_new(IPaddr_t dest, rx_handler_f *handler,
>  		void *ctx);
>  
> @@ -497,6 +604,17 @@ static inline void *net_udp_get_payload(struct net_connection *con)
>  		sizeof(struct udphdr);
>  }
>  
> +static inline void *net_tcp_get_payload(struct net_connection *con)
> +{
> +	return con->packet + sizeof(struct ethernet) + sizeof(struct iphdr) +
> +		net_tcp_data_offset(con->tcp);
> +}
> +
> +int net_tcp_listen(struct net_connection *con);
> +int net_tcp_open(struct net_connection *con);
> +int net_tcp_send(struct net_connection *con, int len);
> +int net_tcp_close(struct net_connection *con);
> +
>  int net_udp_send(struct net_connection *con, int len);
>  int net_icmp_send(struct net_connection *con, int len);
>  
> diff --git a/net/net.c b/net/net.c
> index 9f799f252d..855bb8e4c2 100644
> --- a/net/net.c
> +++ b/net/net.c
> @@ -47,6 +47,8 @@ static struct net_connection *net_ip_get_con(int proto, uint16_t port)
>  			continue;
>  		if (con->proto == IPPROTO_UDP && ntohs(con->udp->uh_sport) == port)
>  			return con;
> +		if (con->proto == IPPROTO_TCP && ntohs(con->tcp->src) == port)
> +			return con;
>  	}
>  
>  	return NULL;
> @@ -99,6 +101,31 @@ uint16_t net_checksum(unsigned char *ptr, int len)
>  	return xsum & 0xffff;
>  }
>  
> +uint16_t tcp_checksum(struct iphdr *ip, struct tcphdr *tcp, int len)
> +{
> +	uint32_t xsum;
> +	struct psdhdr pseudo;
> +	size_t hdrsize = net_tcp_data_offset(tcp);
> +
> +	pseudo.saddr = ip->saddr;
> +	pseudo.daddr = ip->daddr;
> +	pseudo.proto = htons(ip->protocol);
> +	pseudo.ttlen = htons(hdrsize + len);
> +
> +	xsum = net_checksum((void *)&pseudo, sizeof(struct psdhdr));
> +	xsum += net_checksum((void *)tcp, hdrsize + len);
> +
> +	while (xsum > 0xffff)
> +		xsum = (xsum & 0xffff) + (xsum >> 16);
> +
> +	return xsum;
> +}
> +
> +int tcp_checksum_ok(struct iphdr *ip, struct tcphdr *tcp, int len)
> +{
> +	return tcp_checksum(ip, tcp, len) == 0xffff;
> +}
> +
>  IPaddr_t getenv_ip(const char *name)
>  {
>  	IPaddr_t ip;
> @@ -335,6 +362,11 @@ static uint16_t net_udp_new_localport(void)
>  	return net_new_localport(IPPROTO_UDP);
>  }
>  
> +static uint16_t net_tcp_new_localport(void)
> +{
> +	return net_new_localport(IPPROTO_TCP);
> +}
> +
>  IPaddr_t net_get_serverip(void)
>  {
>  	IPaddr_t ip;
> @@ -422,6 +454,7 @@ static struct net_connection *net_new(struct eth_device *edev, IPaddr_t dest,
>  	con->et = (struct ethernet *)con->packet;
>  	con->ip = (struct iphdr *)(con->packet + ETHER_HDR_SIZE);
>  	con->udp = (struct udphdr *)(con->packet + ETHER_HDR_SIZE + sizeof(struct iphdr));
> +	con->tcp = (struct tcphdr *)(con->packet + ETHER_HDR_SIZE + sizeof(struct iphdr));
>  	con->icmp = (struct icmphdr *)(con->packet + ETHER_HDR_SIZE + sizeof(struct iphdr));
>  	con->handler = handler;
>  
> @@ -452,6 +485,30 @@ out:
>  	return ERR_PTR(ret);
>  }
>  
> +struct net_connection *net_tcp_eth_new(struct eth_device *edev, IPaddr_t dest,
> +				       uint16_t dport, rx_handler_f *handler,
> +				       void *ctx)
> +{
> +	struct net_connection *con = net_new(edev, dest, handler, ctx);
> +	uint16_t doff;
> +
> +	if (IS_ERR(con))
> +		return con;
> +
> +	con->proto = IPPROTO_TCP;
> +	con->state = TCP_CLOSED;
> +	con->tcp->src = htons(net_tcp_new_localport());
> +	con->tcp->dst = htons(dport);
> +	con->tcp->seq = 0;
> +	con->tcp->ack = 0;
> +	doff = sizeof(struct tcphdr) / sizeof(uint32_t);
> +	con->tcp->doff_flag = htons(doff << TCP_DOFF_SHIFT);
> +	con->tcp->urp = 0;
> +	con->ip->protocol = IPPROTO_TCP;
> +
> +	return con;
> +}
> +
>  struct net_connection *net_udp_eth_new(struct eth_device *edev, IPaddr_t dest,
>  				       uint16_t dport, rx_handler_f *handler,
>  				       void *ctx)
> @@ -475,6 +532,12 @@ struct net_connection *net_udp_new(IPaddr_t dest, uint16_t dport,
>  	return net_udp_eth_new(NULL, dest, dport, handler, ctx);
>  }
>  
> +struct net_connection *net_tcp_new(IPaddr_t dest, uint16_t dport,
> +		rx_handler_f *handler, void *ctx)
> +{
> +	return net_tcp_eth_new(NULL, dest, dport, handler, ctx);
> +}
> +
>  struct net_connection *net_icmp_new(IPaddr_t dest, rx_handler_f *handler,
>  		void *ctx)
>  {
> @@ -514,6 +577,167 @@ int net_udp_send(struct net_connection *con, int len)
>  	return net_ip_send(con, sizeof(struct udphdr) + len);
>  }
>  
> +static int tcp_send(struct net_connection *con, int len, uint16_t flags)
> +{
> +	size_t hdr_size = net_tcp_data_offset(con->tcp);
> +
> +	con->tcp->doff_flag &= ~htons(TCP_FLAG_MASK);
> +	con->tcp->doff_flag |= htons(flags);
> +	con->tcp->sum = 0;
> +	con->tcp->sum = ~tcp_checksum(con->ip, con->tcp, len);
> +
> +	return net_ip_send(con, hdr_size + len);
> +}
> +
> +int net_tcp_send(struct net_connection *con, int len)
> +{
> +	struct tcb *tcb = &con->tcb;
> +	uint16_t flag = 0;
> +
> +	if (con->proto != IPPROTO_TCP)
> +		return -EPROTOTYPE;
> +	switch (con->state) {
> +	case TCP_CLOSED:
> +		return -ENOTCONN;
> +	case TCP_LISTEN:
> +		/* TODO: proceed as open */
> +		break;
> +	case TCP_SYN_SENT:
> +	case TCP_SYN_RECV:
> +		/* queue request or "error:  insufficient resources". */
> +		break;
> +	case TCP_ESTABLISHED:
> +	case TCP_CLOSE_WAIT:
> +		/* proceed */
> +		break;
> +	case TCP_FIN_WAIT1:
> +	case TCP_FIN_WAIT2:
> +	case TCP_TIME_WAIT:
> +	case TCP_LAST_ACK:
> +	case TCP_CLOSING:
> +		return -ESHUTDOWN;
> +	}
> +
> +	con->tcp->seq = htonl(tcb->snd_nxt);
> +	tcb->snd_nxt += len;
> +	flag |= TCP_FLAG_PSH;
> +	if (1 || ntohl(con->tcp->ack) < con->tcb.rcv_nxt) {
> +		flag |= TCP_FLAG_ACK;
> +		con->tcp->ack = htonl(con->tcb.rcv_nxt);
> +	} else {
> +		con->tcp->ack = 0;
> +	}
> +
> +	return tcp_send(con, len, flag);
> +}
> +
> +int net_tcp_listen(struct net_connection *con)
> +{
> +	if (con->proto != IPPROTO_TCP)
> +		return -EPROTOTYPE;
> +
> +	con->state = TCP_LISTEN;
> +	return -1;
> +}
> +
> +int net_tcp_open(struct net_connection *con)
> +{
> +	struct tcphdr *tcp = net_eth_to_tcphdr(con->packet);
> +	struct tcb *tcb = &con->tcb;
> +	int ret;
> +
> +	if (con->proto != IPPROTO_TCP)
> +		return -EPROTOTYPE;
> +	switch (con->state) {
> +	case TCP_CLOSED:
> +	case TCP_LISTEN:
> +		break;
> +	case TCP_SYN_SENT:
> +	case TCP_SYN_RECV:
> +	case TCP_ESTABLISHED:
> +	case TCP_FIN_WAIT1:
> +	case TCP_FIN_WAIT2:
> +	case TCP_TIME_WAIT:
> +	case TCP_CLOSE_WAIT:
> +	case TCP_LAST_ACK:
> +	case TCP_CLOSING:
> +		return -EISCONN;
> +	}
> +
> +	/* use a window smaller than the MTU, as only one tcp segment packet
> +	 * can be received at time */
> +	tcb->rcv_wnd = 1024;
> +	tcb->snd_wnd = 0;
> +	tcb->iss = random32() + (get_time_ns() >> 10);
> +	con->state = TCP_SYN_SENT;
> +
> +	tcp->wnd = htons(tcb->rcv_wnd);
> +	tcp->seq = htonl(tcb->iss);
> +	tcb->snd_una = tcb->iss;
> +	tcb->snd_nxt = tcb->iss + 1;
> +	ret = tcp_send(con, 0, TCP_FLAG_SYN);
> +	if (ret)
> +		return ret;
> +
> +	ret = wait_on_timeout(6000 * MSECOND, con->state == TCP_ESTABLISHED);
> +	if (ret)
> +		return -ETIMEDOUT;
> +
> +	return con->ret; // TODO: return 0 ?
> +}
> +
> +int net_tcp_close(struct net_connection *con)
> +{
> +	struct tcphdr *tcp = net_eth_to_tcphdr(con->packet);
> +	struct tcb *tcb = &con->tcb;
> +	int ret;
> +
> +	if (con->proto != IPPROTO_TCP)
> +		return -EPROTOTYPE;
> +	switch (con->state) {
> +	case TCP_CLOSED:
> +		return -ENOTCONN;
> +	case TCP_LISTEN:
> +	case TCP_SYN_SENT:
> +		con->state = TCP_CLOSED;
> +		return 0;
> +		break;
> +	case TCP_SYN_RECV:
> +	case TCP_ESTABLISHED:
> +		/* wait for pending send */
> +		con->state = TCP_FIN_WAIT1;
> +		break;
> +	case TCP_FIN_WAIT1:
> +	case TCP_FIN_WAIT2:
> +		/* error: connection closing */
> +		return -1;
> +	case TCP_TIME_WAIT:
> +	case TCP_LAST_ACK:
> +	case TCP_CLOSING:
> +		/* error: connection closing */
> +		return -1;
> +	case TCP_CLOSE_WAIT:
> +		/* queue close request after pending sends */
> +		con->state = TCP_LAST_ACK;
> +		break;
> +	}
> +
> +	tcp->seq = htonl(tcb->snd_nxt);
> +	tcp->ack = htonl(tcb->rcv_nxt);
> +	tcb->snd_nxt += 1;
> +	ret = tcp_send(con, 0, TCP_FLAG_FIN | TCP_FLAG_ACK);
> +	if (ret)
> +		return ret;
> +
> +	ret = wait_on_timeout(1000 * MSECOND, con->state == TCP_CLOSED);
> +	if (ret)
> +		return -ETIMEDOUT;
> +
> +	net_unregister(con);
> +
> +	return con->ret; // TODO: return 0 ?
> +}
> +
>  int net_icmp_send(struct net_connection *con, int len)
>  {
>  	con->icmp->checksum = ~net_checksum((unsigned char *)con->icmp,
> @@ -624,6 +848,186 @@ static int net_handle_udp(unsigned char *pkt, int len)
>  	return -EINVAL;
>  }
>  
> +static int net_handle_tcp(unsigned char *pkt, int len)
> +{
> +	size_t min_size = ETHER_HDR_SIZE + sizeof(struct iphdr);
> +	struct net_connection *con;
> +	struct iphdr *ip = net_eth_to_iphdr(pkt);
> +	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
> +	struct tcb *tcb;
> +	uint16_t flag;
> +	uint16_t doff;
> +	uint32_t tcp_len;
> +	uint32_t seg_len;
> +	uint32_t seg_ack;
> +	uint32_t seg_seq;
> +	uint32_t seg_last;
> +	uint32_t rcv_wnd;
> +	uint32_t rcv_nxt;
> +	int seg_accept = 0;
> +
> +	if (len < (min_size + sizeof(struct tcphdr)))
> +		goto bad;
> +	flag = ntohs(tcp->doff_flag) & TCP_FLAG_MASK;
> +	doff = net_tcp_data_offset(tcp);
> +	if (doff < sizeof(struct tcphdr))
> +		goto bad;
> +	if (len < (min_size + doff))
> +		goto bad;
> +
> +	seg_ack = ntohl(tcp->ack);
> +	seg_seq = ntohl(tcp->seq);
> +	tcp_len = net_eth_to_tcplen(pkt);
> +	seg_len = tcp_len;
> +	seg_len += !!(flag & TCP_FLAG_FIN);
> +	seg_len += !!(flag & TCP_FLAG_SYN);
> +
> +	if (!tcp_checksum_ok(ip, tcp, tcp_len))
> +		goto bad;
> +
> +	con = net_ip_get_con(IPPROTO_TCP, ntohs(tcp->dst));
> +	if (con == NULL)
> +		goto bad;
> +	tcb = &con->tcb;
> +
> +	/* segment arrives */
> +	seg_last = seg_seq + seg_len - 1;
> +	rcv_wnd = tcb->rcv_wnd;
> +	rcv_nxt = tcb->rcv_nxt;
> +
> +	if (seg_len == 0 && rcv_wnd == 0)
> +		seg_accept = seg_seq == rcv_nxt;
> +	if (seg_len == 0 && rcv_wnd > 0)
> +		seg_accept = rcv_nxt <= seg_seq && seg_seq < (rcv_nxt + rcv_wnd);
> +	if (seg_len > 0 && rcv_wnd == 0)
> +		seg_accept = 0; /* not acceptable */
> +	if (seg_len > 0 && rcv_wnd > 0)
> +		seg_accept = (rcv_nxt <= seg_seq && seg_seq < (rcv_nxt + rcv_wnd))
> +			|| (rcv_nxt <= seg_last && seg_last < (rcv_nxt + rcv_wnd));
> +
> +	switch (con->state) {
> +	case TCP_CLOSED:
> +		if (flag & TCP_FLAG_RST) {
> +			goto drop;
> +		}
> +		if (flag & TCP_FLAG_ACK) {
> +			con->tcp->seq = 0;
> +			con->tcp->ack = htonl(seg_seq + seg_len);
> +			con->ret = tcp_send(con, 0, TCP_FLAG_RST | TCP_FLAG_ACK);
> +		} else  {
> +			con->tcp->seq = htonl(seg_ack);
> +			con->ret = tcp_send(con, 0, TCP_FLAG_RST);
> +		}
> +		break;
> +	case TCP_LISTEN:
> +		/* TODO */
> +		break;
> +	case TCP_SYN_SENT:
> +		if (flag & TCP_FLAG_ACK) {
> +			if (seg_ack <= tcb->iss || seg_ack > tcb->snd_nxt) {
> +				if (flag & TCP_FLAG_RST)
> +					goto drop;
> +				con->tcp->seq = htonl(seg_ack);
> +				return tcp_send(con, 0, TCP_FLAG_RST);
> +			}
> +			if (tcb->snd_una > seg_ack || seg_ack > tcb->snd_nxt)
> +				goto drop; /* unacceptable */
> +		}
> +		if (flag & TCP_FLAG_RST) {
> +			con->state = TCP_CLOSED;
> +			con->ret = -ENETRESET;
> +			break;
> +		}
> +		if ((flag & TCP_FLAG_SYN) && !(flag & TCP_FLAG_RST)) {
> +			tcb->irs = seg_seq;
> +			tcb->rcv_nxt = seg_seq + 1;
> +			if (flag & TCP_FLAG_ACK)
> +				tcb->snd_una = seg_ack;
> +			if (tcb->snd_una > tcb->iss) {
> +				con->state = TCP_ESTABLISHED;
> +				con->tcp->seq = htonl(tcb->snd_nxt);
> +				con->tcp->ack = htonl(tcb->rcv_nxt);
> +				con->ret = tcp_send(con, 0, TCP_FLAG_ACK);
> +			} else {
> +				con->state = TCP_SYN_RECV;
> +				tcb->snd_nxt = tcb->iss + 1;
> +				con->tcp->seq = htonl(tcb->iss);
> +				con->tcp->ack = htonl(tcb->rcv_nxt);
> +				con->ret = tcp_send(con, 0, TCP_FLAG_SYN | TCP_FLAG_ACK);
> +			}
> +		}
> +		break;
> +	case TCP_SYN_RECV:
> +	case TCP_ESTABLISHED:
> +		if (flag & TCP_FLAG_RST) {
> +			/* TODO: if passive open then return to LISTEN */
> +			con->state = TCP_CLOSED;
> +			con->ret = -ECONNREFUSED;
> +			break;
> +		}
> +		if (!seg_accept) {
> +			/* segment is not acceptable, send an ack unless RST bit
> +			 * is set (done above) */
> +			con->tcp->seq = htonl(tcb->snd_nxt);
> +			con->tcp->ack = htonl(tcb->rcv_nxt);
> +			con->ret = tcp_send(con, 0, TCP_FLAG_ACK);
> +			goto drop;
> +		}
> +		if (flag & TCP_FLAG_FIN && flag & TCP_FLAG_ACK)
> +			con->state = TCP_CLOSE_WAIT;
> +
> +		if (flag & TCP_FLAG_ACK)
> +			tcb->snd_una = seg_ack;
> +
> +		tcb->rcv_nxt += seg_len;
> +		con->tcp->seq = htonl(tcb->snd_nxt);
> +		if (seg_len) {
> +			con->tcp->ack = htonl(tcb->rcv_nxt);
> +			con->ret = tcp_send(con, 0, TCP_FLAG_ACK |
> +					    /* send FIN+ACK if FIN is set */
> +					    (flag & TCP_FLAG_FIN));
> +		}
> +		con->handler(con->priv, pkt, len);
> +		break;
> +	case TCP_FIN_WAIT1:
> +		if (flag & TCP_FLAG_FIN)
> +			con->state = TCP_CLOSING;
> +		if (flag & TCP_FLAG_ACK)
> +			tcb->snd_una = seg_ack;
> +		/* fall-through */
> +	case TCP_FIN_WAIT2:
> +		tcb->rcv_nxt += seg_len;
> +		con->tcp->seq = htonl(tcb->snd_nxt);
> +		if (seg_len) {
> +			con->tcp->ack = htonl(tcb->rcv_nxt);
> +			con->ret = tcp_send(con, 0, TCP_FLAG_ACK);
> +		}
> +	case TCP_CLOSE_WAIT:
> +		/* all segment queues should be flushed */
> +		if (flag & TCP_FLAG_RST) {
> +			con->state = TCP_CLOSED;
> +			con->ret = -ENETRESET;
> +			break;
> +		}
> +		break;
> +	case TCP_CLOSING:
> +		con->state = TCP_TIME_WAIT;
> +	case TCP_LAST_ACK:
> +	case TCP_TIME_WAIT:
> +		if (flag & TCP_FLAG_RST) {
> +			con->state = TCP_CLOSED;
> +			con->ret = 0;
> +		}
> +		break;
> +	}
> +	return con->ret;
> +drop:
> +	return 0;
> +bad:
> +	net_bad_packet(pkt, len);
> +	return 0;
> +}
> +
>  static int ping_reply(struct eth_device *edev, unsigned char *pkt, int len)
>  {
>  	struct ethernet *et = (struct ethernet *)pkt;
> @@ -711,6 +1115,8 @@ static int net_handle_ip(struct eth_device *edev, unsigned char *pkt, int len)
>  		return net_handle_icmp(edev, pkt, len);
>  	case IPPROTO_UDP:
>  		return net_handle_udp(pkt, len);
> +	case IPPROTO_TCP:
> +		return net_handle_tcp(pkt, len);
>  	}
>  
>  	return 0;
> -- 
> 2.17.1
> 
> 
> 

-- 
Pengutronix e.K.                           |                             |
Steuerwalder Str. 21                       | http://www.pengutronix.de/  |
31137 Hildesheim, Germany                  | Phone: +49-5121-206917-0    |
Amtsgericht Hildesheim, HRA 2686           | Fax:   +49-5121-206917-5555 |



^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: [RFC PATCH 3/5] net: Add simple TCP support
  2022-08-12  7:04   ` Sascha Hauer
@ 2022-08-12 16:17     ` Jules Maselbas
  0 siblings, 0 replies; 7+ messages in thread
From: Jules Maselbas @ 2022-08-12 16:17 UTC (permalink / raw)
  To: Sascha Hauer; +Cc: barebox

Hi Sascha,

On Fri, Aug 12, 2022 at 09:04:48AM +0200, Sascha Hauer wrote:
> Hi Jules,
> 
> On Tue, Aug 09, 2022 at 03:20:19PM +0200, Jules Maselbas wrote:
> > This is a very simple TCP implementation that only support connecting
> > to servers (passive open and listen are not supported).
> > 
> > This also doesn't handle multiples segments and the TCP window size is
> > smaller than the MTU, this will hopefully make the sender only send one
> > segment at a time.
> 
> I am impressed how simple TCP support can be. I never even considered
> trying to write TCP support from scratch.
> My plan for TCP support was always to integrate some existing stack like
> lwip into barebox to get a stack that has proven to work elsewhere. Also
> IPv6 support is still a pending feature which is becoming more and more
> interesting and we would get that for free with integrating an existing
> IP stack.
> Given that I am sceptical if we really want to follow the approach of
> developping TCP from scratch.
Yes... I agree that integrating a "proven" and field-tested TCP
implementation (including IPv6) is the saner solution, over rolling out
a custom implementation.

This is more a PoC and it was an excuse to take a deeper look at how TCP
works and what it requires.

> Nevertheless it's really cool to see how simple it could be ;) Nice
> stuff!
:)

> Sascha
> 
> 
> > 
> > Signed-off-by: Jules Maselbas <jmaselbas@kalray.eu>
> > ---
> >  common/misc.c |  12 +-
> >  include/net.h | 118 +++++++++++++++
> >  net/net.c     | 406 ++++++++++++++++++++++++++++++++++++++++++++++++++
> >  3 files changed, 531 insertions(+), 5 deletions(-)
> > 
> > diff --git a/common/misc.c b/common/misc.c
> > index 0f6de3e9e5..30e94f5a8b 100644
> > --- a/common/misc.c
> > +++ b/common/misc.c
> > @@ -57,6 +57,13 @@ const char *strerror(int errnum)
> >  	case	EPROBE_DEFER	: str = "Requested probe deferral"; break;
> >  	case	ELOOP		: str = "Too many symbolic links encountered"; break;
> >  	case	ENODATA		: str = "No data available"; break;
> > +#ifdef CONFIG_NET
> > +	case	ENETRESET	: str = "Network dropped connection because of reset"; break;
> > +	case	ECONNABORTED	: str = "Software caused connection abort"; break;
> > +	case	ECONNRESET	: str = "Connection reset by peer"; break;
> > +	case	ENOBUFS		: str = "No buffer space available"; break;
> > +	case	ECONNREFUSED	: str = "Connection refused"; break;
> > +#endif
> >  #if 0 /* These are probably not needed */
> >  	case	ENOTBLK		: str = "Block device required"; break;
> >  	case	EFBIG		: str = "File too large"; break;
> > @@ -79,11 +86,6 @@ const char *strerror(int errnum)
> >  	case	EAFNOSUPPORT	: str = "Address family not supported by protocol"; break;
> >  	case	EADDRINUSE	: str = "Address already in use"; break;
> >  	case	EADDRNOTAVAIL	: str = "Cannot assign requested address"; break;
> > -	case	ENETRESET	: str = "Network dropped connection because of reset"; break;
> > -	case	ECONNABORTED	: str = "Software caused connection abort"; break;
> > -	case	ECONNRESET	: str = "Connection reset by peer"; break;
> > -	case	ENOBUFS		: str = "No buffer space available"; break;
> > -	case	ECONNREFUSED	: str = "Connection refused"; break;
> >  	case	EHOSTDOWN	: str = "Host is down"; break;
> >  	case	EALREADY	: str = "Operation already in progress"; break;
> >  	case	EINPROGRESS	: str = "Operation now in progress"; break;
> > diff --git a/include/net.h b/include/net.h
> > index b50b6e76c8..76b64ccb21 100644
> > --- a/include/net.h
> > +++ b/include/net.h
> > @@ -143,6 +143,7 @@ struct ethernet {
> >  #define PROT_VLAN	0x8100		/* IEEE 802.1q protocol		*/
> >  
> >  #define IPPROTO_ICMP	 1	/* Internet Control Message Protocol	*/
> > +#define IPPROTO_TCP	 6	/* Transmission Control Protocol	*/
> >  #define IPPROTO_UDP	17	/* User Datagram Protocol		*/
> >  
> >  #define IP_BROADCAST    0xffffffff /* Broadcast IP aka 255.255.255.255 */
> > @@ -171,6 +172,67 @@ struct udphdr {
> >  	uint16_t	uh_sum;		/* udp checksum */
> >  } __attribute__ ((packed));
> >  
> > +/* pseudo header for checksum */
> > +struct psdhdr {
> > +	uint32_t	saddr;
> > +	uint32_t	daddr;
> > +	uint16_t	proto;
> > +	uint16_t	ttlen;
> > +} __attribute__ ((packed));
> > +
> > +struct tcphdr {
> > +	uint16_t	src;	/* source port */
> > +	uint16_t	dst;	/* destination port */
> > +	uint32_t	seq;	/* sequence number */
> > +	uint32_t	ack;	/* acknowledge number */
> > +	uint16_t 	doff_flag;	/* data offset and flags */
> > +#define TCP_DOFF_MASK	0xf
> > +#define TCP_DOFF_SHIFT	12
> > +#define TCP_FLAG_FIN	BIT(0)
> > +#define TCP_FLAG_SYN	BIT(1)
> > +#define TCP_FLAG_RST	BIT(2)
> > +#define TCP_FLAG_PSH	BIT(3)
> > +#define TCP_FLAG_ACK	BIT(4)
> > +#define TCP_FLAG_URG	BIT(5)
> > +#define TCP_FLAG_ECE	BIT(6)
> > +#define TCP_FLAG_CWR	BIT(7)
> > +#define TCP_FLAG_NS	BIT(8)
> > +#define TCP_FLAG_MASK	0x1ff
> > +	uint16_t	wnd;	/* window size */
> > +	uint16_t	sum;	/* header and data checksum */
> > +	uint16_t	urp;	/* urgent pointer (if URG is set) */
> > +	/* The options start here. */
> > +} __attribute__ ((packed));
> > +
> > +enum tcp_state {
> > +	TCP_CLOSED = 0,
> > +	TCP_LISTEN,
> > +	TCP_SYN_SENT,
> > +	TCP_SYN_RECV,
> > +	TCP_ESTABLISHED,
> > +	TCP_FIN_WAIT1,
> > +	TCP_FIN_WAIT2,
> > +	TCP_TIME_WAIT,
> > +	TCP_CLOSE_WAIT,
> > +	TCP_LAST_ACK,
> > +	TCP_CLOSING,
> > +};
> > +
> > +/* Transmission Control Block */
> > +struct tcb {
> > +	uint32_t snd_una;
> > +	uint32_t snd_nxt;
> > +	uint32_t snd_wnd;
> > +	uint16_t snd_urp;
> > +	uint32_t snd_wl1;
> > +	uint32_t snd_wl2;
> > +	uint32_t rcv_nxt;
> > +	uint32_t rcv_wnd;
> > +	uint16_t rcv_urp;
> > +	uint32_t iss;
> > +	uint32_t irs;
> > +};
> > +
> >  /*
> >   *	Address Resolution Protocol (ARP) header.
> >   */
> > @@ -264,6 +326,13 @@ struct eth_device *net_route(IPaddr_t ip);
> >  /* Do the work */
> >  void net_poll(void);
> >  
> > +static inline size_t net_tcp_data_offset(struct tcphdr *tcp)
> > +{
> > +	uint16_t doff;
> > +	doff = ntohs(tcp->doff_flag) >> TCP_DOFF_SHIFT;
> > +	return doff * sizeof(uint32_t);
> > +}
> > +
> >  static inline struct iphdr *net_eth_to_iphdr(char *pkt)
> >  {
> >  	return (struct iphdr *)(pkt + ETHER_HDR_SIZE);
> > @@ -274,6 +343,11 @@ static inline struct udphdr *net_eth_to_udphdr(char *pkt)
> >  	return (struct udphdr *)(net_eth_to_iphdr(pkt) + 1);
> >  }
> >  
> > +static inline struct tcphdr *net_eth_to_tcphdr(char *pkt)
> > +{
> > +	return (struct tcphdr *)(net_eth_to_iphdr(pkt) + 1);
> > +}
> > +
> >  static inline struct icmphdr *net_eth_to_icmphdr(char *pkt)
> >  {
> >  	return (struct icmphdr *)(net_eth_to_iphdr(pkt) + 1);
> > @@ -295,8 +369,28 @@ static inline int net_eth_to_udplen(char *pkt)
> >  	return ntohs(udp->uh_ulen) - 8;
> >  }
> >  
> > +static inline char *net_eth_to_tcp_payload(char *pkt)
> > +{
> > +	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
> > +	return ((char *)tcp) + net_tcp_data_offset(tcp);
> > +}
> > +
> > +static inline int net_eth_to_iplen(char *pkt)
> > +{
> > +	struct iphdr *ip = net_eth_to_iphdr(pkt);
> > +	return ntohs(ip->tot_len) - sizeof(struct iphdr);
> > +}
> > +
> > +static inline int net_eth_to_tcplen(char *pkt)
> > +{
> > +	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
> > +	return net_eth_to_iplen(pkt) - net_tcp_data_offset(tcp);
> > +}
> > +
> >  int net_checksum_ok(unsigned char *, int);	/* Return true if cksum OK	*/
> >  uint16_t net_checksum(unsigned char *, int);	/* Calculate the checksum	*/
> > +int tcp_checksum_ok(struct iphdr *ip, struct tcphdr *tcp, int len);
> > +uint16_t tcp_checksum(struct iphdr *ip, struct tcphdr *tcp, int len);
> >  
> >  /*
> >   * The following functions are a bit ugly, but necessary to deal with
> > @@ -459,12 +553,18 @@ struct net_connection {
> >  	struct ethernet *et;
> >  	struct iphdr *ip;
> >  	struct udphdr *udp;
> > +	struct tcphdr *tcp;
> >  	struct eth_device *edev;
> >  	struct icmphdr *icmp;
> >  	unsigned char *packet;
> >  	struct list_head list;
> >  	rx_handler_f *handler;
> >  	int proto;
> > +	int state;
> > +	int ret;
> > +	union {
> > +		struct tcb tcb;
> > +	};
> >  	void *priv;
> >  };
> >  
> > @@ -480,6 +580,13 @@ struct net_connection *net_udp_eth_new(struct eth_device *edev, IPaddr_t dest,
> >                                         uint16_t dport, rx_handler_f *handler,
> >                                         void *ctx);
> >  
> > +struct net_connection *net_tcp_new(IPaddr_t dest, uint16_t dport,
> > +		rx_handler_f *handler, void *ctx);
> > +
> > +struct net_connection *net_tcp_eth_new(struct eth_device *edev, IPaddr_t dest,
> > +                                       uint16_t dport, rx_handler_f *handler,
> > +                                       void *ctx);
> > +
> >  struct net_connection *net_icmp_new(IPaddr_t dest, rx_handler_f *handler,
> >  		void *ctx);
> >  
> > @@ -497,6 +604,17 @@ static inline void *net_udp_get_payload(struct net_connection *con)
> >  		sizeof(struct udphdr);
> >  }
> >  
> > +static inline void *net_tcp_get_payload(struct net_connection *con)
> > +{
> > +	return con->packet + sizeof(struct ethernet) + sizeof(struct iphdr) +
> > +		net_tcp_data_offset(con->tcp);
> > +}
> > +
> > +int net_tcp_listen(struct net_connection *con);
> > +int net_tcp_open(struct net_connection *con);
> > +int net_tcp_send(struct net_connection *con, int len);
> > +int net_tcp_close(struct net_connection *con);
> > +
> >  int net_udp_send(struct net_connection *con, int len);
> >  int net_icmp_send(struct net_connection *con, int len);
> >  
> > diff --git a/net/net.c b/net/net.c
> > index 9f799f252d..855bb8e4c2 100644
> > --- a/net/net.c
> > +++ b/net/net.c
> > @@ -47,6 +47,8 @@ static struct net_connection *net_ip_get_con(int proto, uint16_t port)
> >  			continue;
> >  		if (con->proto == IPPROTO_UDP && ntohs(con->udp->uh_sport) == port)
> >  			return con;
> > +		if (con->proto == IPPROTO_TCP && ntohs(con->tcp->src) == port)
> > +			return con;
> >  	}
> >  
> >  	return NULL;
> > @@ -99,6 +101,31 @@ uint16_t net_checksum(unsigned char *ptr, int len)
> >  	return xsum & 0xffff;
> >  }
> >  
> > +uint16_t tcp_checksum(struct iphdr *ip, struct tcphdr *tcp, int len)
> > +{
> > +	uint32_t xsum;
> > +	struct psdhdr pseudo;
> > +	size_t hdrsize = net_tcp_data_offset(tcp);
> > +
> > +	pseudo.saddr = ip->saddr;
> > +	pseudo.daddr = ip->daddr;
> > +	pseudo.proto = htons(ip->protocol);
> > +	pseudo.ttlen = htons(hdrsize + len);
> > +
> > +	xsum = net_checksum((void *)&pseudo, sizeof(struct psdhdr));
> > +	xsum += net_checksum((void *)tcp, hdrsize + len);
> > +
> > +	while (xsum > 0xffff)
> > +		xsum = (xsum & 0xffff) + (xsum >> 16);
> > +
> > +	return xsum;
> > +}
> > +
> > +int tcp_checksum_ok(struct iphdr *ip, struct tcphdr *tcp, int len)
> > +{
> > +	return tcp_checksum(ip, tcp, len) == 0xffff;
> > +}
> > +
> >  IPaddr_t getenv_ip(const char *name)
> >  {
> >  	IPaddr_t ip;
> > @@ -335,6 +362,11 @@ static uint16_t net_udp_new_localport(void)
> >  	return net_new_localport(IPPROTO_UDP);
> >  }
> >  
> > +static uint16_t net_tcp_new_localport(void)
> > +{
> > +	return net_new_localport(IPPROTO_TCP);
> > +}
> > +
> >  IPaddr_t net_get_serverip(void)
> >  {
> >  	IPaddr_t ip;
> > @@ -422,6 +454,7 @@ static struct net_connection *net_new(struct eth_device *edev, IPaddr_t dest,
> >  	con->et = (struct ethernet *)con->packet;
> >  	con->ip = (struct iphdr *)(con->packet + ETHER_HDR_SIZE);
> >  	con->udp = (struct udphdr *)(con->packet + ETHER_HDR_SIZE + sizeof(struct iphdr));
> > +	con->tcp = (struct tcphdr *)(con->packet + ETHER_HDR_SIZE + sizeof(struct iphdr));
> >  	con->icmp = (struct icmphdr *)(con->packet + ETHER_HDR_SIZE + sizeof(struct iphdr));
> >  	con->handler = handler;
> >  
> > @@ -452,6 +485,30 @@ out:
> >  	return ERR_PTR(ret);
> >  }
> >  
> > +struct net_connection *net_tcp_eth_new(struct eth_device *edev, IPaddr_t dest,
> > +				       uint16_t dport, rx_handler_f *handler,
> > +				       void *ctx)
> > +{
> > +	struct net_connection *con = net_new(edev, dest, handler, ctx);
> > +	uint16_t doff;
> > +
> > +	if (IS_ERR(con))
> > +		return con;
> > +
> > +	con->proto = IPPROTO_TCP;
> > +	con->state = TCP_CLOSED;
> > +	con->tcp->src = htons(net_tcp_new_localport());
> > +	con->tcp->dst = htons(dport);
> > +	con->tcp->seq = 0;
> > +	con->tcp->ack = 0;
> > +	doff = sizeof(struct tcphdr) / sizeof(uint32_t);
> > +	con->tcp->doff_flag = htons(doff << TCP_DOFF_SHIFT);
> > +	con->tcp->urp = 0;
> > +	con->ip->protocol = IPPROTO_TCP;
> > +
> > +	return con;
> > +}
> > +
> >  struct net_connection *net_udp_eth_new(struct eth_device *edev, IPaddr_t dest,
> >  				       uint16_t dport, rx_handler_f *handler,
> >  				       void *ctx)
> > @@ -475,6 +532,12 @@ struct net_connection *net_udp_new(IPaddr_t dest, uint16_t dport,
> >  	return net_udp_eth_new(NULL, dest, dport, handler, ctx);
> >  }
> >  
> > +struct net_connection *net_tcp_new(IPaddr_t dest, uint16_t dport,
> > +		rx_handler_f *handler, void *ctx)
> > +{
> > +	return net_tcp_eth_new(NULL, dest, dport, handler, ctx);
> > +}
> > +
> >  struct net_connection *net_icmp_new(IPaddr_t dest, rx_handler_f *handler,
> >  		void *ctx)
> >  {
> > @@ -514,6 +577,167 @@ int net_udp_send(struct net_connection *con, int len)
> >  	return net_ip_send(con, sizeof(struct udphdr) + len);
> >  }
> >  
> > +static int tcp_send(struct net_connection *con, int len, uint16_t flags)
> > +{
> > +	size_t hdr_size = net_tcp_data_offset(con->tcp);
> > +
> > +	con->tcp->doff_flag &= ~htons(TCP_FLAG_MASK);
> > +	con->tcp->doff_flag |= htons(flags);
> > +	con->tcp->sum = 0;
> > +	con->tcp->sum = ~tcp_checksum(con->ip, con->tcp, len);
> > +
> > +	return net_ip_send(con, hdr_size + len);
> > +}
> > +
> > +int net_tcp_send(struct net_connection *con, int len)
> > +{
> > +	struct tcb *tcb = &con->tcb;
> > +	uint16_t flag = 0;
> > +
> > +	if (con->proto != IPPROTO_TCP)
> > +		return -EPROTOTYPE;
> > +	switch (con->state) {
> > +	case TCP_CLOSED:
> > +		return -ENOTCONN;
> > +	case TCP_LISTEN:
> > +		/* TODO: proceed as open */
> > +		break;
> > +	case TCP_SYN_SENT:
> > +	case TCP_SYN_RECV:
> > +		/* queue request or "error:  insufficient resources". */
> > +		break;
> > +	case TCP_ESTABLISHED:
> > +	case TCP_CLOSE_WAIT:
> > +		/* proceed */
> > +		break;
> > +	case TCP_FIN_WAIT1:
> > +	case TCP_FIN_WAIT2:
> > +	case TCP_TIME_WAIT:
> > +	case TCP_LAST_ACK:
> > +	case TCP_CLOSING:
> > +		return -ESHUTDOWN;
> > +	}
> > +
> > +	con->tcp->seq = htonl(tcb->snd_nxt);
> > +	tcb->snd_nxt += len;
> > +	flag |= TCP_FLAG_PSH;
> > +	if (1 || ntohl(con->tcp->ack) < con->tcb.rcv_nxt) {
> > +		flag |= TCP_FLAG_ACK;
> > +		con->tcp->ack = htonl(con->tcb.rcv_nxt);
> > +	} else {
> > +		con->tcp->ack = 0;
> > +	}
> > +
> > +	return tcp_send(con, len, flag);
> > +}
> > +
> > +int net_tcp_listen(struct net_connection *con)
> > +{
> > +	if (con->proto != IPPROTO_TCP)
> > +		return -EPROTOTYPE;
> > +
> > +	con->state = TCP_LISTEN;
> > +	return -1;
> > +}
> > +
> > +int net_tcp_open(struct net_connection *con)
> > +{
> > +	struct tcphdr *tcp = net_eth_to_tcphdr(con->packet);
> > +	struct tcb *tcb = &con->tcb;
> > +	int ret;
> > +
> > +	if (con->proto != IPPROTO_TCP)
> > +		return -EPROTOTYPE;
> > +	switch (con->state) {
> > +	case TCP_CLOSED:
> > +	case TCP_LISTEN:
> > +		break;
> > +	case TCP_SYN_SENT:
> > +	case TCP_SYN_RECV:
> > +	case TCP_ESTABLISHED:
> > +	case TCP_FIN_WAIT1:
> > +	case TCP_FIN_WAIT2:
> > +	case TCP_TIME_WAIT:
> > +	case TCP_CLOSE_WAIT:
> > +	case TCP_LAST_ACK:
> > +	case TCP_CLOSING:
> > +		return -EISCONN;
> > +	}
> > +
> > +	/* use a window smaller than the MTU, as only one tcp segment packet
> > +	 * can be received at time */
> > +	tcb->rcv_wnd = 1024;
> > +	tcb->snd_wnd = 0;
> > +	tcb->iss = random32() + (get_time_ns() >> 10);
> > +	con->state = TCP_SYN_SENT;
> > +
> > +	tcp->wnd = htons(tcb->rcv_wnd);
> > +	tcp->seq = htonl(tcb->iss);
> > +	tcb->snd_una = tcb->iss;
> > +	tcb->snd_nxt = tcb->iss + 1;
> > +	ret = tcp_send(con, 0, TCP_FLAG_SYN);
> > +	if (ret)
> > +		return ret;
> > +
> > +	ret = wait_on_timeout(6000 * MSECOND, con->state == TCP_ESTABLISHED);
> > +	if (ret)
> > +		return -ETIMEDOUT;
> > +
> > +	return con->ret; // TODO: return 0 ?
> > +}
> > +
> > +int net_tcp_close(struct net_connection *con)
> > +{
> > +	struct tcphdr *tcp = net_eth_to_tcphdr(con->packet);
> > +	struct tcb *tcb = &con->tcb;
> > +	int ret;
> > +
> > +	if (con->proto != IPPROTO_TCP)
> > +		return -EPROTOTYPE;
> > +	switch (con->state) {
> > +	case TCP_CLOSED:
> > +		return -ENOTCONN;
> > +	case TCP_LISTEN:
> > +	case TCP_SYN_SENT:
> > +		con->state = TCP_CLOSED;
> > +		return 0;
> > +		break;
> > +	case TCP_SYN_RECV:
> > +	case TCP_ESTABLISHED:
> > +		/* wait for pending send */
> > +		con->state = TCP_FIN_WAIT1;
> > +		break;
> > +	case TCP_FIN_WAIT1:
> > +	case TCP_FIN_WAIT2:
> > +		/* error: connection closing */
> > +		return -1;
> > +	case TCP_TIME_WAIT:
> > +	case TCP_LAST_ACK:
> > +	case TCP_CLOSING:
> > +		/* error: connection closing */
> > +		return -1;
> > +	case TCP_CLOSE_WAIT:
> > +		/* queue close request after pending sends */
> > +		con->state = TCP_LAST_ACK;
> > +		break;
> > +	}
> > +
> > +	tcp->seq = htonl(tcb->snd_nxt);
> > +	tcp->ack = htonl(tcb->rcv_nxt);
> > +	tcb->snd_nxt += 1;
> > +	ret = tcp_send(con, 0, TCP_FLAG_FIN | TCP_FLAG_ACK);
> > +	if (ret)
> > +		return ret;
> > +
> > +	ret = wait_on_timeout(1000 * MSECOND, con->state == TCP_CLOSED);
> > +	if (ret)
> > +		return -ETIMEDOUT;
> > +
> > +	net_unregister(con);
> > +
> > +	return con->ret; // TODO: return 0 ?
> > +}
> > +
> >  int net_icmp_send(struct net_connection *con, int len)
> >  {
> >  	con->icmp->checksum = ~net_checksum((unsigned char *)con->icmp,
> > @@ -624,6 +848,186 @@ static int net_handle_udp(unsigned char *pkt, int len)
> >  	return -EINVAL;
> >  }
> >  
> > +static int net_handle_tcp(unsigned char *pkt, int len)
> > +{
> > +	size_t min_size = ETHER_HDR_SIZE + sizeof(struct iphdr);
> > +	struct net_connection *con;
> > +	struct iphdr *ip = net_eth_to_iphdr(pkt);
> > +	struct tcphdr *tcp = net_eth_to_tcphdr(pkt);
> > +	struct tcb *tcb;
> > +	uint16_t flag;
> > +	uint16_t doff;
> > +	uint32_t tcp_len;
> > +	uint32_t seg_len;
> > +	uint32_t seg_ack;
> > +	uint32_t seg_seq;
> > +	uint32_t seg_last;
> > +	uint32_t rcv_wnd;
> > +	uint32_t rcv_nxt;
> > +	int seg_accept = 0;
> > +
> > +	if (len < (min_size + sizeof(struct tcphdr)))
> > +		goto bad;
> > +	flag = ntohs(tcp->doff_flag) & TCP_FLAG_MASK;
> > +	doff = net_tcp_data_offset(tcp);
> > +	if (doff < sizeof(struct tcphdr))
> > +		goto bad;
> > +	if (len < (min_size + doff))
> > +		goto bad;
> > +
> > +	seg_ack = ntohl(tcp->ack);
> > +	seg_seq = ntohl(tcp->seq);
> > +	tcp_len = net_eth_to_tcplen(pkt);
> > +	seg_len = tcp_len;
> > +	seg_len += !!(flag & TCP_FLAG_FIN);
> > +	seg_len += !!(flag & TCP_FLAG_SYN);
> > +
> > +	if (!tcp_checksum_ok(ip, tcp, tcp_len))
> > +		goto bad;
> > +
> > +	con = net_ip_get_con(IPPROTO_TCP, ntohs(tcp->dst));
> > +	if (con == NULL)
> > +		goto bad;
> > +	tcb = &con->tcb;
> > +
> > +	/* segment arrives */
> > +	seg_last = seg_seq + seg_len - 1;
> > +	rcv_wnd = tcb->rcv_wnd;
> > +	rcv_nxt = tcb->rcv_nxt;
> > +
> > +	if (seg_len == 0 && rcv_wnd == 0)
> > +		seg_accept = seg_seq == rcv_nxt;
> > +	if (seg_len == 0 && rcv_wnd > 0)
> > +		seg_accept = rcv_nxt <= seg_seq && seg_seq < (rcv_nxt + rcv_wnd);
> > +	if (seg_len > 0 && rcv_wnd == 0)
> > +		seg_accept = 0; /* not acceptable */
> > +	if (seg_len > 0 && rcv_wnd > 0)
> > +		seg_accept = (rcv_nxt <= seg_seq && seg_seq < (rcv_nxt + rcv_wnd))
> > +			|| (rcv_nxt <= seg_last && seg_last < (rcv_nxt + rcv_wnd));
> > +
> > +	switch (con->state) {
> > +	case TCP_CLOSED:
> > +		if (flag & TCP_FLAG_RST) {
> > +			goto drop;
> > +		}
> > +		if (flag & TCP_FLAG_ACK) {
> > +			con->tcp->seq = 0;
> > +			con->tcp->ack = htonl(seg_seq + seg_len);
> > +			con->ret = tcp_send(con, 0, TCP_FLAG_RST | TCP_FLAG_ACK);
> > +		} else  {
> > +			con->tcp->seq = htonl(seg_ack);
> > +			con->ret = tcp_send(con, 0, TCP_FLAG_RST);
> > +		}
> > +		break;
> > +	case TCP_LISTEN:
> > +		/* TODO */
> > +		break;
> > +	case TCP_SYN_SENT:
> > +		if (flag & TCP_FLAG_ACK) {
> > +			if (seg_ack <= tcb->iss || seg_ack > tcb->snd_nxt) {
> > +				if (flag & TCP_FLAG_RST)
> > +					goto drop;
> > +				con->tcp->seq = htonl(seg_ack);
> > +				return tcp_send(con, 0, TCP_FLAG_RST);
> > +			}
> > +			if (tcb->snd_una > seg_ack || seg_ack > tcb->snd_nxt)
> > +				goto drop; /* unacceptable */
> > +		}
> > +		if (flag & TCP_FLAG_RST) {
> > +			con->state = TCP_CLOSED;
> > +			con->ret = -ENETRESET;
> > +			break;
> > +		}
> > +		if ((flag & TCP_FLAG_SYN) && !(flag & TCP_FLAG_RST)) {
> > +			tcb->irs = seg_seq;
> > +			tcb->rcv_nxt = seg_seq + 1;
> > +			if (flag & TCP_FLAG_ACK)
> > +				tcb->snd_una = seg_ack;
> > +			if (tcb->snd_una > tcb->iss) {
> > +				con->state = TCP_ESTABLISHED;
> > +				con->tcp->seq = htonl(tcb->snd_nxt);
> > +				con->tcp->ack = htonl(tcb->rcv_nxt);
> > +				con->ret = tcp_send(con, 0, TCP_FLAG_ACK);
> > +			} else {
> > +				con->state = TCP_SYN_RECV;
> > +				tcb->snd_nxt = tcb->iss + 1;
> > +				con->tcp->seq = htonl(tcb->iss);
> > +				con->tcp->ack = htonl(tcb->rcv_nxt);
> > +				con->ret = tcp_send(con, 0, TCP_FLAG_SYN | TCP_FLAG_ACK);
> > +			}
> > +		}
> > +		break;
> > +	case TCP_SYN_RECV:
> > +	case TCP_ESTABLISHED:
> > +		if (flag & TCP_FLAG_RST) {
> > +			/* TODO: if passive open then return to LISTEN */
> > +			con->state = TCP_CLOSED;
> > +			con->ret = -ECONNREFUSED;
> > +			break;
> > +		}
> > +		if (!seg_accept) {
> > +			/* segment is not acceptable, send an ack unless RST bit
> > +			 * is set (done above) */
> > +			con->tcp->seq = htonl(tcb->snd_nxt);
> > +			con->tcp->ack = htonl(tcb->rcv_nxt);
> > +			con->ret = tcp_send(con, 0, TCP_FLAG_ACK);
> > +			goto drop;
> > +		}
> > +		if (flag & TCP_FLAG_FIN && flag & TCP_FLAG_ACK)
> > +			con->state = TCP_CLOSE_WAIT;
> > +
> > +		if (flag & TCP_FLAG_ACK)
> > +			tcb->snd_una = seg_ack;
> > +
> > +		tcb->rcv_nxt += seg_len;
> > +		con->tcp->seq = htonl(tcb->snd_nxt);
> > +		if (seg_len) {
> > +			con->tcp->ack = htonl(tcb->rcv_nxt);
> > +			con->ret = tcp_send(con, 0, TCP_FLAG_ACK |
> > +					    /* send FIN+ACK if FIN is set */
> > +					    (flag & TCP_FLAG_FIN));
> > +		}
> > +		con->handler(con->priv, pkt, len);
> > +		break;
> > +	case TCP_FIN_WAIT1:
> > +		if (flag & TCP_FLAG_FIN)
> > +			con->state = TCP_CLOSING;
> > +		if (flag & TCP_FLAG_ACK)
> > +			tcb->snd_una = seg_ack;
> > +		/* fall-through */
> > +	case TCP_FIN_WAIT2:
> > +		tcb->rcv_nxt += seg_len;
> > +		con->tcp->seq = htonl(tcb->snd_nxt);
> > +		if (seg_len) {
> > +			con->tcp->ack = htonl(tcb->rcv_nxt);
> > +			con->ret = tcp_send(con, 0, TCP_FLAG_ACK);
> > +		}
> > +	case TCP_CLOSE_WAIT:
> > +		/* all segment queues should be flushed */
> > +		if (flag & TCP_FLAG_RST) {
> > +			con->state = TCP_CLOSED;
> > +			con->ret = -ENETRESET;
> > +			break;
> > +		}
> > +		break;
> > +	case TCP_CLOSING:
> > +		con->state = TCP_TIME_WAIT;
> > +	case TCP_LAST_ACK:
> > +	case TCP_TIME_WAIT:
> > +		if (flag & TCP_FLAG_RST) {
> > +			con->state = TCP_CLOSED;
> > +			con->ret = 0;
> > +		}
> > +		break;
> > +	}
> > +	return con->ret;
> > +drop:
> > +	return 0;
> > +bad:
> > +	net_bad_packet(pkt, len);
> > +	return 0;
> > +}
> > +
> >  static int ping_reply(struct eth_device *edev, unsigned char *pkt, int len)
> >  {
> >  	struct ethernet *et = (struct ethernet *)pkt;
> > @@ -711,6 +1115,8 @@ static int net_handle_ip(struct eth_device *edev, unsigned char *pkt, int len)
> >  		return net_handle_icmp(edev, pkt, len);
> >  	case IPPROTO_UDP:
> >  		return net_handle_udp(pkt, len);
> > +	case IPPROTO_TCP:
> > +		return net_handle_tcp(pkt, len);
> >  	}
> >  
> >  	return 0;
> > -- 
> > 2.17.1
> > 
> > 
> > 
> 
> -- 
> Pengutronix e.K.                           |                             |
> Steuerwalder Str. 21                       | http://www.pengutronix.de/  |
> 31137 Hildesheim, Germany                  | Phone: +49-5121-206917-0    |
> Amtsgericht Hildesheim, HRA 2686           | Fax:   +49-5121-206917-5555 |
> 
> 







^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2022-08-12 16:19 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-08-09 13:20 [RFC PATCH 1/5] net: Add a function to retrieve UDP connection Jules Maselbas
2022-08-09 13:20 ` [RFC PATCH 2/5] net: Implement source port randomization Jules Maselbas
2022-08-09 13:20 ` [RFC PATCH 3/5] net: Add simple TCP support Jules Maselbas
2022-08-12  7:04   ` Sascha Hauer
2022-08-12 16:17     ` Jules Maselbas
2022-08-09 13:20 ` [RFC PATCH 4/5] Add irc command Jules Maselbas
2022-08-09 13:20 ` [RFC PATCH 5/5] Add tcpdump command Jules Maselbas

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox