Add stubs to easily build and include all of libnatpmp and miniupnpc in osdep/

This commit is contained in:
Adam Ierymenko 2019-08-19 20:28:44 -07:00
parent c8ca1cfa3c
commit cfbd7e3bf5
No known key found for this signature in database
GPG Key ID: 1657198823E52A61
26 changed files with 82 additions and 1931 deletions

View File

@ -13,14 +13,17 @@ if(WIN32)
set(CMAKE_SYSTEM_VERSION "7" CACHE STRING INTERNAL FORCE)
endif(WIN32)
#
# ZeroTier One Version Config
#
set(ZEROTIER_ONE_VERSION_MAJOR 1 CACHE INTERNAL "")
set(ZEROTIER_ONE_VERSION_MINOR 9 CACHE INTERNAL "")
set(ZEROTIER_ONE_VERSION_REVISION 0 CACHE INTERNAL "")
set(ZEROTIER_ONE_VERSION_BUILD 0 CACHE INTERNAL "")
#
# Set a default build type if none was specified
#
set(default_build_type "Release")
if(EXISTS "${CMAKE_SOURCE_DIR}/.git")
set(default_build_type "Debug")
@ -169,7 +172,6 @@ if(BUILD_CENTRAL_CONTROLLER)
set(libs ${libs} rabbitmq-static ${PostgreSQL_LIBRARIES})
endif(BUILD_CENTRAL_CONTROLLER)
add_executable(${PROJECT_NAME} ${src} ${headers})
target_link_libraries(${PROJECT_NAME} ${libs})
target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_BINARY_DIR})

View File

@ -1,42 +0,0 @@
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import fr.free.miniupnp.libnatpmp.NatPmp;
import fr.free.miniupnp.libnatpmp.NatPmpResponse;
class JavaTest {
public static void main(String[] args) {
NatPmp natpmp = new NatPmp();
natpmp.sendPublicAddressRequest();
NatPmpResponse response = new NatPmpResponse();
int result = -1;
do{
result = natpmp.readNatPmpResponseOrRetry(response);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
//fallthrough
}
} while (result != 0);
byte[] bytes = intToByteArray(response.addr);
try {
InetAddress inetAddress = InetAddress.getByAddress(bytes);
System.out.println("Public address is " + inetAddress);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)value,
(byte)(value >>> 8),
(byte)(value >>> 16),
(byte)(value >>> 24)};
}
}

View File

@ -1,177 +0,0 @@
# $Id: Makefile,v 1.23 2013/11/26 16:38:15 nanard Exp $
# This Makefile is designed for use with GNU make
# libnatpmp
# (c) 2007-2013 Thomas Bernard
# http://miniupnp.free.fr/libnatpmp.html
OS = $(shell uname -s)
CC = gcc
INSTALL = install -p
ARCH = $(shell uname -m | sed -e s/i.86/i686/)
VERSION = $(shell cat VERSION)
ifeq ($(OS), Darwin)
JARSUFFIX=mac
endif
ifeq ($(OS), Linux)
JARSUFFIX=linux
endif
ifneq (,$(findstring WIN,$(OS)))
JARSUFFIX=win32
endif
# APIVERSION is used in soname
APIVERSION = 1
#LDFLAGS = -Wl,--no-undefined
CFLAGS ?= -Os
#CFLAGS = -g -O0
CFLAGS += -fPIC
CFLAGS += -Wall
#CFLAGS += -Wextra
CFLAGS += -DENABLE_STRNATPMPERR
#CFLAGS += -Wstrict-aliasing
LIBOBJS = natpmp.o getgateway.o
OBJS = $(LIBOBJS) testgetgateway.o natpmpc.o natpmp-jni.o
STATICLIB = libnatpmp.a
ifeq ($(OS), Darwin)
SHAREDLIB = libnatpmp.dylib
JNISHAREDLIB = libjninatpmp.dylib
SONAME = $(basename $(SHAREDLIB)).$(APIVERSION).dylib
CFLAGS := -DMACOSX -D_DARWIN_C_SOURCE $(CFLAGS)
SONAMEFLAGS=-Wl,-install_name,$(JNISHAREDLIB) -dynamiclib -framework JavaVM
else
ifneq (,$(findstring WIN,$(OS)))
SHAREDLIB = natpmp.dll
JNISHAREDLIB = jninatpmp.dll
CC = i686-w64-mingw32-gcc
EXTRA_LD = -lws2_32 -lIphlpapi -Wl,--no-undefined -Wl,--enable-runtime-pseudo-reloc --Wl,kill-at
else
SHAREDLIB = libnatpmp.so
JNISHAREDLIB = libjninatpmp.so
SONAME = $(SHAREDLIB).$(APIVERSION)
SONAMEFLAGS=-Wl,-soname,$(JNISHAREDLIB)
endif
endif
HEADERS = natpmp.h
EXECUTABLES = testgetgateway natpmpc-shared natpmpc-static
INSTALLPREFIX ?= $(PREFIX)/usr
INSTALLDIRINC = $(INSTALLPREFIX)/include
INSTALLDIRLIB = $(INSTALLPREFIX)/lib
INSTALLDIRBIN = $(INSTALLPREFIX)/bin
JAVA ?= java
JAVAC ?= javac
JAVAH ?= javah
JAVAPACKAGE = fr/free/miniupnp/libnatpmp
JAVACLASSES = $(JAVAPACKAGE)/NatPmp.class $(JAVAPACKAGE)/NatPmpResponse.class $(JAVAPACKAGE)/LibraryExtractor.class $(JAVAPACKAGE)/URLUtils.class
JNIHEADERS = fr_free_miniupnp_libnatpmp_NatPmp.h
.PHONY: all clean depend install cleaninstall installpythonmodule
all: $(STATICLIB) $(SHAREDLIB) $(EXECUTABLES)
pythonmodule: $(STATICLIB) libnatpmpmodule.c setup.py
python setup.py build
touch $@
installpythonmodule: pythonmodule
python setup.py install
clean:
$(RM) $(OBJS) $(EXECUTABLES) $(STATICLIB) $(SHAREDLIB) $(JAVACLASSES) $(JNISHAREDLIB)
$(RM) pythonmodule
$(RM) -r build/ dist/ libraries/
depend:
makedepend -f$(MAKEFILE_LIST) -Y $(OBJS:.o=.c) 2>/dev/null
install: $(HEADERS) $(STATICLIB) $(SHAREDLIB) natpmpc-shared
$(INSTALL) -d $(INSTALLDIRINC)
$(INSTALL) -m 644 $(HEADERS) $(INSTALLDIRINC)
$(INSTALL) -d $(INSTALLDIRLIB)
$(INSTALL) -m 644 $(STATICLIB) $(INSTALLDIRLIB)
$(INSTALL) -m 644 $(SHAREDLIB) $(INSTALLDIRLIB)/$(SONAME)
$(INSTALL) -d $(INSTALLDIRBIN)
$(INSTALL) -m 755 natpmpc-shared $(INSTALLDIRBIN)/natpmpc
ln -s -f $(SONAME) $(INSTALLDIRLIB)/$(SHAREDLIB)
$(JNIHEADERS): fr/free/miniupnp/libnatpmp/NatPmp.class
$(JAVAH) -jni fr.free.miniupnp.libnatpmp.NatPmp
%.class: %.java
$(JAVAC) -cp . $<
$(JNISHAREDLIB): $(SHAREDLIB) $(JNIHEADERS) $(JAVACLASSES)
ifeq (,$(JAVA_HOME))
@echo "Check your JAVA_HOME environement variable" && false
endif
ifneq (,$(findstring WIN,$(OS)))
$(CC) -m32 -D_JNI_Implementation_ -Wl,--kill-at \
-I"$(JAVA_HOME)/include" -I"$(JAVA_HOME)/include/win32" \
natpmp-jni.c -shared \
-o $(JNISHAREDLIB) -L. -lnatpmp -lws2_32 -lIphlpapi
else
$(CC) $(CFLAGS) -c -I"$(JAVA_HOME)/include" -I"$(JAVA_HOME)/include/win32" natpmp-jni.c
$(CC) $(CFLAGS) -o $(JNISHAREDLIB) -shared $(SONAMEFLAGS) natpmp-jni.o -lc -L. -lnatpmp
endif
jar: $(JNISHAREDLIB)
find fr -name '*.class' -print > classes.list
$(eval JNISHAREDLIBPATH := $(shell java fr.free.miniupnp.libnatpmp.LibraryExtractor))
mkdir -p libraries/$(JNISHAREDLIBPATH)
mv $(JNISHAREDLIB) libraries/$(JNISHAREDLIBPATH)/$(JNISHAREDLIB)
jar cf natpmp_$(JARSUFFIX).jar @classes.list libraries/$(JNISHAREDLIBPATH)/$(JNISHAREDLIB)
$(RM) classes.list
jnitest: $(JNISHAREDLIB) JavaTest.class
$(RM) libjninatpmp.so
$(JAVA) -Djna.nosys=true -cp . JavaTest
mvn_install:
mvn install:install-file -Dfile=java/natpmp_$(JARSUFFIX).jar \
-DgroupId=com.github \
-DartifactId=natpmp \
-Dversion=$(VERSION) \
-Dpackaging=jar \
-Dclassifier=$(JARSUFFIX) \
-DgeneratePom=true \
-DcreateChecksum=true
cleaninstall:
$(RM) $(addprefix $(INSTALLDIRINC), $(HEADERS))
$(RM) $(INSTALLDIRLIB)/$(SONAME)
$(RM) $(INSTALLDIRLIB)/$(SHAREDLIB)
$(RM) $(INSTALLDIRLIB)/$(STATICLIB)
testgetgateway: testgetgateway.o getgateway.o
$(CC) $(LDFLAGS) -o $@ $^ $(EXTRA_LD)
natpmpc-static: natpmpc.o $(STATICLIB)
$(CC) $(LDFLAGS) -o $@ $^ $(EXTRA_LD)
natpmpc-shared: natpmpc.o $(SHAREDLIB)
$(CC) $(LDFLAGS) -o $@ $^ $(EXTRA_LD)
$(STATICLIB): $(LIBOBJS)
$(AR) crs $@ $?
$(SHAREDLIB): $(LIBOBJS)
ifeq ($(OS), Darwin)
$(CC) -dynamiclib -Wl,-install_name,$(SONAME) -o $@ $^
else
$(CC) -shared -Wl,-soname,$(SONAME) -o $@ $^ $(EXTRA_LD)
endif
# DO NOT DELETE
natpmp.o: natpmp.h getgateway.h declspec.h
getgateway.o: getgateway.h declspec.h
testgetgateway.o: getgateway.h declspec.h
natpmpc.o: natpmp.h

