Port forwarder example in openwrt ucode

disclaimer: code is AI generated, uloop as poll.

so the missing ones are ARGV, or change substr to something else.

#!/usr/bin/ucode

import * as uloop from 'uloop';
import * as socket from 'socket';

const LISTEN_PORT = 12345;
const TARGET_HOST = "192.168.0.1";
const TARGET_PORT = 80;

uloop.init();

let listener = socket.listen("0.0.0.0", LISTEN_PORT);

function close_pair(client, upstream, h1, h2) {
    h1?.delete();
    h2?.delete();

    client?.close();
    upstream?.close();
}

function forward(src, dst, hsrc, hdst) {
    let data = src.recv(8192);

    if (!data || length(data) == 0) {
        close_pair(src, dst, hsrc, hdst);
        return;
    }

    let off = 0;

    while (off < length(data)) {
        let n = dst.send(substr(data, off));

        if (n <= 0) {
            close_pair(src, dst, hsrc, hdst);
            return;
        }

        off += n;
    }
}

uloop.handle(listener, function(events) {

    if (!(events & uloop.ULOOP_READ))
        return;

    let client = listener.accept();

    if (!client)
        return;

    let upstream = socket.connect(TARGET_HOST, TARGET_PORT);

    if (!upstream) {
        client.close();
        return;
    }

    let h_client;
    let h_upstream;

    h_client = uloop.handle(client, function(events) {
        if (events & uloop.ULOOP_READ)
            forward(client, upstream, h_client, h_upstream);
    }, uloop.ULOOP_READ);

    h_upstream = uloop.handle(upstream, function(events) {
        if (events & uloop.ULOOP_READ)
            forward(upstream, client, h_upstream, h_client);
    }, uloop.ULOOP_READ);

}, uloop.ULOOP_READ);

printf("Forwarding TCP :%d -> %s:%d\n",
       LISTEN_PORT, TARGET_HOST, TARGET_PORT);

uloop.run();
0
所有评论 0
Avatar
@busylog
准则 博客 联系 反馈 © 2025 Geeknote