quinn-os/udp.c
2021-12-10 21:14:10 +10:00

49 lines
1.5 KiB
C

#include "ipv4.h"
#include "udp.h"
#include "socket.h"
void udp_process_packet(struct ether_t *ether, unsigned int dest, unsigned int src, struct udp_header_t *packet, unsigned int len) {
struct socket_t *sock = socket_find(htons(packet->destination_port), htons(packet->source_port), htonl(src), 0);
if (!sock || sock->socket_type != 17) {
return;
}
struct udp_data_t *data = (struct udp_data_t *)malloc(sizeof(struct udp_data_t));
if (!data) {
return;
}
int ulen = packet->length - sizeof(struct udp_header_t);
data->data = (char *)malloc(ulen);
if (!data->data) {
free(data);
return;
}
memcpy(data->data, packet->payload, ulen);
data->from = src;
data->len = ulen;
if (sock->packet_count == 0) {
sock->packets.udp = (struct udp_data_t**)malloc(sizeof(struct udp_data_t *));
} else {
sock->packets.udp = (struct udp_data_t **)realloc(sock->packets.udp, sizeof(struct udp_data_t *) * (sock->packet_count + 1));
}
sock->packets.udp[sock->packet_count] = data;
sock->packet_count++;
}
void udp_send(struct ether_t *ether, struct socket_t *sock, unsigned char *packet, unsigned int len) {
struct udp_header_t *header = (struct udp_header_t *)malloc(len + sizeof(struct udp_header_t));
header->source_port = htons(sock->port_recv);
header->destination_port = htons(sock->port_dest);
header->length = htons((unsigned short)len + sizeof(struct udp_header_t));
header->checksum = 0;
memcpy(header->payload, packet, len);
ipv4_send(ether, 0x11, htonl(sock->addr), header, len + sizeof(struct udp_header_t));
}