View File

@ -1,30 +0,0 @@
@echo Compiling with MinGW
@SET LIBS=-lws2_32 -liphlpapi
@echo Compile getgateway
gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR getgateway.c
gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR testgetgateway.c
gcc -o testgetgateway getgateway.o testgetgateway.o %LIBS%
del testgetgateway.o
@echo Compile natpmp-static:
gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR getgateway.c
gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR natpmp.c
gcc -c -Wall -Os -DWIN32 wingettimeofday.c
ar cr natpmp.a getgateway.o natpmp.o wingettimeofday.o
del getgateway.o natpmp.o
gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR natpmpc.c
gcc -o natpmpc-static natpmpc.o natpmp.a %LIBS%
upx --best natpmpc-static.exe
del natpmpc.o
@echo Create natpmp.dll:
gcc -c -Wall -Os -DWIN32 -DENABLE_STRNATPMPERR -DNATPMP_EXPORTS getgateway.c
gcc -c -Wall -Os -DWIN32 -DENABLE_STRNATPMPERR -DNATPMP_EXPORTS natpmp.c
dllwrap -k --driver-name gcc --def natpmp.def --output-def natpmp.dll.def --implib natpmp.lib -o natpmp.dll getgateway.o natpmp.o wingettimeofday.o %LIBS%
@echo Compile natpmp-shared:
gcc -c -Wall -Os -DWIN32 -DENABLE_STRNATPMPERR -DNATPMP_EXPORTS natpmpc.c
gcc -o natpmpc-shared natpmpc.o natpmp.lib -lws2_32
upx --best natpmpc-shared.exe
del *.o

View File

