about summary refs log tree commit diff
path: root/src/protocol.c
blob: 87ae81f4eec6afbbb3b71844589d5d2a79cab1c3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <protocol.h>

Packet_t* generate_packet(uint64_t type, const uint8_t* data, uint64_t data_size)
{
    Packet_t* packet = calloc(1, get_packet_size_without_data() + data_size);

    srand(time(NULL));

    packet->magic = PACKET_MAGIC;
    packet->id = rand();
    packet->type = type;
    packet->data_size = data_size;
    packet->data = NULL;
    memcpy(&packet->data, data, data_size);

    packet->checksum = get_packet_checksum(packet);

    printf("GENERATED PACKET:\n");
    print_packet(packet);

    return packet;
}

int handle_packet(const Packet_t* packet)
{
    int ret = is_packet_valid(packet);
    if(ret < 0)
    {
        printf("Packet is invalid!\n");
        return ret;
    }

    printf("PACKET VALIDATED!\n");
    printf("RECIEVED PACKET:\n");

    switch(packet->id)
    {
        default:
            print_packet(packet);
            break;
    }

    return 0;
}

int is_packet_valid(const Packet_t* packet)
{
    if(packet->magic != PACKET_MAGIC)
    {
        perror("Invalid packet magic!\n");
        return -EINVAL;
    }

    uint64_t checksum = get_packet_checksum(packet);
    if(packet->checksum != checksum)
    {
        printf("packet checksum: %llu\n", checksum);
        printf("expected checksum: %llu\n", packet->checksum);
        perror("Invalid packet checksum!\n");

        printf("PACKET AFTER RECIEVED:\n");
        print_packet(packet);

        return -EINVAL;
    }

    return 0;
}

uint64_t get_packet_checksum(const Packet_t* packet)
{
    //FIXME: This is not a proper checksum implementation.

    uint64_t sum = 0;
    uint64_t i = sizeof(packet->checksum); //start calculating checksum from outside checksum var in struct
    for(; i < get_packet_size_without_data() + packet->data_size; ++i)
        sum += ((uint8_t*)packet)[i];

    return sum;
}

void print_packet(const Packet_t* packet)
{
    printf("Packet:\n");
    printf("\tmagic: %llu\n", packet->magic);
    printf("\tchecksum: %llu\n", packet->checksum);
    printf("\tid: %llu\n", packet->id);
    printf("\ttype: %llu\n", packet->type);
    printf("\tdata size: %llu\n", packet->data_size);
    printf("\tdata string: %s\n\tdata raw: ", (char*)&packet->data);
    show_raw((uint8_t*)&packet->data, packet->data_size);
}

size_t get_packet_size_without_data()
{
    return sizeof(Packet_t) - sizeof(uint8_t*);
}