/*
    uhpd.c - UDP hole punch daemon
    Copyright (C) 2013 Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#define PORT 7373
#define KEY "uhp"

int main(int argc, char *argv[]){
    int ret, i, sock;
    struct sockaddr_in sin;

    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sock < 0) {
        perror("socket() failed");
        return -1;
    }

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;
    sin.sin_port = htons(7373);
    ret = bind(sock, (struct sockaddr *)&sin, sizeof(sin));
    if (ret < 0) {
        perror("bind() failed");
        return -1;
    }

    ret = fork();
    if (ret != 0) return 0;

    // child

    for (i = 0; i < 10; i++) {
        if (i != sock) close(i);
    }

    while(1){
        char buf[2048];
        socklen_t slen = sizeof(sin);
        ret = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*)&sin, &slen);
        if (ret < strlen(KEY)) continue;
        if (memcmp(buf, KEY, strlen(KEY)) != 0) continue;
        sprintf(buf, "%s:%d\r\n", inet_ntoa(sin.sin_addr), (unsigned short)ntohs(sin.sin_port));
        ret = sendto(sock, buf, strlen(buf), 0, (struct sockaddr*)&sin, sizeof(sin));
    }
    return 0;
}