@ -1,238 +0,0 @@
package fr.free.miniupnp.libnatpmp;
/** I (Leah X Schmidt) copied this code from jnaerator, because
JNAerator's extractor requires you to buy into the whole JNA
concept.
JNAErator is
Copyright (c) 2009 Olivier Chafik, All Rights Reserved
JNAerator 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 3 of the License, or
(at your option) any later version.
JNAerator 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 JNAerator. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class LibraryExtractor {
private static boolean libPathSet = false;
public static String getLibraryPath(String libraryName, boolean extractAllLibraries, Class<?> cl) {
try {
String customPath = System.getProperty("library." + libraryName);
if (customPath == null)
customPath = System.getenv(libraryName.toUpperCase() + "_LIBRARY");
if (customPath != null) {
File f = new File(customPath);
if (!f.exists())
System.err.println("Library file '" + customPath + "' does not exist !");
else
return f.getAbsolutePath();
}
//ClassLoader cl = LibraryExtractor.class.getClassLoader();
String prefix = "(?i)" + (isWindows() ? "" : "lib") + libraryName + "[^A-Za-z_].*";
String libsuffix = "(?i).*\\.(so|dll|dylib|jnilib)";
//String othersuffix = "(?i).*\\.(pdb)";
URL sourceURL = null;
List<URL> otherURLs = new ArrayList<URL>();
String arch = getCurrentOSAndArchString();
//System.out.println("libURL = " + libURL);
List<URL> list = URLUtils.listFiles(URLUtils.getResource(cl, "libraries/" + arch)),
noArchList = URLUtils.listFiles(URLUtils.getResource(cl, "libraries/noarch"));
Set<String> names = new HashSet<String>();
for (URL url : list) {
String name = getFileName(url);
names.add(name);
}
for (URL url : noArchList) {
String name = getFileName(url);
if (names.add(name))
list.add(url);
}
for (File f : new File(".").listFiles())
if (f.isFile())
list.add(f.toURI().toURL());
for (URL url : list) {
String name = getFileName(url);
boolean pref = name.matches(prefix), suff = name.matches(libsuffix);
if (pref && suff)
sourceURL = url;
else //if (suff || fileName.matches(othersuffix))
otherURLs.add(url);
}
List<File> files = new ArrayList<File>();
if (extractAllLibraries) {
for (URL url : otherURLs)
files.add(extract(url));
}
if (System.getProperty("javawebstart.version") != null) {
if (isWindows()) {
//File f = new File("c:\\Windows\\" + (Platform.is64Bit() ? "SysWOW64\\" : "System32\\") + libraryName + ".dll");
File f = new File("c:\\Windows\\" + "System32\\" + libraryName + ".dll");
if (f.exists())
return f.toString();
} else if (isMac()) {
File f = new File("/System/Library/Frameworks/" + libraryName + ".framework/" + libraryName);
if (f.exists())
return f.toString();
}
}
if (sourceURL == null)
return libraryName;
else {
File file = extract(sourceURL);
files.add(file);
int lastSize;
do {
lastSize = files.size();
for (Iterator<File> it = files.iterator(); it.hasNext();) {
File f = it.next();
if (!f.getName().matches(libsuffix))
continue;
try {
System.load(f.toString());
it.remove();
} catch (Throwable ex) {
System.err.println("Loading " + f.getName() + " failed (" + ex + ")");
}
}
} while (files.size() < lastSize);
return file.getCanonicalPath();
}
} catch (Throwable ex) {
System.err.println("ERROR: Failed to extract library " + libraryName);
ex.printStackTrace();
return libraryName;
}
}
public static final boolean isWindows() {
String osName = System.getProperty("os.name");
return osName.startsWith("Windows");
}
public static final boolean isMac() {
String osName = System.getProperty("os.name");
return osName.startsWith("Mac") || osName.startsWith("Darwin");
}
//this code is from JNA, but JNA has a fallback to some native
//stuff in case this doesn't work. Since sun.arch.data.model is
//defined for Sun and IBM, this should work nearly everywhere.
public static final boolean is64Bit() {
String model = System.getProperty("sun.arch.data.model",
System.getProperty("com.ibm.vm.bitmode"));
if (model != null) {
return "64".equals(model);
}
String arch = System.getProperty("os.arch").toLowerCase();
if ("x86_64".equals(arch)
|| "ia64".equals(arch)
|| "ppc64".equals(arch)
|| "sparcv9".equals(arch)
|| "amd64".equals(arch)) {
return true;
}
return false;
}
public static String getCurrentOSAndArchString() {
String os = System.getProperty("os.name"), arch = System.getProperty("os.arch");
if (os.equals("Mac OS X")) {
os = "darwin";
arch = "fat";
} else if (os.startsWith("Windows")) {
return "win" + (is64Bit() ? "64" : "32");
} else if (os.matches("SunOS|Solaris"))
os = "solaris";
return os + "-" + arch;
}
private static File extract(URL url) throws IOException {
File localFile;
if ("file".equals(url.getProtocol()))
localFile = new File(URLDecoder.decode(url.getFile(), "UTF-8"));
else {
File f = new File(System.getProperty("user.home"));
f = new File(f, ".jnaerator");
f = new File(f, "extractedLibraries");
if (!f.exists())
f.mkdirs();
if (!libPathSet) {
String path = System.getProperty("java.library.path");
if (path == null) {
System.setProperty("java.library.path", f.toString());
} else {
System.setProperty("java.library.path", path + ":" + f);
}
libPathSet = true;
}
localFile = new File(f, new File(url.getFile()).getName());
URLConnection c = url.openConnection();
if (localFile.exists() && localFile.lastModified() > c.getLastModified()) {
c.getInputStream().close();
} else {
System.out.println("Extracting " + url);
InputStream in = c.getInputStream();
OutputStream out = new FileOutputStream(localFile);
int len;
byte[] b = new byte[1024];
while ((len = in.read(b)) > 0)
out.write(b, 0, len);
out.close();
in.close();
}
}
return localFile;
}
private static String getFileName(URL url) {
return new File(url.getFile()).getName();
}
public static void main(String[] args) {
System.out.println(getCurrentOSAndArchString());
}
}

View File

@ -1,50 +0,0 @@
package fr.free.miniupnp.libnatpmp;
import java.nio.ByteBuffer;
public class NatPmp {
private static final String JNA_LIBRARY_NAME = LibraryExtractor.getLibraryPath("jninatpmp", true, NatPmp.class);
static {
String s = JNA_LIBRARY_NAME;
startup();
}
public ByteBuffer natpmp;
public NatPmp() {
init(0, 0);
}
public NatPmp(int forcedgw) {
init(1, forcedgw);
}
/** Cleans up the native resources used by this object.
Attempting to use the object after this has been called
will lead to crashes.*/
public void dispose() {
free();
}
protected void finalize() {
if (natpmp != null)
free();
}
private native void init(int forcegw, int forcedgw);
private native void free();
private static native void startup();
public native int sendPublicAddressRequest();
public native int sendNewPortMappingRequest(int protocol, int privateport, int publicport, int lifetime);
//returns a number of milliseconds, in accordance with Java convention
public native long getNatPmpRequestTimeout();
public native int readNatPmpResponseOrRetry(NatPmpResponse response);
}

View File

@ -1,28 +0,0 @@
package fr.free.miniupnp.libnatpmp;
public class NatPmpResponse {
public static final int TYPE_PUBLICADDRESS=0;
public static final int TYPE_UDPPORTMAPPING=1;
public static final int TYPE_TCPPORTMAPPING=2;
/** see TYPE_* constants */
public short type;
/** NAT-PMP response code */
public short resultcode;
/** milliseconds since start of epoch */
public long epoch;
/** only defined if type == 0*/
public int addr;
/** only defined if type != 0 */
public int privateport;
/** only defined if type != 0 */
public int mappedpublicport;
/** only defined if type != 0 */
public long lifetime; //milliseconds
}

View File

