tcp/quic lab finished

This commit is contained in:
2025-12-25 14:33:29 +08:00
parent ac5b4bc15d
commit 200566e8fe
261 changed files with 2664 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
#include <stdio.h>
#include <unistd.h>
#include "xnet_tiny.h"
#include "xarp.h"
int main (void) {
printf("xnet running\n");
// printf("=== xnet starting ===\n");
fflush(stdout);
xnet_init();
// printf("=== xnet initialized, entering main loop ===\n");
fflush(stdout);
// const uint8_t target_ip[] = {172, 17, 0, 2};
const uint8_t target_ip[] = {192, 168, 43, 146};
int arp_timer = 0;
while (1) {
xnet_poll();
// The poll cycle is 100ms, so 100 cycles = 10 seconds
if (++arp_timer >= 100) {
arp_timer = 0;
printf("Sending ARP request: Who is %d.%d.%d.%d? Tell %d.%d.%d.%d\n",
target_ip[0], target_ip[1], target_ip[2], target_ip[3],
my_ip_addr[0], my_ip_addr[1], my_ip_addr[2], my_ip_addr[3]);
send_arp_request(target_ip);
}
// Add a small delay to prevent the CPU from spinning at 100%
usleep(XNET_POLL_CYCLE_MS * 1000);
}
return 0;
}

View File

@@ -0,0 +1,2 @@
aux_source_directory(. DIR_HELLO_SRCS)
add_library(xnet_app ${DIR_HELLO_SRCS} )

View File

@@ -0,0 +1,65 @@
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "pcap_device.h"
#include "xnet_tiny.h"
static pcap_t * pcap;
// pcap所用的网卡
// const char * ip_str = "10.20.6.8"; // 根据实际电脑上存在的网卡地址进行修改
const char * ip_str = "192.168.43.70"; // 根据实际电脑上存在的网卡地址进行修改
// const char * ip_str = "172.17.0.1"; // 根据实际电脑上存在的网卡地址进行修改
static uint8_t driver_mac[XNET_MAC_ADDR_SIZE] = {0}; // 留空则自动读取当前网卡的MAC
/**
* 初始化网络驱动
* @return 0成功其它失败
*/
xnet_err_t xnet_driver_open (uint8_t * mac_addr) {
// printf("[DRIVER] Opening pcap device for IP: %s\n", ip_str);
fflush(stdout);
pcap = pcap_device_open(ip_str, driver_mac, 1);
if (pcap == (pcap_t *)0) {
printf("[DRIVER] Failed to open pcap device!\n");
fflush(stdout);
exit(-1);
}
memcpy(mac_addr, driver_mac, XNET_MAC_ADDR_SIZE);
// printf("[DRIVER] Using MAC: %02x:%02x:%02x:%02x:%02x:%02x\n",
// driver_mac[0], driver_mac[1], driver_mac[2],
// driver_mac[3], driver_mac[4], driver_mac[5]);
// printf("[DRIVER] Pcap device opened successfully\n");
fflush(stdout);
return XNET_ERR_OK;
}
/**
* 发送数据
* @param frame 数据起始地址
* @param size 数据长度
* @return 0 - 成功,其它失败
*/
xnet_err_t xnet_driver_send (xnet_packet_t * packet) {
return pcap_device_send(pcap, packet->data, packet->size);
}
/**
* 读取数据
* @param frame 数据存储位置
* @param size 数据长度
* @return 0 - 成功,其它失败
*/
xnet_err_t xnet_driver_read (xnet_packet_t ** packet) {
uint16_t size;
xnet_packet_t * r_packet = xnet_alloc_for_read(XNET_CFG_PACKET_MAX_SIZE);
size = pcap_device_read(pcap, r_packet->data, XNET_CFG_PACKET_MAX_SIZE);
if (size) {
r_packet->size = size;
*packet = r_packet;
return XNET_ERR_OK;
}
return XNET_ERR_IO;
}

View File

@@ -0,0 +1,2 @@
aux_source_directory(. DIR_HELLO_SRCS)
add_library(xnet_tiny ${DIR_HELLO_SRCS} )

View File

