/* VMNetworkInterface.c - Native methods for NetworkInterface class
   Copyright (C) 2003, 2005, 2006  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
 
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

/* do not move; needed here because of some macro definitions */
#include <config.h>

#include <jni.h>

#include "java_net_VMNetworkInterface.h"

#include "javanet.h"
#include <Iphlpapi.h>

/**
 * Parse IP address string.
 *
 * @return IP address byte array.
 */
static jbyteArray parse_ip_address_string(JNIEnv* env, const char* str) {
	jbyteArray result = (*env)->NewByteArray(env, 4);
	if (result) {
		jbyte* data = (*env)->GetByteArrayElements(env, result, NULL);
		if (data) {
			int index = 0;
			jint value = 0;
			for (;;) {
				if (*str == '.' || ! *str) {
					data[index++] = value;
					if (index >= 4 || ! *str) {
						break;
					}
					value = 0;
				} else {
					value = value * 10 + (*str - '0');
				}
				str++;
			}
			(*env)->ReleaseByteArrayElements(env, result, data, 0);
		}
	}
	return result;
}


/**
 * Create an InetAddress object.
 *
 * @return Inet4Address[]
 */
static jobjectArray create_InetAddresses(JNIEnv* env, PIP_ADDR_STRING address_list) {
	jobjectArray result = NULL;
	jclass inet_address_class = (*env)->FindClass(env, "java/net/Inet4Address");
	PIP_ADDR_STRING tmp_address_list = address_list;

	if (inet_address_class) {
		int i, address_count = 0;
		jmethodID mid = (*env)->GetMethodID(env,
											inet_address_class,
											"<init>",
											"([BLjava/lang/String;)V");
		// Count addresses
		while (tmp_address_list) {
			address_count++;
			tmp_address_list = tmp_address_list->Next;
		}
		result = (*env)->NewObjectArray(env,
										address_count,
										inet_address_class,
										NULL);
		if (result) {
			// Create InetAddress objects.
			tmp_address_list = address_list;
			for (i = 0; i < address_count && tmp_address_list; ++i) {
				IP_ADDRESS_STRING address_string = tmp_address_list->IpAddress;
				char* str = address_string.String;
				jbyteArray ip_address = parse_ip_address_string(env, str);
				if (ip_address) {
					// new Inet4Address(byte[], String)
					jobject inet_address = (*env)->NewObject(env,
															 inet_address_class,
															 mid,
															 ip_address,
															 NULL);
															 
					if (inet_address) {
						(*env)->SetObjectArrayElement(env, result, i, inet_address);
					}
					tmp_address_list = tmp_address_list->Next;
				}
			}
		}
	}
	return result;
}


/*
 * Returns all local network interfaces as vector
 */
JNIEXPORT jobject JNICALL
Java_java_net_VMNetworkInterface_getInterfaces (JNIEnv * env,
						jclass class
						__attribute__ ((__unused__)))
{
	jclass vector_class, network_interface_class;
	jobject result = NULL;
	PIP_ADAPTER_INFO adapter_info;
	ULONG buflen = 0;

	// Get required buffer size.
	GetAdaptersInfo(NULL, &buflen);
	adapter_info = (PIP_ADAPTER_INFO) malloc(buflen);

	// Load classes
	vector_class = (*env)->FindClass(env, "java/util/Vector");
	network_interface_class = (*env)->FindClass(env, "java/net/NetworkInterface");

	if (vector_class && network_interface_class) {
		jmethodID vector_constructor_id
								= (*env)->GetMethodID(env,
													  vector_class,
													  "<init>",
													  "()V");
		jmethodID vector_add_id = (*env)->GetMethodID(env,
													  vector_class,
													  "add",
													  "(Ljava/lang/Object;)Z");
		jmethodID network_interface_constructor_id
								= (*env)->GetMethodID(env,
													  network_interface_class,
													  "<init>",
													  "(Ljava/lang/String;[Ljava/net/InetAddress;)V");
		// Allocate a Vector.
		result = (*env)->NewObject(env,
								   vector_class,
								   vector_constructor_id);

		// Get network adapters information.
		if (GetAdaptersInfo(adapter_info, &buflen) == NO_ERROR) {
			do {
				jstring name;
				jobject network_interface;
				jobjectArray inet_addresses;
				
				inet_addresses = create_InetAddresses(env, &adapter_info->IpAddressList);
				if (! inet_addresses) {
					break;
				}

				name = (*env)->NewStringUTF(env, adapter_info->AdapterName);
				if (! name) {
					break;
				}

				network_interface = (*env)->NewObject(env,
													  network_interface_class,
													  network_interface_constructor_id,
													  name,
													  inet_addresses);
				if (! network_interface) {
					break;
				}

				// Call Vector.add()
				(*env)->CallBooleanMethod(env,
										  result,
										  vector_add_id,
										  network_interface);
				if ((*env)->ExceptionCheck(env)) {
					break;
				}
			} while ((adapter_info = adapter_info->Next) != NULL);
		}
	}
	free(adapter_info);

	return result;
}

/* end of file */