@ -1,81 +0,0 @@
package fr.free.miniupnp.libnatpmp;
/** I (Leah X Schmidt) copied this code from jnaerator, because
JNAerator's extractor requires you to buy into the whole JNA
concept.
JNAErator is
Copyright (c) 2009 Olivier Chafik, All Rights Reserved
JNAerator 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 3 of the License, or
(at your option) any later version.
JNAerator 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 JNAerator. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
public class URLUtils {
public static URL getResource(Class<?> cl, String path) throws IOException {
String clp = cl.getName().replace('.', '/') + ".class";
URL clu = cl.getClassLoader().getResource(clp);
String s = clu.toString();
if (s.endsWith(clp))
return new URL(s.substring(0, s.length() - clp.length()) + path);
if (s.startsWith("jar:")) {
String[] ss = s.split("!");
return new URL(ss[1] + "!/" + path);
}
return null;
}
public static List<URL> listFiles(URL directory) throws IOException {
List<URL> ret = new ArrayList<URL>();
String s = directory.toString();
if (s.startsWith("jar:")) {
String[] ss = s.substring("jar:".length()).split("!");
String path = ss[1];
URL target = new URL(ss[0]);
InputStream tin = target.openStream();
try {
JarInputStream jin = new JarInputStream(tin);
JarEntry je;
while ((je = jin.getNextJarEntry()) != null) {
String p = "/" + je.getName();
if (p.startsWith(path) && p.indexOf('/', path.length() + 1) < 0)
ret.add(new URL("jar:" + target + "!" + p));
}
} finally {
tin.close();
}
} else if (s.startsWith("file:")) {
File f = new File(directory.getFile());
File[] ffs = f.listFiles();
if (ffs != null)
for (File ff : ffs)
ret.add(ff.toURI().toURL());
} else
throw new IOException("Cannot list contents of " + directory);
return ret;
}
}

View File

@ -1,281 +0,0 @@
/* $Id: libnatpmpmodule.c,v 1.7 2012/03/05 19:38:37 nanard Exp $ */
/* libnatpmp
* http://miniupnp.free.fr/libnatpmp.html
Copyright (c) 2007-2011, Thomas BERNARD
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <Python.h>
#ifdef WIN32
#include <winsock2.h>
#else
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#define STATICLIB
#include "structmember.h"
#include "natpmp.h"
/* for compatibility with Python < 2.4 */
#ifndef Py_RETURN_NONE
#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
#endif
#ifndef Py_RETURN_TRUE
#define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True
#endif
#ifndef Py_RETURN_FALSE
#define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False
#endif
typedef struct {
PyObject_HEAD
/* Type-specific fields go here. */
unsigned int discoverdelay;
natpmp_t natpmp;
} NATPMPObject;
static PyMemberDef NATPMP_members[] = {
{"discoverdelay", T_UINT, offsetof(NATPMPObject, discoverdelay),
0/*READWRITE*/, "value in ms used to wait for NATPMP responses"
},
{NULL}
};
static PyObject *
NATPMPObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
NATPMPObject *self;
self = (NATPMPObject *)type->tp_alloc(type, 0);
if (self) {
initnatpmp(&self->natpmp, 0, 0);
}
return (PyObject *)self;
}
static void
NATPMPObject_dealloc(NATPMPObject *self)
{
closenatpmp(&self->natpmp);
self->ob_type->tp_free((PyObject*)self);
}
static PyObject *
NATPMP_externalipaddress(NATPMPObject *self)
{
int r;
struct timeval timeout;
fd_set fds;
natpmpresp_t response;
r = sendpublicaddressrequest(&self->natpmp);
if (r < 0) {
#ifdef ENABLE_STRNATPMPERR
PyErr_SetString(PyExc_Exception, strnatpmperr(r));
#endif
return NULL;
}
do {
FD_ZERO(&fds);
FD_SET(self->natpmp.s, &fds);
getnatpmprequesttimeout(&self->natpmp, &timeout);
select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
r = readnatpmpresponseorretry(&self->natpmp, &response);
if (r < 0 && r != NATPMP_TRYAGAIN) {
#ifdef ENABLE_STRNATPMPERR
PyErr_SetString(PyExc_Exception, strnatpmperr(r));
#endif
return NULL;
}
} while (r == NATPMP_TRYAGAIN);
return Py_BuildValue("s", inet_ntoa(response.pnu.publicaddress.addr));
}
static PyObject *
NATPMP_domapping(natpmp_t *n, unsigned short eport, unsigned short iport,
const char *protocol, unsigned int lifetime)
{
int proto;
struct timeval timeout;
fd_set fds;
natpmpresp_t response;
int r;
if (!strncasecmp("tcp", protocol, 3)) {
proto = NATPMP_PROTOCOL_TCP;
} else if (!strncasecmp("udp", protocol, 3)) {
proto = NATPMP_PROTOCOL_UDP;
} else {
PyErr_SetString(PyExc_Exception, "Unknown protocol");
return NULL;
}
r = sendnewportmappingrequest(n, proto, iport, eport,
lifetime);
if (r < 0) {
#ifdef ENABLE_STRNATPMPERR
PyErr_SetString(PyExc_Exception, strnatpmperr(r));
#endif
return NULL;
}
do {
FD_ZERO(&fds);
FD_SET(n->s, &fds);
getnatpmprequesttimeout(n, &timeout);
select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
r = readnatpmpresponseorretry(n, &response);
if (r < 0 && r != NATPMP_TRYAGAIN) {
#ifdef ENABLE_STRNATPMPERR
PyErr_SetString(PyExc_Exception, strnatpmperr(r));
#endif
return NULL;
}
} while (r == NATPMP_TRYAGAIN);
return Py_BuildValue("H", response.pnu.newportmapping.mappedpublicport);
}
/* AddPortMapping(externalPort, protocol, internalPort, lifetime)
* protocol is 'UDP' or 'TCP' */
static PyObject *
NATPMP_addportmapping(NATPMPObject *self, PyObject *args)
{
unsigned short eport;
unsigned short iport;
unsigned int lifetime;
const char *protocol;
if (!PyArg_ParseTuple(args, "HsHI", &eport, &protocol, &iport, &lifetime))
return NULL;
return NATPMP_domapping(&self->natpmp, eport, iport, protocol, lifetime);
}
/* DeletePortMapping(externalPort, protocol, internalPort)
* protocol is 'UDP' or 'TCP' */
static PyObject *
NATPMP_deleteportmapping(NATPMPObject *self, PyObject *args)
{
unsigned short eport;
unsigned short iport;
const char *protocol;
if (!PyArg_ParseTuple(args, "HsH", &eport, &protocol, &iport))
return NULL;
return NATPMP_domapping(&self->natpmp, eport, iport, protocol, 0);
}
/* natpmp.NATPMP object Method Table */
static PyMethodDef NATPMP_methods[] = {
{"externalipaddress", (PyCFunction)NATPMP_externalipaddress, METH_NOARGS,
"return external IP address"
},
{"addportmapping", (PyCFunction)NATPMP_addportmapping, METH_VARARGS,
"add a port mapping"
},
{"deleteportmapping", (PyCFunction)NATPMP_deleteportmapping, METH_VARARGS,
"delete a port mapping"
},
{NULL} /* Sentinel */
};
static PyTypeObject NATPMPType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"libnatpmp.NATPMP", /*tp_name*/
sizeof(NATPMPObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)NATPMPObject_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
"NATPMP objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
NATPMP_methods, /* tp_methods */
NATPMP_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
NATPMPObject_new, /* tp_new */
};
/* module methods */
static PyMethodDef libnatpmp_methods[] = {
{NULL} /* Sentinel */
};
#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initlibnatpmp(void)
{
PyObject* m;
if (PyType_Ready(&NATPMPType) < 0)
return;
m = Py_InitModule3("libnatpmp", libnatpmp_methods,
"libnatpmp module.");
Py_INCREF(&NATPMPType);
PyModule_AddObject(m, "NATPMP", (PyObject *)&NATPMPType);
}

