summaryrefslogtreecommitdiff
path: root/fw/esp32/components/eos/tun.c
blob: cb1dde60f630c58c56ad1e63406c6d46b629690d (plain)
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
#include <string.h>
#include <stdio.h>

#include <lwip/pbuf.h>
#include <lwip/netif.h>
#include <lwip/tcpip.h>
#include <lwip/ip.h>
#include <lwip/lwip_napt.h>

#include <esp_log.h>

#include "net.h"
#include "app.h"
#include "tun.h"

static const char *TAG = "EOS TUN";

static ip4_addr_t ipaddr, netmask, gw;
static struct netif netif_tun;

static err_t IRAM_ATTR tun_output(struct netif *netif, struct pbuf *p, const struct ip4_addr *ipaddr) {
    EOSMessage msg;
    struct pbuf *q;

    for (q = p; q != NULL; q = q->next) {
        eos_app_alloc(&msg);
        if (q->len > msg.size) {
            eos_app_free(&msg);
            continue;
        }

        memcpy(msg.buffer, q->payload, q->len);
        eos_app_send(EOS_APP_MTYPE_TUN, &msg, q->len);
    }

    return ERR_OK;
}

static void IRAM_ATTR tun_input(unsigned char mtype, EOSMessage *msg, uint16_t len) {
    struct netif *netif = &netif_tun;
    struct pbuf *p;
    int rv;

    if (!netif_is_up(netif)) return;

    p = pbuf_alloc(PBUF_LINK, len, PBUF_RAM);
    if (p == NULL) return;

    memcpy(p->payload, msg->buffer, len);
    rv = netif->input(p, netif);
    if (rv != ERR_OK) {
        pbuf_free(p);
    }
}

static err_t tun_init(struct netif *netif) {
    netif->name[0] = 't';
    netif->name[1] = 'n';
    netif->hostname = NULL;
    netif->output = tun_output;
    netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_LINK_UP;
    netif->mtu = 1500;

    return ERR_OK;
}

void eos_tun_portmap_add(uint32_t ext_addr) {
    ip4_addr_t app_addr;

    IP4_ADDR(&app_addr, 192,168,152,1);
    ip_portmap_add(IP_PROTO_TCP, ext_addr, 22, app_addr.addr, 22);
}

void eos_tun_portmap_remove(void) {
    ip_portmap_remove(IP_PROTO_TCP, 22);
}

void eos_tun_init(void) {
    struct netif *rv;

    IP4_ADDR(&gw, 0,0,0,0);
    IP4_ADDR(&ipaddr, 192,168,152,2);
    IP4_ADDR(&netmask, 255,255,255,0);

    rv = netif_add(&netif_tun, &ipaddr, &netmask, &gw, NULL, tun_init, tcpip_input);
    assert(rv != NULL);

    netif_set_up(&netif_tun);
    ip_napt_enable_netif(&netif_tun, 1);
    eos_app_set_handler(EOS_APP_MTYPE_TUN, tun_input);

    ESP_LOGI(TAG, "INIT");
    ESP_LOGI(TAG, "addres: %x", (unsigned int)ipaddr.addr);
}