-
Notifications
You must be signed in to change notification settings - Fork 1
/
slip_netif.c
107 lines (91 loc) · 1.74 KB
/
slip_netif.c
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
98
99
100
101
102
103
104
105
106
107
/* file: slip_netif.c
* description: Serial Line IP interface
* date: 12/2020
* author: Sergio Johann Filho <[email protected]>
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/if_tun.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include "include/ustack.h"
int fd;
int32_t if_setup()
{
if ((fd = open(SERIAL_DEV0, O_RDWR)) < 0) {
printf("[FATAL] Cannot open serial interface %s\n", SERIAL_DEV0);
return -1;
}
printf("[DEBUG] Serial interface %s initialized\n", SERIAL_DEV0);
return 0;
}
static void tty_write(uint8_t byte)
{
write(fd, &byte, 1);
}
static uint8_t tty_read(void)
{
uint8_t byte;
read(fd, &byte, 1);
return byte;
}
uint16_t netif_send(uint8_t *packet, uint16_t len)
{
uint16_t i;
tty_write(SLIP_END);
for (i = 0; i < len; i++) {
if (packet[i] == SLIP_END) {
tty_write(SLIP_ESC);
tty_write(SLIP_ESC_END);
} else {
if (packet[i] == SLIP_ESC) {
tty_write(SLIP_ESC);
tty_write(SLIP_ESC_ESC);
} else {
tty_write(packet[i]);
}
}
}
tty_write(SLIP_END);
#ifdef USTACK_DEBUG_FRAMES
hexdump(packet, len);
#endif
return len;
}
uint16_t netif_recv(uint8_t *packet)
{
uint16_t len = 0;
int16_t r;
while (1) {
r = tty_read();
if (r == SLIP_END) {
if (len > 0) {
#ifdef USTACK_DEBUG_FRAMES
hexdump(packet, len);
#endif
return len;
}
} else {
if (r == SLIP_ESC) {
r = tty_read();
if (r == SLIP_ESC_END) {
r = SLIP_END;
} else {
if (r == SLIP_ESC_ESC) {
r = SLIP_ESC;
}
}
}
packet[len++] = r;
if (len > FRAME_SIZE)
len = 0;
}
}
}