View File

@ -1,29 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 10.00
# Visual C++ Express 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libnatpmp", "libnatpmp.vcproj", "{D59B6527-F3DE-4D26-A08D-52F1EE989301}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "natpmpc-static", "natpmpc-static.vcproj", "{A0B49FA9-98AB-4A74-8B4C-8AB7FA36089B}"
ProjectSection(ProjectDependencies) = postProject
{D59B6527-F3DE-4D26-A08D-52F1EE989301} = {D59B6527-F3DE-4D26-A08D-52F1EE989301}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D59B6527-F3DE-4D26-A08D-52F1EE989301}.Debug|Win32.ActiveCfg = Debug|Win32
{D59B6527-F3DE-4D26-A08D-52F1EE989301}.Debug|Win32.Build.0 = Debug|Win32
{D59B6527-F3DE-4D26-A08D-52F1EE989301}.Release|Win32.ActiveCfg = Release|Win32
{D59B6527-F3DE-4D26-A08D-52F1EE989301}.Release|Win32.Build.0 = Release|Win32
{A0B49FA9-98AB-4A74-8B4C-8AB7FA36089B}.Debug|Win32.ActiveCfg = Debug|Win32
{A0B49FA9-98AB-4A74-8B4C-8AB7FA36089B}.Debug|Win32.Build.0 = Debug|Win32
{A0B49FA9-98AB-4A74-8B4C-8AB7FA36089B}.Release|Win32.ActiveCfg = Release|Win32
{A0B49FA9-98AB-4A74-8B4C-8AB7FA36089B}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -1,195 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="libnatpmp"
ProjectGUID="{D59B6527-F3DE-4D26-A08D-52F1EE989301}"
RootNamespace="libnatpmp"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB;STATICLIB"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB;STATICLIB"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Fichiers sources"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath="..\getgateway.c"
>
</File>
<File
RelativePath="..\natpmp.c"
>
</File>
<File
RelativePath="..\wingettimeofday.c"
>
</File>
</Filter>
<Filter
Name="Fichiers d&apos;en-tête"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath="..\declspec.h"
>
</File>
<File
RelativePath="..\getgateway.h"
>
</File>
<File
RelativePath="..\natpmp.h"
>
</File>
<File
RelativePath="..\wingettimeofday.h"
>
</File>
</Filter>
<Filter
Name="Fichiers de ressources"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@ -1,195 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="natpmpc-static"
ProjectGUID="{A0B49FA9-98AB-4A74-8B4C-8AB7FA36089B}"
RootNamespace="natpmpcstatic"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;STATICLIB;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="ws2_32.lib Iphlpapi.lib"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;STATICLIB;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="ws2_32.lib iphlpapi.lib"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Fichiers sources"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath="..\natpmpc.c"
>
</File>
</Filter>
<Filter
Name="Fichiers d&apos;en-tête"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
</Filter>
<Filter
Name="Fichiers de ressources"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@ -1,157 +0,0 @@
#ifdef __CYGWIN__
#include <stdint.h>
#define __int64 uint64_t
#endif
#ifdef WIN32
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include <stdlib.h>
#include "natpmp.h"
#include "fr_free_miniupnp_libnatpmp_NatPmp.h"
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_fr_free_miniupnp_libnatpmp_NatPmp_init (JNIEnv *env, jobject obj, jint forcegw, jint forcedgw) {
natpmp_t *p = malloc (sizeof(natpmp_t));
if (p == NULL) return;
initnatpmp(p, forcegw, (in_addr_t) forcedgw);
jobject wrapped = (*env)->NewDirectByteBuffer(env, p, sizeof(natpmp_t));
if (wrapped == NULL) return;
jclass thisClass = (*env)->GetObjectClass(env,obj);
if (thisClass == NULL) return;
jfieldID fid = (*env)->GetFieldID(env, thisClass, "natpmp", "Ljava/nio/ByteBuffer;");
if (fid == NULL) return;
(*env)->SetObjectField(env, obj, fid, wrapped);
}
JNIEXPORT void JNICALL Java_fr_free_miniupnp_libnatpmp_NatPmp_free (JNIEnv *env, jobject obj) {
jclass thisClass = (*env)->GetObjectClass(env,obj);
if (thisClass == NULL) return;
jfieldID fid = (*env)->GetFieldID(env, thisClass, "natpmp", "Ljava/nio/ByteBuffer;");
if (fid == NULL) return;
jobject wrapped = (*env)->GetObjectField(env, obj, fid);
if (wrapped == NULL) return;
natpmp_t* natpmp = (natpmp_t*) (*env)->GetDirectBufferAddress(env, wrapped);
closenatpmp(natpmp);
if (natpmp == NULL) return;
free(natpmp);
(*env)->SetObjectField(env, obj, fid, NULL);
}
static natpmp_t* getNatPmp(JNIEnv* env, jobject obj) {
jclass thisClass = (*env)->GetObjectClass(env,obj);
if (thisClass == NULL) return NULL;
jfieldID fid = (*env)->GetFieldID(env, thisClass, "natpmp", "Ljava/nio/ByteBuffer;");
if (fid == NULL) return NULL;
jobject wrapped = (*env)->GetObjectField(env, obj, fid);
if (wrapped == NULL) return NULL;
natpmp_t* natpmp = (natpmp_t*) (*env)->GetDirectBufferAddress(env, wrapped);
return natpmp;
}
JNIEXPORT jint JNICALL Java_fr_free_miniupnp_libnatpmp_NatPmp_sendPublicAddressRequest(JNIEnv* env, jobject obj) {
natpmp_t* natpmp = getNatPmp(env, obj);
if (natpmp == NULL) return -1;
return sendpublicaddressrequest(natpmp);
}
JNIEXPORT void JNICALL Java_fr_free_miniupnp_libnatpmp_NatPmp_startup(JNIEnv* env, jclass cls) {
(void)env;
(void)cls;
#ifdef WIN32
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 2);
WSAStartup(wVersionRequested, &wsaData);
#endif
}
JNIEXPORT jint JNICALL Java_fr_free_miniupnp_libnatpmp_NatPmp_sendNewPortMappingRequest(JNIEnv* env, jobject obj, jint protocol, jint privateport, jint publicport, jint lifetime) {
natpmp_t* natpmp = getNatPmp(env, obj);
if (natpmp == NULL) return -1;
return sendnewportmappingrequest(natpmp, protocol, privateport, publicport, lifetime);
}
JNIEXPORT jlong JNICALL Java_fr_free_miniupnp_libnatpmp_NatPmp_getNatPmpRequestTimeout(JNIEnv* env, jobject obj) {
natpmp_t* natpmp = getNatPmp(env, obj);
struct timeval timeout;
getnatpmprequesttimeout(natpmp, &timeout);
return ((jlong) timeout.tv_sec) * 1000 + (timeout.tv_usec / 1000);
}
#define SET_FIELD(prefix, name, type, longtype) { \
jfieldID fid = (*env)->GetFieldID(env, thisClass, #name, type); \
if (fid == NULL) return -1; \
(*env)->Set ## longtype ## Field(env, response, fid, resp. prefix name); \
}
JNIEXPORT jint JNICALL Java_fr_free_miniupnp_libnatpmp_NatPmp_readNatPmpResponseOrRetry(JNIEnv* env, jobject obj, jobject response) {
natpmp_t* natpmp = getNatPmp(env, obj);
natpmpresp_t resp;
int result = readnatpmpresponseorretry(natpmp, &resp);
if (result != 0) {
return result;
}
jclass thisClass = (*env)->GetObjectClass(env, response);
if (thisClass == NULL) return -1;
SET_FIELD(,type, "S", Short);
SET_FIELD(,resultcode, "S", Short);
jfieldID fid = (*env)->GetFieldID(env, thisClass, "epoch", "J");
if (fid == NULL) return -1;
(*env)->SetLongField(env, response, fid, ((jlong)resp.epoch) * 1000);
if (resp.type == 0) {
jfieldID fid = (*env)->GetFieldID(env, thisClass, "addr", "I");
if (fid == NULL) return -1;
(*env)->SetIntField(env, response, fid, resp.pnu.publicaddress.addr.s_addr);
} else {
SET_FIELD(pnu.newportmapping., privateport, "I", Int);
SET_FIELD(pnu.newportmapping., mappedpublicport, "I", Int);
jfieldID fid = (*env)->GetFieldID(env, thisClass, "lifetime", "J");
if (fid == NULL) return -1;
(*env)->SetLongField(env, response, fid, ((jlong) resp.pnu.newportmapping.lifetime) * 1000 * 1000);
}
return result;
}
#ifdef __cplusplus
}
#endif