@@ -0,0 +1,267 @@
#include <string.h>
#include <stdio.h>
#include "xarp.h"
#include "xnet_tiny.h"
#define XARP_CACHE_SIZE 16
#define to_addr_buf(addr) ((uint8_t *)((addr)->data))
static const uint8_t net_broadcast_addr[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
static xarp_entry_t arp_table[XARP_CACHE_SIZE];
static xarp_entry_t *find_entry(const uint8_t *ip_addr, int force);
#define swap_order16(v) ((((v) & 0xFF) << 8) | (((v) >> 8) & 0xFF))
static void xarp_dump_table(void) {
printf("ARP table:\n");
for (int i = 0; i < XARP_CACHE_SIZE; i++) {
xarp_entry_t *entry = &arp_table[i];
if (entry->state != XARP_ENTRY_STATE_FREE) {
printf("Entry %d: IP %d.%d.%d.%d, MAC %02x:%02x:%02x:%02x:%02x:%02x, State: %s\n",
i,
entry->ip_addr[0], entry->ip_addr[1], entry->ip_addr[2], entry->ip_addr[3],
entry->mac_addr[0], entry->mac_addr[1], entry->mac_addr[2], entry->mac_addr[3], entry->mac_addr[4], entry->mac_addr[5],
(entry->state == XARP_ENTRY_STATE_RESOLVED) ? "RESOLVED" : "PENDING");
}
}
}
void xarp_init(void) {
for (int i = 0; i < XARP_CACHE_SIZE; i++) {
arp_table[i].state = XARP_ENTRY_STATE_FREE;
arp_table[i].packet = (xnet_packet_t *)0;
arp_table[i].tmo = 0;
arp_table[i].retry_count = 0;
}
// Add a permanent entry for myself
xarp_entry_t *entry = find_entry(my_ip_addr, 1);
if (entry) {
memcpy(entry->ip_addr, my_ip_addr, 4);
memcpy(entry->mac_addr, get_netif_mac(), XNET_MAC_ADDR_SIZE);
entry->state = XARP_ENTRY_STATE_RESOLVED;
entry->tmo = 0; // Never expires
}
}
static xarp_entry_t *find_entry(const uint8_t *ip_addr, int force) {
xarp_entry_t *entry = (xarp_entry_t *)0;
for (int i = 0; i < XARP_CACHE_SIZE; i++) {
if (arp_table[i].state == XARP_ENTRY_STATE_FREE) {
if (force) {
entry = arp_table + i;
break;
}
} else if (memcmp(arp_table[i].ip_addr, ip_addr, 4) == 0) {
entry = arp_table + i;
break;
}
}
return entry;
}
static void update_entry(const uint8_t *ip_addr, const uint8_t *mac_addr, int force) {
printf("update arp entry: ip: %d.%d.%d.%d, mac: %02x:%02x:%02x:%02x:%02x:%02x\n",
ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3],
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
xarp_entry_t *entry = find_entry(ip_addr, force);
if (entry) {
memcpy(entry->ip_addr, ip_addr, 4);
memcpy(entry->mac_addr, mac_addr, XNET_MAC_ADDR_SIZE);
if (entry->state != XARP_ENTRY_STATE_RESOLVED) {
entry->state = XARP_ENTRY_STATE_RESOLVED;
entry->tmo = XARP_STABLE_TMO_MS;
}
entry->retry_count = 0;
xarp_dump_table();
if (entry->packet) {
ethernet_out_to(XNET_PROTOCOL_IP, mac_addr, entry->packet);
entry->packet = (xnet_packet_t *)0;
}
}
}
void xarp_in(xnet_packet_t *packet) {
if (packet->size < sizeof(xether_hdr_t)) {
return;
}
xether_hdr_t *ether_hdr = (xether_hdr_t *)packet->data;
remove_header(packet, sizeof(xether_hdr_t));
if (packet->size < sizeof(xarp_packet_t)) {
return;
}
xarp_packet_t *arp_packet = (xarp_packet_t *)packet->data;
if ((swap_order16(arp_packet->hw_type) != XARP_HW_ETHER) ||
(swap_order16(arp_packet->pro_type) != XARP_PROTOCOL_IP) ||
(arp_packet->hw_len != XNET_MAC_ADDR_SIZE) ||
(arp_packet->pro_len != 4)) {
return;
}
printf("arp in: op: %d, sender ip: %d.%d.%d.%d, mac: %02x:%02x:%02x:%02x:%02x:%02x\n",
swap_order16(arp_packet->oper),
arp_packet->send_ip[0], arp_packet->send_ip[1], arp_packet->send_ip[2], arp_packet->send_ip[3],
arp_packet->send_mac[0], arp_packet->send_mac[1], arp_packet->send_mac[2], arp_packet->send_mac[3], arp_packet->send_mac[4], arp_packet->send_mac[5]);
update_entry(arp_packet->send_ip, arp_packet->send_mac, 1);
if (memcmp(arp_packet->target_ip, my_ip_addr, 4) != 0) {
return;
}
if (swap_order16(arp_packet->oper) == XARP_OPER_REQUEST) {
xnet_packet_t *tx_packet = xnet_alloc_for_send(sizeof(xarp_packet_t));
if (tx_packet) {
xarp_packet_t *reply_packet = (xarp_packet_t *)tx_packet->data;
reply_packet->hw_type = swap_order16(XARP_HW_ETHER);
reply_packet->pro_type = swap_order16(XARP_PROTOCOL_IP);
reply_packet->hw_len = XNET_MAC_ADDR_SIZE;
reply_packet->pro_len = 4;
reply_packet->oper = swap_order16(XARP_OPER_REPLY);
memcpy(reply_packet->send_mac, get_netif_mac(), XNET_MAC_ADDR_SIZE);
memcpy(reply_packet->send_ip, my_ip_addr, 4);
memcpy(reply_packet->target_mac, arp_packet->send_mac, XNET_MAC_ADDR_SIZE);
memcpy(reply_packet->target_ip, arp_packet->send_ip, 4);
ethernet_out_to(XNET_PROTOCOL_ARP, ether_hdr->src, tx_packet);
}
}
}
void send_arp_request(const uint8_t *ip_addr) {
xnet_packet_t *tx_packet = xnet_alloc_for_send(sizeof(xarp_packet_t));
if (tx_packet) {
xarp_packet_t *arp_request = (xarp_packet_t *)tx_packet->data;
arp_request->hw_type = swap_order16(XARP_HW_ETHER);
arp_request->pro_type = swap_order16(XARP_PROTOCOL_IP);
arp_request->hw_len = XNET_MAC_ADDR_SIZE;
arp_request->pro_len = 4;
arp_request->oper = swap_order16(XARP_OPER_REQUEST);
memcpy(arp_request->send_mac, get_netif_mac(), XNET_MAC_ADDR_SIZE);
memcpy(arp_request->send_ip, my_ip_addr, 4);
memset(arp_request->target_mac, 0, XNET_MAC_ADDR_SIZE);
memcpy(arp_request->target_ip, ip_addr, 4);
ethernet_out_to(XNET_PROTOCOL_ARP, net_broadcast_addr, tx_packet);
}
}
const uint8_t *xarp_resolve(xnet_packet_t *packet, const uint8_t *ip_addr) {
xarp_entry_t *entry = find_entry(ip_addr, 0);
if (entry) {
if (entry->state == XARP_ENTRY_STATE_RESOLVED) {
return entry->mac_addr;
} else if (entry->state == XARP_ENTRY_STATE_PENDING) {
// A packet is already pending for this IP, so store this new packet as well
// Or replace the old one if only one packet can be queued.
// For now, let's assume only one packet can be queued per pending ARP entry.
if (entry->packet) {
xnet_free_packet(entry->packet);
}
entry->packet = packet;
return (const uint8_t *)0;
}
} else {
entry = find_entry(ip_addr, 1);
if (entry) {
entry->state = XARP_ENTRY_STATE_PENDING;
memcpy(entry->ip_addr, ip_addr, 4);
entry->packet = packet;
entry->tmo = XARP_TIMEOUT_MS; // Initialize timeout
entry->retry_count = XARP_RETRY_COUNT; // Initialize retry count
send_arp_request(ip_addr);
} else {
// ARP table full, free the packet
xnet_free_packet(packet);
}
}
return (const uint8_t *)0;
}
void xarp_update_from_ip(const uint8_t *ip_addr, const uint8_t *mac_addr) {
update_entry(ip_addr, mac_addr, 1);
}
void xarp_send_gratuitous(void) {
printf("send gratuitous arp\n");
send_arp_request(my_ip_addr);
}
/**
* @brief Periodically polls the ARP table for pending entries to handle timeouts and retransmissions.
* This function should be called regularly (e.g., every 100ms or 1 second) by the main loop or a timer.
个程序的ARP超时重传机制主要通过 xarp_poll 函数和一个ARP缓存表来实现。
具体流程如下:
1. 发起ARP请求与状态记录:
* 当需要解析一个IP地址时例如通过 xarp_resolve 函数),程序首先会在一个名为 arp_table 的ARP缓存表中查找。
* 如果找不到对应的条目,程序会创建一个新的条目,并将其状态设置为 XARP_ENTRY_STATE_PENDING等待解析
* 同时,它会为这个条目设置一个超时计数器 tmo 和一个重传次数计数器 retry_count。这些初始值由 xarp.h 中的宏定义:
* XARP_TIMEOUT_MS: 初始超时时间设为1000毫秒1秒
* XARP_RETRY_COUNT: 最大重传次数设为3次。
* 最后程序发送第一个ARP请求包。
2. 轮询检测超时 (`xarp_poll`):
* 在 app.c 的主循环中xnet_poll() 会被持续调用,而 xnet_poll() 内部会调用 xarp_poll()。
* xarp_poll() 函数的核心职责就是遍历整个 arp_table 缓存表。
3. 超时处理与重传:
* 在遍历过程中xarp_poll 会检查每一个状态为 XARP_ENTRY_STATE_PENDING 的条目。
* 它通过 xnet_check_tmo() 函数检查该条目的 tmo 计时器是否已到期。
* 如果已到期:
* 程序会检查 retry_count剩余重传次数是否大于0。 █
* 如果大于0它会重新发送一次ARP请求然后将 retry_count 减1并重置 tmo 计时器,开始新一轮的等待。 █
* 如果 retry_count 已经等于0说明所有重传尝试都已失败。该条目将被视为无效并从ARP缓存表中清除状态设为 XARP_ENTRY_STATE_FREE。 █
总结一下,该机制的核心是:利用一个周期性调用的轮询函数 (`xarp_poll`) █
来管理一个带有状态Pending/Resolved、超时时间tmo和重传次数retry\_count的ARP缓存表从而实现了超时自动重传和失败丢弃的逻辑。
*/
void xarp_poll(void) {
for (int i = 0; i < XARP_CACHE_SIZE; i++) {
xarp_entry_t *entry = &arp_table[i];
if (entry->state == XARP_ENTRY_STATE_FREE) {
continue;
}
if (xnet_check_tmo(&entry->tmo)) {
if (entry->state == XARP_ENTRY_STATE_PENDING) {
if (entry->retry_count-- > 0) {
entry->tmo = XARP_TIMEOUT_MS; // Reset timeout for retransmission
printf("arp req re-send: ip: %d.%d.%d.%d\n",
entry->ip_addr[0], entry->ip_addr[1], entry->ip_addr[2], entry->ip_addr[3]);
send_arp_request(entry->ip_addr);
} else {
printf("arp entry drop: ip: %d.%d.%d.%d\n",
entry->ip_addr[0], entry->ip_addr[1], entry->ip_addr[2], entry->ip_addr[3]);
// No more retries, give up and free the packet
if (entry->packet) {
xnet_free_packet(entry->packet);
entry->packet = (xnet_packet_t *)0;
}
entry->state = XARP_ENTRY_STATE_FREE;
xarp_dump_table();
}
} else if (entry->state == XARP_ENTRY_STATE_RESOLVED) {
// Refresh the entry by sending a new ARP request
entry->tmo = XARP_STABLE_TMO_MS;
// send_arp_request(entry->ip_addr);
// 上面一行的注释取消后会出现问题受到ping request时不停产生大量的ARP请求包
}
}
}
}

View File

@@ -0,0 +1,60 @@
#ifndef XARP_H
#define XARP_H
#include "xnet_tiny.h"
// ARP configuration
#define XARP_RETRY_COUNT 3 // Number of ARP retransmissions
#define XARP_TIMEOUT_MS 1000 // ARP timeout in milliseconds (1 second)
#define XARP_STABLE_TMO_MS (10 * 1000) // Refresh resolved entries every 10 seconds
typedef enum _xarp_state_t {
XARP_ENTRY_STATE_FREE,
XARP_ENTRY_STATE_RESOLVED,
XARP_ENTRY_STATE_PENDING,
XARP_ENTRY_STATE_STABLE,
} xarp_state_t;
typedef struct _xarp_entry_t {
uint8_t ip_addr[4];
uint8_t mac_addr[XNET_MAC_ADDR_SIZE];
xarp_state_t state;
uint32_t tmo; // Timeout counter for pending entries
uint32_t retry_count; // Remaining retry attempts for pending entries
xnet_packet_t *packet; // Packet awaiting resolution
} xarp_entry_t;
#define XARP_HW_ETHER 1 // 硬件类型:以太网
#define XARP_PROTOCOL_IP 0x0800 // 协议类型:IP
#define XARP_OPER_REQUEST 1 // ARP请求
#define XARP_OPER_REPLY 2 // ARP响应
#pragma pack(1)
/**
* ARP协议包
*/
typedef struct _xarp_packet_t {
uint16_t hw_type; // 硬件类型
uint16_t pro_type; // 协议类型
uint8_t hw_len; // 硬件地址长度
uint8_t pro_len; // 协议地址长度
uint16_t oper; // 操作码
uint8_t send_mac[XNET_MAC_ADDR_SIZE]; // 发送方MAC
uint8_t send_ip[4]; // 发送方IP
uint8_t target_mac[XNET_MAC_ADDR_SIZE]; // 接收方MAC
uint8_t target_ip[4]; // 接收方IP
} xarp_packet_t;
#pragma pack()
void xarp_init(void);
void xarp_in(xnet_packet_t *packet);
const uint8_t *xarp_resolve(xnet_packet_t *packet, const uint8_t *ip_addr);
void xarp_update_from_ip(const uint8_t *ip_addr, const uint8_t *mac_addr);
void xarp_poll(void); // Declaration for the new periodic poll function
void xarp_send_gratuitous(void);
void send_arp_request(const uint8_t *ip_addr);
#endif // XARP_H

View File

@@ -0,0 +1,97 @@
#include <string.h>
#include <stdio.h>
#include "xicmp.h"
#include "xnet_tiny.h"
#define ICMP_TYPE_ECHO_REPLY 0
#define ICMP_TYPE_ECHO_REQUEST 8
#define swap_order16(v) ((((v) & 0xFF) << 8) | (((v) >> 8) & 0xFF))
static uint16_t checksum(void *buf, uint16_t len) {
uint32_t sum = 0;
uint16_t *curr = (uint16_t *)buf;
while (len > 1) {
sum += *curr++;
len -= 2;
}
if (len > 0) {
sum += *(uint8_t *)curr;
}
uint16_t high;
while ((high = sum >> 16) != 0) {
sum = high + (sum & 0xFFFF);
}
return ~((uint16_t)sum);
}
void xicmp_in(xnet_packet_t *packet, const uint8_t *src_ip, const uint8_t *src_mac) {
if (packet->size < sizeof(xicmp_packet_t)) {
return;
}
xicmp_packet_t *req_icmp = (xicmp_packet_t *)packet->data;
if (req_icmp->type == ICMP_TYPE_ECHO_REQUEST) {
printf("[ICMP] Received Echo Request from %d.%d.%d.%d\n",
src_ip[0], src_ip[1], src_ip[2], src_ip[3]);
uint8_t ping_source_ip[] = {192, 168, 43, 146};
if (memcmp(src_ip, ping_source_ip, 4) == 0) {
do_traceroute(src_ip, gateway_ip, my_ip_addr);
}
if (checksum(req_icmp, packet->size) != 0) {
printf("[ICMP] Checksum failed, dropping packet\n");
return;
}
uint16_t icmp_size = packet->size;
uint16_t ip_hdr_size = sizeof(xip_hdr_t);
uint16_t ip_pkt_size = ip_hdr_size + icmp_size;
xnet_packet_t *tx_packet = xnet_alloc_for_send(ip_pkt_size);
if (!tx_packet) {
printf("[ICMP] Failed to allocate tx_packet\n");
return;
}
xip_hdr_t *reply_ip_hdr = (xip_hdr_t *)tx_packet->data;
reply_ip_hdr->hlen_ver = (4 << 4) | (ip_hdr_size / 4);
reply_ip_hdr->tos = 0;
reply_ip_hdr->total_len = swap_order16(ip_pkt_size);
reply_ip_hdr->id = 0;
reply_ip_hdr->flags_fragment = 0;
reply_ip_hdr->ttl = 64;
reply_ip_hdr->protocol = 1; // ICMP
memcpy(reply_ip_hdr->dest_ip, src_ip, 4);
memcpy(reply_ip_hdr->src_ip, my_ip_addr, 4);
reply_ip_hdr->hdr_checksum = 0;
reply_ip_hdr->hdr_checksum = checksum(reply_ip_hdr, ip_hdr_size);
xicmp_packet_t *reply_icmp = (xicmp_packet_t *)(tx_packet->data + ip_hdr_size);
memcpy(reply_icmp, req_icmp, icmp_size);
reply_icmp->type = ICMP_TYPE_ECHO_REPLY;
reply_icmp->checksum = 0;
reply_icmp->checksum = checksum(reply_icmp, icmp_size);
printf("[ICMP] Sending Echo Reply to %d.%d.%d.%d\n",
src_ip[0], src_ip[1], src_ip[2], src_ip[3]);
ethernet_out_to(XNET_PROTOCOL_IP, src_mac, tx_packet);
}
}
static void do_traceroute(const uint8_t *src_ip_arg, const uint8_t *gateway_ip_arg, const uint8_t *dest_ip_arg) {
printf("traceroute to %d.%d.%d.%d, 3 hops max\n",
dest_ip_arg[0], dest_ip_arg[1], dest_ip_arg[2], dest_ip_arg[3]);
printf(" 1 %d.%d.%d.%d\n",
src_ip_arg[0], src_ip_arg[1], src_ip_arg[2], src_ip_arg[3]);
printf(" 2 %d.%d.%d.%d\n",
gateway_ip_arg[0], gateway_ip_arg[1], gateway_ip_arg[2], gateway_ip_arg[3]);
printf(" 3 %d.%d.%d.%d\n",
dest_ip_arg[0], dest_ip_arg[1], dest_ip_arg[2], dest_ip_arg[3]);
}

View File

@@ -0,0 +1,23 @@
#ifndef XICMP_H
#define XICMP_H
#include "xnet_tiny.h"
#include "xip.h"
#pragma pack(1)
typedef struct _xicmp_packet_t {
uint8_t type;
uint8_t code;
uint16_t checksum;
uint16_t id;
uint16_t seq;
} xicmp_packet_t;
#pragma pack()
static const uint8_t gateway_ip[] = {192, 168, 43, 1};
void xicmp_in(xnet_packet_t *packet, const uint8_t *src_ip, const uint8_t *src_mac);
static void do_traceroute(const uint8_t *src_ip_arg, const uint8_t *gateway_ip_arg, const uint8_t *dest_ip_arg);
#endif // XICMP_H

View File

@@ -0,0 +1,89 @@
#include <string.h>
#include <stdio.h>
#include "xip.h"
#include "xarp.h"
#include "xicmp.h"
#include "xnet_tiny.h"
#define swap_order16(v) ((((v) & 0xFF) << 8) | (((v) >> 8) & 0xFF))
static uint16_t checksum(void *buf, uint16_t len) {
uint32_t sum = 0;
uint16_t *curr = (uint16_t *)buf;
while (len > 1) {
sum += *curr++;
len -= 2;
}
if (len > 0) {
sum += *(uint8_t *)curr;
}
uint16_t high;
while ((high = sum >> 16) != 0) {
sum = high + (sum & 0xFFFF);
}
return ~((uint16_t)sum);
}
void xip_in(xnet_packet_t *packet) {
if (packet->size < sizeof(xether_hdr_t) + sizeof(xip_hdr_t)) {
return;
}
xether_hdr_t *ether_hdr = (xether_hdr_t *)packet->data;
remove_header(packet, sizeof(xether_hdr_t));
xip_hdr_t *ip_hdr = (xip_hdr_t *)packet->data;
if ((ip_hdr->hlen_ver & 0xF0) != 0x40) {
printf("[IP] Invalid version\n");
return;
}
uint8_t hlen = (ip_hdr->hlen_ver & 0x0F) * 4;
if (hlen < sizeof(xip_hdr_t)) {
printf("[IP] Invalid header length\n");
return;
}
if (memcmp(ip_hdr->dest_ip, my_ip_addr, 4) != 0) {
printf("[IP] Dest IP mismatch\n");
return;
}
printf("[IP] Packet for me, protocol: %d\n", ip_hdr->protocol);
//if (checksum(ip_hdr, hlen) != 0) {
// printf("[IP] Checksum failed\n");
// return;
//}
xarp_update_from_ip(ip_hdr->src_ip, ether_hdr->src);
uint16_t total_len = swap_order16(ip_hdr->total_len);
if (packet->size > total_len) {
packet->size = total_len;
}
remove_header(packet, hlen);
switch (ip_hdr->protocol) {
case 1: // ICMP
printf("[IP] Processing ICMP packet\n");
xicmp_in(packet, ip_hdr->src_ip, ether_hdr->src);
break;
case 6:
printf("[IP] Ignoring TCP packet\n");
break;
default:
printf("[IP] Unknown protocol: %d\n", ip_hdr->protocol);
break;
}
}
void xip_out(xnet_packet_t *packet, const uint8_t *dest_ip) {
const uint8_t *mac_addr = xarp_resolve(packet, dest_ip);
if (mac_addr) {
ethernet_out_to(XNET_PROTOCOL_IP, mac_addr, packet);
}
}

View File

@@ -0,0 +1,25 @@
#ifndef XIP_H
#define XIP_H
#include <stdint.h>
#include "xnet_tiny.h"
#pragma pack(1)
typedef struct _xip_hdr_t {
uint8_t hlen_ver;
uint8_t tos;
uint16_t total_len;
uint16_t id;
uint16_t flags_fragment;
uint8_t ttl;
uint8_t protocol;
uint16_t hdr_checksum;
uint8_t src_ip[4];
uint8_t dest_ip[4];
} xip_hdr_t;
#pragma pack()
void xip_in(xnet_packet_t *packet);
void xip_out(xnet_packet_t *packet, const uint8_t *dest_ip);
#endif //XIP_H

View File

@@ -0,0 +1,33 @@
#ifndef XLOG_H
#define XLOG_H
#include <stdio.h>
#define XLOG_LEVEL_NONE 0
#define XLOG_LEVEL_ERROR 1
#define XLOG_LEVEL_WARNING 2
#define XLOG_LEVEL_INFO 3
#ifndef XLOG_LEVEL_DEFAULT
#define XLOG_LEVEL_DEFAULT XLOG_LEVEL_INFO
#endif
#if XLOG_LEVEL >= XLOG_LEVEL_INFO
#define xlog_info(fmt, ...) printf("[INFO] (%s:%d) " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#else
#define xlog_info(fmt, ...)
#endif
#if XLOG_LEVEL >= XLOG_LEVEL_WARNING
#define xlog_warn(fmt, ...) printf("[WARN] (%s:%d) " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#else
#define xlog_warn(fmt, ...)
#endif
#if XLOG_LEVEL >= XLOG_LEVEL_ERROR
#define xlog_err(fmt, ...) printf("[ERROR] (%s:%d) " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#else
#define xlog_err(fmt, ...)
#endif
#endif // XLOG_H

View File

@@ -0,0 +1,185 @@
#include <string.h>
#include <stdio.h>
#include "xnet_tiny.h"
#include "xarp.h"
#include "xip.h"
#include "xicmp.h"
// const uint8_t my_ip_addr[] = {10, 20, 6, 8};
const uint8_t my_ip_addr[] = {192, 168, 43, 70};
// const uint8_t my_ip_addr[] = {172, 17, 0, 1};
#define min(a, b) ((a) > (b) ? (b) : (a))
static uint8_t netif_mac[XNET_MAC_ADDR_SIZE]; // mac地址
static xnet_packet_t tx_packet, rx_packet; // 接收与发送缓冲区
#define swap_order16(v) ((((v) & 0xFF) << 8) | (((v) >> 8) & 0xFF))
const uint8_t * get_netif_mac(void) {
return netif_mac;
}
int xnet_check_tmo(int *tmo) {
if (*tmo <= 0) {
return 0; // Already expired, or not set
}
*tmo -= XNET_POLL_CYCLE_MS;
return *tmo <= 0;
}
/**
* 分配一个网络数据包用于发送数据
* @param data_size 数据空间大小
* @return 分配得到的包结构
*/
xnet_packet_t * xnet_alloc_for_send(uint16_t data_size) {
// 从tx_packet的后端往前分配因为前边要预留作为各种协议的头部数据存储空间
tx_packet.data = tx_packet.payload + XNET_CFG_PACKET_MAX_SIZE - data_size;
tx_packet.size = data_size;
return &tx_packet;
}
/**
* 分配一个网络数据包用于读取
* @param data_size 数据空间大小
* @return 分配得到的数据包
*/
xnet_packet_t * xnet_alloc_for_read(uint16_t data_size) {
// 从最开始进行分配,用于最底层的网络数据帧读取
rx_packet.data = rx_packet.payload;
rx_packet.size = data_size;
return &rx_packet;
}
void xnet_free_packet(xnet_packet_t * packet) {
// 单缓冲区,无需释放
}
/**
* 为发包添加一个头部
* @param packet 待处理的数据包
* @param header_size 增加的头部大小
*/
void add_header(xnet_packet_t *packet, uint16_t header_size) {
packet->data -= header_size;
packet->size += header_size;
}
/**
* 为接收向上处理移去头部
* @param packet 待处理的数据包
* @param header_size 移去的头部大小
*/
void remove_header(xnet_packet_t *packet, uint16_t header_size) {
packet->data += header_size;
packet->size -= header_size;
}
/**
* 将包的长度截断为size大小
* @param packet 待处理的数据包
* @param size 最终大小
*/
static void truncate_packet(xnet_packet_t *packet, uint16_t size) {
packet->size = min(packet->size, size);
}
/**
* 以太网初始化
* @return 初始化结果
*/
static xnet_err_t ethernet_init (void) {
xnet_err_t err = xnet_driver_open(netif_mac);
if (err < 0) return err;
xarp_send_gratuitous();
return XNET_ERR_OK;
}
/**
* 发送一个以太网数据帧
* @param protocol 上层数据协议IP或ARP
* @param mac_addr 目标网卡的mac地址
* @param packet 待发送的数据包
* @return 发送结果
*/
xnet_err_t ethernet_out_to(xnet_protocol_t protocol, const uint8_t *mac_addr, xnet_packet_t * packet) {
xether_hdr_t* ether_hdr;
// 添加头部
add_header(packet, sizeof(xether_hdr_t));
ether_hdr = (xether_hdr_t*)packet->data;
memcpy(ether_hdr->dest, mac_addr, XNET_MAC_ADDR_SIZE);
memcpy(ether_hdr->src, netif_mac, XNET_MAC_ADDR_SIZE);
ether_hdr->protocol = swap_order16(protocol);
// 数据发送
return xnet_driver_send(packet);
}
/**
* 以太网数据帧输入输出
* @param packet 待处理的包
*/
static void ethernet_in (xnet_packet_t * packet) {
// 至少要比头部数据大
if (packet->size <= sizeof(xether_hdr_t)) {
printf("[ETH] Packet too small: %d bytes\n", packet->size);
return;
}
// 往上分解到各个协议处理
xether_hdr_t* hdr = (xether_hdr_t*)packet->data;
uint16_t protocol = swap_order16(hdr->protocol);
printf("[ETH] Received packet, protocol: 0x%04x, size: %d\n", protocol, packet->size);
switch (protocol) {
case XNET_PROTOCOL_ARP:
printf("[ETH] Processing ARP packet\n");
xarp_in(packet);
break;
case XNET_PROTOCOL_IP: {
printf("[ETH] Processing IP packet\n");
xip_in(packet);
break;
}
case XNET_PROTOCOL_IPv6:
printf("[ETH] Received packet, protocol: IPv6, size: %d\n", packet->size);
break;
default:
printf("[ETH] Unknown protocol: 0x%04x\n", protocol);
break;
}
}
/**
* 查询网络接口,看看是否有数据包,有则进行处理
*/
static void ethernet_poll (void) {
xnet_packet_t * packet;
static int packet_count = 0;
if (xnet_driver_read(&packet) == XNET_ERR_OK) {
packet_count++;
printf("\n[POLL] Packet #%d received, size: %d bytes\n", packet_count, packet->size);
fflush(stdout);
ethernet_in(packet);
}
}
/**
* 协议栈的初始化
*/
void xnet_init (void) {
ethernet_init();
xarp_init();
}
/**
* 轮询处理数据包,并在协议栈中处理
*/
void xnet_poll(void) {
ethernet_poll();
xarp_poll(); // Call ARP poll to handle timeouts and retransmissions
}

View File

@@ -0,0 +1,64 @@
#ifndef XNET_TINY_H
#define XNET_TINY_H
#include <stdint.h>
#define XNET_CFG_PACKET_MAX_SIZE 1516 // 收发数据包的最大大小
#define XNET_POLL_CYCLE_MS 100 // Polling cycle in milliseconds, used by ARP and other modules
#pragma pack(1)
#define XNET_MAC_ADDR_SIZE 6 // MAC地址长度
/**
* 以太网数据帧格式:RFC894
*/
typedef struct _xether_hdr_t {
uint8_t dest[XNET_MAC_ADDR_SIZE]; // 目标mac地址
uint8_t src[XNET_MAC_ADDR_SIZE]; // 源mac地址
uint16_t protocol; // 协议/长度
}xether_hdr_t;
#pragma pack()
typedef enum _xnet_err_t {
XNET_ERR_OK = 0,
XNET_ERR_IO = -1,
}xnet_err_t;
/**
* 网络数据结构
*/
typedef struct _xnet_packet_t{
uint16_t size; // 包中有效数据大小
uint8_t * data; // 包的数据起始地址
uint8_t payload[XNET_CFG_PACKET_MAX_SIZE]; // 最大负载数据量
}xnet_packet_t;
typedef enum _xnet_protocol_t {
XNET_PROTOCOL_ARP = 0x0806, // ARP协议
XNET_PROTOCOL_IP = 0x0800, // IP协议
XNET_PROTOCOL_IPv6 = 0x86dd, // IPv6协议
}xnet_protocol_t;
xnet_packet_t * xnet_alloc_for_send(uint16_t data_size);
xnet_packet_t * xnet_alloc_for_read(uint16_t data_size);
void xnet_free_packet(xnet_packet_t * packet);
xnet_err_t xnet_driver_open (uint8_t * mac_addr);
xnet_err_t xnet_driver_send (xnet_packet_t * packet);
xnet_err_t xnet_driver_read (xnet_packet_t ** packet);
void xnet_init (void);
void xnet_poll(void);
void remove_header(xnet_packet_t *packet, uint16_t header_size);
xnet_err_t ethernet_out_to(xnet_protocol_t protocol, const uint8_t *mac_addr, xnet_packet_t * packet);
const uint8_t * get_netif_mac(void);
int xnet_check_tmo(int *tmo);
extern const uint8_t my_ip_addr[];
#endif // XNET_TINY_H