/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#endif

#include <errno.h>

#include "jcademo_raoutbound_natmultcp_NatMulTCP.h"

JNIEXPORT jlong JNICALL Java_jcademo_raoutbound_natmultcp_NatMulTCP_open(JNIEnv *cntx, jclass jc, jstring host, jint port)
{
    int sd, status;
    const char *chost;
    char cport[6];
    struct addrinfo hints, *res;
#ifdef WIN32
    WSADATA WSAData;
    WSAStartup(0x0101, &WSAData);
#endif
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = 0;
    chost = (*cntx)->GetStringUTFChars(cntx, host, 0);
    itoa(port, cport, 10);
    status = getaddrinfo(chost, cport, &hints, &res);
    (*cntx)->ReleaseStringUTFChars(cntx, host, chost);
    if(status != 0) return -1;
    sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if(sd < 0) return -1;
    status = connect(sd, res->ai_addr, res->ai_addrlen);
    if(status != 0) return -1;
    freeaddrinfo(res);
    return sd;
}

static char buf[1000];

JNIEXPORT jboolean JNICALL Java_jcademo_raoutbound_natmultcp_NatMulTCP_send(JNIEnv *cntx, jclass jc, jlong sd, jstring msg)
{
	int status;
	const char *cmsg;
    cmsg = (*cntx)->GetStringUTFChars(cntx, msg, 0);
	strcpy(buf, cmsg); // move message to non-JNI memory
    status = send(sd, (char *)&buf, strlen(buf), 0);
    (*cntx)->ReleaseStringUTFChars(cntx, msg, cmsg);
    if(status < 0) return 0;
	return 1;
}

JNIEXPORT jstring JNICALL Java_jcademo_raoutbound_natmultcp_NatMulTCP_receive(JNIEnv *cntx, jclass jc, jlong sd)
{
	int ix;
	char res[100];
	strcpy(res, "");
	ix = 0;
	while(strstr(res, "\r\n") == NULL && ix < sizeof(res)) {
		ix = ix + recv(sd, res + ix, sizeof(res) - ix, 0);
		res[ix] = '\0';
	}
	return (*cntx)->NewStringUTF(cntx, res);
}

JNIEXPORT void JNICALL Java_jcademo_raoutbound_natmultcp_NatMulTCP_close(JNIEnv *cntx, jclass jc, jlong sd)
{
#ifdef WIN32
    closesocket(sd);
    WSACleanup();
#else
    close(sd);
#endif
}