View File

@ -1,11 +0,0 @@
LIBRARY
; libnatpmp library
EXPORTS
initnatpmp
closenatpmp
sendpublicaddressrequest
sendnewportmappingrequest
getnatpmprequesttimeout
readnatpmpresponseorretry
strnatpmperr

View File

@ -1,19 +0,0 @@
.TH natpmpc 1
.SH NAME
natpmpc \- NAT\-PMP library test client and mapping setter.
.SH "SYNOPSIS"
Display the public IP address:
.br
\fBnatpmpc\fP
Add a port mapping:
.br
\fBnatpmpc\fP \-a <public port> <private port> <protocol> [lifetime]
.SH DESCRIPTION
In order to remove a mapping, set it with a lifetime of 0 seconds.
To remove all mappings for your machine, use 0 as private port and
lifetime.

View File

@ -1,244 +0,0 @@
/* $Id: natpmpc.c,v 1.13 2012/08/21 17:23:38 nanard Exp $ */
/* libnatpmp
Copyright (c) 2007-2011, Thomas BERNARD
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#if defined(_MSC_VER)
#if _MSC_VER >= 1400
#define strcasecmp _stricmp
#else
#define strcasecmp stricmp
#endif
#else
#include <unistd.h>
#endif
#ifdef WIN32
#include <winsock2.h>
#else
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include "natpmp.h"
void usage(FILE * out, const char * argv0)
{
fprintf(out, "Usage :\n");
fprintf(out, " %s [options]\n", argv0);
fprintf(out, "\tdisplay the public IP address.\n");
fprintf(out, " %s -h\n", argv0);
fprintf(out, "\tdisplay this help screen.\n");
fprintf(out, " %s [options] -a <public port> <private port> <protocol> [lifetime]\n", argv0);
fprintf(out, "\tadd a port mapping.\n");
fprintf(out, "\nOption available :\n");
fprintf(out, " -g ipv4address\n");
fprintf(out, "\tforce the gateway to be used as destination for NAT-PMP commands.\n");
fprintf(out, "\n In order to remove a mapping, set it with a lifetime of 0 seconds.\n");
fprintf(out, " To remove all mappings for your machine, use 0 as private port and lifetime.\n");
}
/* sample code for using libnatpmp */
int main(int argc, char * * argv)
{
natpmp_t natpmp;
natpmpresp_t response;
int r;
int sav_errno;
struct timeval timeout;
fd_set fds;
int i;
int protocol = 0;
uint16_t privateport = 0;
uint16_t publicport = 0;
uint32_t lifetime = 3600;
int command = 0;
int forcegw = 0;
in_addr_t gateway = 0;
struct in_addr gateway_in_use;
#ifdef WIN32
WSADATA wsaData;
int nResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(nResult != NO_ERROR)
{
fprintf(stderr, "WSAStartup() failed.\n");
return -1;
}
#endif
/* argument parsing */
for(i=1; i<argc; i++) {
if(argv[i][0] == '-') {
switch(argv[i][1]) {
case 'h':
usage(stdout, argv[0]);
return 0;
case 'g':
forcegw = 1;
if(argc < i + 1) {
fprintf(stderr, "Not enough arguments for option -%c\n", argv[i][1]);
return 1;
}
gateway = inet_addr(argv[++i]);
break;
case 'a':
command = 'a';
if(argc < i + 4) {
fprintf(stderr, "Not enough arguments for option -%c\n", argv[i][1]);
return 1;
}
i++;
if(1 != sscanf(argv[i], "%hu", &publicport)) {
fprintf(stderr, "%s is not a correct 16bits unsigned integer\n", argv[i]);
return 1;
}
i++;
if(1 != sscanf(argv[i], "%hu", &privateport)) {
fprintf(stderr, "%s is not a correct 16bits unsigned integer\n", argv[i]);
return 1;
}
i++;
if(0 == strcasecmp(argv[i], "tcp"))
protocol = NATPMP_PROTOCOL_TCP;
else if(0 == strcasecmp(argv[i], "udp"))
protocol = NATPMP_PROTOCOL_UDP;
else {
fprintf(stderr, "%s is not a valid protocol\n", argv[i]);
return 1;
}
if(argc > i + 1) {
if(1 != sscanf(argv[i+1], "%u", &lifetime)) {
fprintf(stderr, "%s is not a correct 32bits unsigned integer\n", argv[i]);
} else {
i++;
}
}
break;
default:
fprintf(stderr, "Unknown option %s\n", argv[i]);
usage(stderr, argv[0]);
return 1;
}
} else {
fprintf(stderr, "Unknown option %s\n", argv[i]);
usage(stderr, argv[0]);
return 1;
}
}
/* initnatpmp() */
r = initnatpmp(&natpmp, forcegw, gateway);
printf("initnatpmp() returned %d (%s)\n", r, r?"FAILED":"SUCCESS");
if(r<0)
return 1;
gateway_in_use.s_addr = natpmp.gateway;
printf("using gateway : %s\n", inet_ntoa(gateway_in_use));
/* sendpublicaddressrequest() */
r = sendpublicaddressrequest(&natpmp);
printf("sendpublicaddressrequest returned %d (%s)\n",
r, r==2?"SUCCESS":"FAILED");
if(r<0)
return 1;
do {
FD_ZERO(&fds);
FD_SET(natpmp.s, &fds);
getnatpmprequesttimeout(&natpmp, &timeout);
r = select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
if(r<0) {
fprintf(stderr, "select()");
return 1;
}
r = readnatpmpresponseorretry(&natpmp, &response);
sav_errno = errno;
printf("readnatpmpresponseorretry returned %d (%s)\n",
r, r==0?"OK":(r==NATPMP_TRYAGAIN?"TRY AGAIN":"FAILED"));
if(r<0 && r!=NATPMP_TRYAGAIN) {
#ifdef ENABLE_STRNATPMPERR
fprintf(stderr, "readnatpmpresponseorretry() failed : %s\n",
strnatpmperr(r));
#endif
fprintf(stderr, " errno=%d '%s'\n",
sav_errno, strerror(sav_errno));
}
} while(r==NATPMP_TRYAGAIN);
if(r<0)
return 1;
/* TODO : check that response.type == 0 */
printf("Public IP address : %s\n", inet_ntoa(response.pnu.publicaddress.addr));
printf("epoch = %u\n", response.epoch);
if(command == 'a') {
/* sendnewportmappingrequest() */
r = sendnewportmappingrequest(&natpmp, protocol,
privateport, publicport,
lifetime);
printf("sendnewportmappingrequest returned %d (%s)\n",
r, r==12?"SUCCESS":"FAILED");
if(r < 0)
return 1;
do {
FD_ZERO(&fds);
FD_SET(natpmp.s, &fds);
getnatpmprequesttimeout(&natpmp, &timeout);
select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
r = readnatpmpresponseorretry(&natpmp, &response);
printf("readnatpmpresponseorretry returned %d (%s)\n",
r, r==0?"OK":(r==NATPMP_TRYAGAIN?"TRY AGAIN":"FAILED"));
} while(r==NATPMP_TRYAGAIN);
if(r<0) {
#ifdef ENABLE_STRNATPMPERR
fprintf(stderr, "readnatpmpresponseorretry() failed : %s\n",
strnatpmperr(r));
#endif
return 1;
}
printf("Mapped public port %hu protocol %s to local port %hu "
"liftime %u\n",
response.pnu.newportmapping.mappedpublicport,
response.type == NATPMP_RESPTYPE_UDPPORTMAPPING ? "UDP" :
(response.type == NATPMP_RESPTYPE_TCPPORTMAPPING ? "TCP" :
"UNKNOWN"),
response.pnu.newportmapping.privateport,
response.pnu.newportmapping.lifetime);
printf("epoch = %u\n", response.epoch);
}
r = closenatpmp(&natpmp);
printf("closenatpmp() returned %d (%s)\n", r, r==0?"SUCCESS":"FAILED");
if(r<0)
return 1;
return 0;
}

View File

@ -1,18 +0,0 @@
#! /usr/bin/python
# $Id: setup.py,v 1.3 2012/03/05 04:54:01 nanard Exp $
#
# python script to build the libnatpmp module under unix
#
# replace libnatpmp.a by libnatpmp.so for shared library usage
from distutils.core import setup, Extension
from distutils import sysconfig
sysconfig.get_config_vars()["OPT"] = ''
sysconfig.get_config_vars()["CFLAGS"] = ''
setup(name="libnatpmp", version="1.0",
ext_modules=[
Extension(name="libnatpmp", sources=["libnatpmpmodule.c"],
extra_objects=["libnatpmp.a"],
define_macros=[('ENABLE_STRNATPMPERR', None)]
)]
)

View File

@ -1,17 +0,0 @@
#! /usr/bin/python
# $Id: setupmingw32.py,v 1.3 2012/03/05 04:54:01 nanard Exp $
# python script to build the miniupnpc module under windows
#
from distutils.core import setup, Extension
from distutils import sysconfig
sysconfig.get_config_vars()["OPT"] = ''
sysconfig.get_config_vars()["CFLAGS"] = ''
setup(name="libnatpmp", version="1.0",
ext_modules=[
Extension(name="libnatpmp", sources=["libnatpmpmodule.c"],
libraries=["ws2_32"],
extra_objects=["libnatpmp.a"],
define_macros=[('ENABLE_STRNATPMPERR', None)]
)]
)

View File

@ -1,57 +0,0 @@
/* $Id: testgetgateway.c,v 1.7 2012/08/21 17:13:31 nanard Exp $ */
/* libnatpmp
Copyright (c) 2007-2011, Thomas BERNARD
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#ifdef WIN32
#include <winsock2.h>
#else
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include "getgateway.h"
int main(int argc, char * * argv)
{
(void)argc;
(void)argv;
struct in_addr gatewayaddr;
int r;
#ifdef WIN32
uint32_t temp = 0;
r = getdefaultgateway(&temp);
gatewayaddr.S_un.S_addr = temp;
#else
r = getdefaultgateway(&(gatewayaddr.s_addr));
#endif
if(r>=0)
printf("default gateway : %s\n", inet_ntoa(gatewayaddr));
else
fprintf(stderr, "getdefaultgateway() failed\n");
return 0;
}

View File

@ -9,6 +9,8 @@ set(src
NeighborDiscovery.cpp
OSUtils.cpp
PortMapper.cpp
PortMapper-miniupnpc.c
PortMapper-libnatpmp.c
)
set(headers
@ -56,5 +58,3 @@ if(APPLE)
add_executable(MacEthernetTapAgent MacEthernetTapAgent.c MacEthernetTapAgent.h)
target_include_directories(MacEthernetTapAgent PRIVATE ${CMAKE_BINARY_DIR})
endif(APPLE)

View File

@ -0,0 +1,14 @@
#define ENABLE_STRNATPMPERR
#define _BSD_SOURCE
#define _DEFAULT_SOURCE
#define _XOPEN_SOURCE 600
#ifdef __APPLE__
#ifndef _DARWIN_C_SOURCE
#define _DARWIN_C_SOURCE
#endif
#endif
#include "../ext/libnatpmp/getgateway.c"
#include "../ext/libnatpmp/wingettimeofday.c"
#include "../ext/libnatpmp/natpmp.c"

View File

@ -0,0 +1,41 @@
#define MINIUPNP_STATICLIB
#define MINIUPNPC_SET_SOCKET_TIMEOUT
#define MINIUPNPC_GET_SRC_ADDR
#define _BSD_SOURCE
#define _DEFAULT_SOURCE
#define _XOPEN_SOURCE 600
#define MINIUPNPC_VERSION_STRING "2.0"
#define UPNP_VERSION_STRING "UPnP/1.1"
#ifdef __LINUX__
#define OS_STRING "Linux"
#endif
#ifdef __APPLE__
#define OS_STRING "Darwin"
#endif
#ifdef __WINDOWS__
#define OS_STRING "Windows"
#endif
#ifndef OS_STRING
#define OS_STRING "ZeroTier"
#endif
#ifdef __APPLE__
#ifndef _DARWIN_C_SOURCE
#define _DARWIN_C_SOURCE
#endif
#endif
#include "../ext/miniupnpc/connecthostport.c"
#include "../ext/miniupnpc/igd_desc_parse.c"
#include "../ext/miniupnpc/minisoap.c"
#include "../ext/miniupnpc/miniupnpc.c"
#include "../ext/miniupnpc/miniwget.c"
#include "../ext/miniupnpc/minixml.c"
#include "../ext/miniupnpc/portlistingparse.c"
#include "../ext/miniupnpc/receivedata.c"
#include "../ext/miniupnpc/upnpcommands.c"
#include "../ext/miniupnpc/upnpdev.c"
#include "../ext/miniupnpc/upnperrors.c"
#include "../ext/miniupnpc/upnpreplyparse.c"
#include "../ext/miniupnpc/minissdpc.c"

View File

@ -24,8 +24,6 @@
* of your own application.
*/
#ifdef ZT_USE_MINIUPNPC
// Uncomment to dump debug messages
//#define ZT_PORTMAPPER_TRACE 1
@ -347,5 +345,3 @@ std::vector<InetAddress> PortMapper::get() const
}
} // namespace ZeroTier
#endif // ZT_USE_MINIUPNPC

View File

@ -24,8 +24,6 @@
* of your own application.
*/
#ifdef ZT_USE_MINIUPNPC
#ifndef ZT_PORTMAPPER_HPP
#define ZT_PORTMAPPER_HPP
@ -39,7 +37,7 @@
/**
* How frequently should we refresh our UPNP/NAT-PnP/whatever state?
*/
#define ZT_PORTMAPPER_REFRESH_DELAY 300000
#define ZT_PORTMAPPER_REFRESH_DELAY 120000
namespace ZeroTier {
@ -75,5 +73,3 @@ private:
} // namespace ZeroTier
#endif
#endif // ZT_USE_MINIUPNPC

View File

@ -7,14 +7,11 @@ endif(WIN32)
set(src
OneService.cpp
SoftwareUpdater.cpp
)
set(headers
OneService.hpp
SoftwareUpdater.hpp
)
add_library(${PROJECT_NAME} STATIC ${src} ${headers})
target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_11)

View File

@ -352,15 +352,6 @@ struct TcpConnection
Mutex writeq_m;
};
struct OneServiceIncomingPacket
{
uint64_t now;
int64_t sock;
struct sockaddr_storage from;
unsigned int size;
uint8_t data[ZT_MAX_MTU];
};
class OneServiceImpl : public OneService
{
public:
@ -383,7 +374,6 @@ public:
unsigned int _primaryPort;
unsigned int _secondaryPort;
unsigned int _tertiaryPort;
volatile unsigned int _udpPortPickerCounter;
// Local configuration and memo-ized information from it
json _localConfig;
@ -397,7 +387,7 @@ public:
std::vector< std::string > _interfacePrefixBlacklist;
Mutex _localConfig_m;
std::vector<InetAddress> explicitBind;
std::vector<InetAddress> _explicitBind;
/*
* To attempt to handle NAT/gateway craziness we use three local UDP ports:
@ -454,9 +444,7 @@ public:
// uPnP/NAT-PMP port mapper if enabled
bool _portMappingEnabled; // local.conf settings
#ifdef ZT_USE_MINIUPNPC
PortMapper *_portMapper;
#endif
// Set to false to force service to stop
volatile bool _run;
@ -478,15 +466,12 @@ public:
,_localControlSocket6((PhySocket *)0)
,_updateAutoApply(false)
,_primaryPort(port)
,_udpPortPickerCounter(0)
,_lastDirectReceiveFromGlobal(0)
,_lastRestart(0)
,_nextBackgroundTaskDeadline(0)
,_termReason(ONE_STILL_RUNNING)
,_portMappingEnabled(true)
#ifdef ZT_USE_MINIUPNPC
,_portMapper((PortMapper *)0)
#endif
,_run(true)
,_mqc(NULL)
{
@ -501,9 +486,7 @@ public:
_phy.close(_localControlSocket4);
_phy.close(_localControlSocket6);
#ifdef ZT_USE_MINIUPNPC
delete _portMapper;
#endif
delete _controller;
delete _mqc;
}
@ -609,7 +592,6 @@ public:
}
}
#ifdef ZT_USE_MINIUPNPC
if (_portMappingEnabled) {
// If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
// use the other two ports for that because some NATs do really funky
@ -633,7 +615,6 @@ public:
}
}
}
#endif
// Delete legacy iddb.d if present (cleanup)
OSUtils::rmDashRf((_homePath + ZT_PATH_SEPARATOR_S "iddb.d").c_str());
@ -658,7 +639,6 @@ public:
_lastRestart = clockShouldBe;
int64_t lastTapMulticastGroupCheck = 0;
int64_t lastBindRefresh = 0;
int64_t lastUpdateCheck = clockShouldBe;
int64_t lastMultipathModeUpdate = 0;
int64_t lastCleanedPeersDb = 0;
int64_t lastLocalInterfaceAddressCheck = (clockShouldBe - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give portmapper time to configure and other things time to settle
@ -706,7 +686,7 @@ public:
if (_ports[i])
p[pc++] = _ports[i];
}
_binder.refresh(_phy,p,pc,explicitBind,*this);
_binder.refresh(_phy,p,pc,_explicitBind,*this);
{
Mutex::Lock _l(_nets_m);
for(std::map<uint64_t,NetworkState>::iterator n(_nets.begin());n!=_nets.end();++n) {
@ -756,13 +736,11 @@ public:
_node->clearLocalInterfaceAddresses();
#ifdef ZT_USE_MINIUPNPC
if (_portMapper) {
std::vector<InetAddress> mappedAddresses(_portMapper->get());
for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
_node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
}
#endif
std::vector<InetAddress> boundAddrs(_binder.allBoundLocalInterfaceAddresses());
for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
@ -898,7 +876,7 @@ public:
if (ips.length() > 0) {
InetAddress ip(ips.c_str());
if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6))
explicitBind.push_back(ip);
_explicitBind.push_back(ip);
}
}
}
@ -1125,11 +1103,7 @@ public:
}
}
#ifdef ZT_USE_MINIUPNPC
settings["portMappingEnabled"] = OSUtils::jsonBool(settings["portMappingEnabled"],true);
#else
settings["portMappingEnabled"] = false; // not supported in build
#endif
scode = 200;
} else if (ps[0] == "network") {