pax_global_header00006660000000000000000000000064126050523650014516gustar00rootroot0000000000000052 comment=64dad4c24780921ab0c6388787d68162f8e80a00 weupnp-weupnp-0.1.4/000077500000000000000000000000001260505236500143525ustar00rootroot00000000000000weupnp-weupnp-0.1.4/.gitignore000066400000000000000000000001131260505236500163350ustar00rootroot00000000000000target/* .DS_Store .classpath .project .settings *.iml *.ipr *.iws .idea/* weupnp-weupnp-0.1.4/CONTRIBUTING.md000066400000000000000000000011721260505236500166040ustar00rootroot00000000000000# Thank you for consdering constributing to weupnp. Before you submit your pull request, please considering the following: 1. be consistent with the style of the existing code (brackets, newlines, whitespace) 2. weupnp was designed to be minimal, so do not introduce dependencies to new libraries unless there is some strong reason to do so, 3. provide us with context in the pull request description: each device behaves slightly different and we do not have access to all of them, so it would help us to know what exactly was the problem you were trying to solve. Other than that, we would be happy to get your help! Thank you weupnp-weupnp-0.1.4/README.md000066400000000000000000000007021260505236500156300ustar00rootroot00000000000000# weupnp A lightweight Java library designed to implement the UPnP protocol and handle port mappings on Gateway Devices. You can find more information on the library at the project website: http://bitletorg.github.io/weupnp/ If you use Maven, you can start using weupnp by including the following dependency: ```xml org.bitlet weupnp 0.1.3 ``` weupnp-weupnp-0.1.4/pom.xml000066400000000000000000000106651260505236500156770ustar00rootroot00000000000000 4.0.0 org.bitlet weupnp bundle 0.1.4 weupnp https://github.com/bitletorg/weupnp org.sonatype.oss oss-parent 7 org.apache.maven.plugins maven-compiler-plugin 1.5 1.5 ${project.build.sourceEncoding} 3.1 org.apache.maven.plugins maven-resources-plugin ${project.build.sourceEncoding} 2.6 org.apache.maven.plugins maven-jar-plugin org.bitlet.weupnp.Main org.bitlet.weupnp true true 2.4 org.apache.felix maven-bundle-plugin 2.5.4 true UTF-8 Weupnp is a lightweight Java library, released under the LGPL licence, designed to implement the UPnP protocol to handle port mappings on Gateway Devices. scm:git:https://github.com/bitletorg/weupnp.git scm:git:https://github.com/bitletorg/weupnp.git https://github.com/bitletorg/weupnp GNU Lesser General Public License (LGPL) ale.bahgat Alessandro Bahgat Shehata daniele.castagna Daniele Castagna christophercyll Cristopher Cyll release-sign-artifacts performRelease true org.apache.maven.plugins maven-gpg-plugin sign-artifacts verify sign weupnp-weupnp-0.1.4/src/000077500000000000000000000000001260505236500151415ustar00rootroot00000000000000weupnp-weupnp-0.1.4/src/main/000077500000000000000000000000001260505236500160655ustar00rootroot00000000000000weupnp-weupnp-0.1.4/src/main/java/000077500000000000000000000000001260505236500170065ustar00rootroot00000000000000weupnp-weupnp-0.1.4/src/main/java/org/000077500000000000000000000000001260505236500175755ustar00rootroot00000000000000weupnp-weupnp-0.1.4/src/main/java/org/bitlet/000077500000000000000000000000001260505236500210605ustar00rootroot00000000000000weupnp-weupnp-0.1.4/src/main/java/org/bitlet/weupnp/000077500000000000000000000000001260505236500223765ustar00rootroot00000000000000weupnp-weupnp-0.1.4/src/main/java/org/bitlet/weupnp/GatewayDevice.java000066400000000000000000000526001260505236500257650ustar00rootroot00000000000000/* * weupnp - Trivial upnp java library * * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com * Daniele Castagna - daniele dot castagna at gmail dot com * */ package org.bitlet.weupnp; import java.io.IOException; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * A GatewayDevice is a class that abstracts UPnP-compliant gateways *

* It holds all the information that comes back as UPnP responses, and * provides methods to issue UPnP commands to a gateway. * * @author casta */ public class GatewayDevice { /** * Receive timeout when requesting data from device */ private static final int DEFAULT_HTTP_RECEIVE_TIMEOUT = 7000; private String st; private String location; private String serviceType; private String serviceTypeCIF; private String urlBase; private String controlURL; private String controlURLCIF; private String eventSubURL; private String eventSubURLCIF; private String sCPDURL; private String sCPDURLCIF; private String deviceType; private String deviceTypeCIF; // description data /** * The friendly (human readable) name associated with this device */ private String friendlyName; /** * The device manufacturer name */ private String manufacturer; /** * The model description as a string */ private String modelDescription; /** * The URL that can be used to access the IGD interface */ private String presentationURL; /** * The address used to reach this machine from the GatewayDevice */ private InetAddress localAddress; /** * The model number (used by the manufacturer to identify the product) */ private String modelNumber; /** * The model name */ private String modelName; /** * Timeout in milliseconds for HTTP reads */ private static int httpReadTimeout = DEFAULT_HTTP_RECEIVE_TIMEOUT; /** * Creates a new instance of GatewayDevice */ public GatewayDevice() { } /** * Retrieves the properties and description of the GatewayDevice. *

* Connects to the device's {@link #location} and parses the response * using a {@link GatewayDeviceHandler} to populate the fields of this * class * * @throws SAXException if an error occurs while parsing the request * @throws IOException on communication errors * @see org.bitlet.weupnp.GatewayDeviceHandler */ public void loadDescription() throws SAXException, IOException { URLConnection urlConn = new URL(getLocation()).openConnection(); urlConn.setReadTimeout(httpReadTimeout); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new GatewayDeviceHandler(this)); parser.parse(new InputSource(urlConn.getInputStream())); /* fix urls */ String ipConDescURL; if (urlBase != null && urlBase.trim().length() > 0) { ipConDescURL = urlBase; } else { ipConDescURL = location; } int lastSlashIndex = ipConDescURL.indexOf('/', 7); if (lastSlashIndex > 0) { ipConDescURL = ipConDescURL.substring(0, lastSlashIndex); } sCPDURL = copyOrCatUrl(ipConDescURL, sCPDURL); controlURL = copyOrCatUrl(ipConDescURL, controlURL); controlURLCIF = copyOrCatUrl(ipConDescURL, controlURLCIF); presentationURL = copyOrCatUrl(ipConDescURL, presentationURL); } /** * Issues UPnP commands to a GatewayDevice that can be reached at the * specified url *

* The command is identified by a service and an action * and can receive arguments * * @param url the url to use to contact the device * @param service the service to invoke * @param action the specific action to perform * @param args the command arguments * @return the response to the performed command, as a name-value map. * In case errors occur, the returned map will be empty. * @throws IOException on communication errors * @throws SAXException if errors occur while parsing the response */ public static Map simpleUPnPcommand(String url, String service, String action, Map args) throws IOException, SAXException { String soapAction = "\"" + service + "#" + action + "\""; StringBuilder soapBody = new StringBuilder(); soapBody.append("\r\n" + "" + "" + ""); if (args != null && args.size() > 0) { Set> entrySet = args.entrySet(); for (Map.Entry entry : entrySet) { soapBody.append("<" + entry.getKey() + ">" + entry.getValue() + ""); } } soapBody.append(""); soapBody.append(""); URL postUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(httpReadTimeout); conn.setReadTimeout(httpReadTimeout); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml"); conn.setRequestProperty("SOAPAction", soapAction); conn.setRequestProperty("Connection", "Close"); byte[] soapBodyBytes = soapBody.toString().getBytes(); conn.setRequestProperty("Content-Length", String.valueOf(soapBodyBytes.length)); conn.getOutputStream().write(soapBodyBytes); Map nameValue = new HashMap(); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new NameValueHandler(nameValue)); if (conn.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) { try { // attempt to parse the error message parser.parse(new InputSource(conn.getErrorStream())); } catch (SAXException e) { // ignore the exception // FIXME We probably need to find a better way to return // significant information when we reach this point } conn.disconnect(); return nameValue; } else { parser.parse(new InputSource(conn.getInputStream())); conn.disconnect(); return nameValue; } } /** * Retrieves the connection status of this device * * @return true if connected, false otherwise * @throws IOException * @throws SAXException * @see #simpleUPnPcommand(java.lang.String, java.lang.String, * java.lang.String, java.util.Map) */ public boolean isConnected() throws IOException, SAXException { Map nameValue = simpleUPnPcommand(controlURL, serviceType, "GetStatusInfo", null); String connectionStatus = nameValue.get("NewConnectionStatus"); if (connectionStatus != null && connectionStatus.equalsIgnoreCase("Connected")) { return true; } return false; } /** * Retrieves the external IP address associated with this device *

* The external address is the address that can be used to connect to the * GatewayDevice from the external network * * @return the external IP * @throws IOException * @throws SAXException * @see #simpleUPnPcommand(java.lang.String, java.lang.String, * java.lang.String, java.util.Map) */ public String getExternalIPAddress() throws IOException, SAXException { Map nameValue = simpleUPnPcommand(controlURL, serviceType, "GetExternalIPAddress", null); return nameValue.get("NewExternalIPAddress"); } /** * Adds a new port mapping to the GatewayDevices using the supplied * parameters. * * @param externalPort the external associated with the new mapping * @param internalPort the internal port associated with the new mapping * @param internalClient the internal client associated with the new mapping * @param protocol the protocol associated with the new mapping * @param description the mapping description * @return true if the mapping was successfully added, false otherwise * @throws IOException * @throws SAXException * @see #simpleUPnPcommand(java.lang.String, java.lang.String, * java.lang.String, java.util.Map) * @see PortMappingEntry */ public boolean addPortMapping(int externalPort, int internalPort, String internalClient, String protocol, String description) throws IOException, SAXException { Map args = new LinkedHashMap(); args.put("NewRemoteHost", ""); // wildcard, any remote host matches args.put("NewExternalPort", Integer.toString(externalPort)); args.put("NewProtocol", protocol); args.put("NewInternalPort", Integer.toString(internalPort)); args.put("NewInternalClient", internalClient); args.put("NewEnabled", Integer.toString(1)); args.put("NewPortMappingDescription", description); args.put("NewLeaseDuration", Integer.toString(0)); Map nameValue = simpleUPnPcommand(controlURL, serviceType, "AddPortMapping", args); return nameValue.get("errorCode") == null; } /** * Queries the GatewayDevice to retrieve a specific port mapping entry, * corresponding to specified criteria, if present. *

* Retrieves the PortMappingEntry associated with * externalPort and protocol, if present. * * @param externalPort the external port * @param protocol the protocol (TCP or UDP) * @param portMappingEntry the entry containing the details, in any is * present, null otherwise. (used as return value) * @return true if a valid mapping is found * @throws IOException * @throws SAXException * @todo consider refactoring this method to make it consistent with * Java practices (return the port mapping) * @see #simpleUPnPcommand(java.lang.String, java.lang.String, * java.lang.String, java.util.Map) * @see PortMappingEntry */ public boolean getSpecificPortMappingEntry(int externalPort, String protocol, final PortMappingEntry portMappingEntry) throws IOException, SAXException { portMappingEntry.setExternalPort(externalPort); portMappingEntry.setProtocol(protocol); Map args = new LinkedHashMap(); args.put("NewRemoteHost", ""); // wildcard, any remote host matches args.put("NewExternalPort", Integer.toString(externalPort)); args.put("NewProtocol", protocol); Map nameValue = simpleUPnPcommand(controlURL, serviceType, "GetSpecificPortMappingEntry", args); if (nameValue.isEmpty() || nameValue.containsKey("errorCode")) return false; if (!nameValue.containsKey("NewInternalClient") || !nameValue.containsKey("NewInternalPort")) return false; portMappingEntry.setProtocol(protocol); portMappingEntry.setEnabled(nameValue.get("NewEnabled")); portMappingEntry.setInternalClient(nameValue.get("NewInternalClient")); portMappingEntry.setExternalPort(externalPort); portMappingEntry.setPortMappingDescription(nameValue.get("NewPortMappingDescription")); portMappingEntry.setRemoteHost(nameValue.get("NewRemoteHost")); try { portMappingEntry.setInternalPort(Integer.parseInt(nameValue.get("NewInternalPort"))); } catch (NumberFormatException nfe) { // skip bad port } return true; } /** * Returns a specific port mapping entry, depending on a the supplied index. * * @param index the index of the desired port mapping * @param portMappingEntry the entry containing the details, in any is * present, null otherwise. (used as return value) * @return true if a valid mapping is found * @throws IOException * @throws SAXException * @todo consider refactoring this method to make it consistent with * Java practices (return the port mapping) * @see #simpleUPnPcommand(java.lang.String, java.lang.String, * java.lang.String, java.util.Map) * @see PortMappingEntry */ public boolean getGenericPortMappingEntry(int index, final PortMappingEntry portMappingEntry) throws IOException, SAXException { Map args = new LinkedHashMap(); args.put("NewPortMappingIndex", Integer.toString(index)); Map nameValue = simpleUPnPcommand(controlURL, serviceType, "GetGenericPortMappingEntry", args); if (nameValue.isEmpty() || nameValue.containsKey("errorCode")) return false; portMappingEntry.setRemoteHost(nameValue.get("NewRemoteHost")); portMappingEntry.setInternalClient(nameValue.get("NewInternalClient")); portMappingEntry.setProtocol(nameValue.get("NewProtocol")); portMappingEntry.setEnabled(nameValue.get("NewEnabled")); portMappingEntry.setPortMappingDescription( nameValue.get("NewPortMappingDescription")); try { portMappingEntry.setInternalPort( Integer.parseInt(nameValue.get("NewInternalPort"))); } catch (Exception e) { } try { portMappingEntry.setExternalPort( Integer.parseInt(nameValue.get("NewExternalPort"))); } catch (Exception e) { } return true; } /** * Retrieves the number of port mappings that are registered on the * GatewayDevice. * * @return the number of port mappings * @throws IOException * @throws SAXException */ public Integer getPortMappingNumberOfEntries() throws IOException, SAXException { Map nameValue = simpleUPnPcommand(controlURL, serviceType, "GetPortMappingNumberOfEntries", null); Integer portMappingNumber = null; try { portMappingNumber = Integer.valueOf( nameValue.get("NewPortMappingNumberOfEntries")); } catch (Exception e) { } return portMappingNumber; } /** * Deletes the port mapping associated to externalPort and * protocol * * @param externalPort the external port * @param protocol the protocol * @return true if removal was successful * @throws IOException * @throws SAXException */ public boolean deletePortMapping(int externalPort, String protocol) throws IOException, SAXException { Map args = new LinkedHashMap(); args.put("NewRemoteHost", ""); args.put("NewExternalPort", Integer.toString(externalPort)); args.put("NewProtocol", protocol); Map nameValue = simpleUPnPcommand(controlURL, serviceType, "DeletePortMapping", args); return true; } // getters and setters /** * Gets the local address to connect the gateway through * * @return the {@link #localAddress} */ public InetAddress getLocalAddress() { return localAddress; } /** * Sets the {@link #localAddress} * * @param localAddress the address to set */ public void setLocalAddress(InetAddress localAddress) { this.localAddress = localAddress; } public String getSt() { return st; } public void setSt(String st) { this.st = st; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getServiceType() { return serviceType; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } public String getServiceTypeCIF() { return serviceTypeCIF; } public void setServiceTypeCIF(String serviceTypeCIF) { this.serviceTypeCIF = serviceTypeCIF; } public String getControlURL() { return controlURL; } public void setControlURL(String controlURL) { this.controlURL = controlURL; } public String getControlURLCIF() { return controlURLCIF; } public void setControlURLCIF(String controlURLCIF) { this.controlURLCIF = controlURLCIF; } public String getEventSubURL() { return eventSubURL; } public void setEventSubURL(String eventSubURL) { this.eventSubURL = eventSubURL; } public String getEventSubURLCIF() { return eventSubURLCIF; } public void setEventSubURLCIF(String eventSubURLCIF) { this.eventSubURLCIF = eventSubURLCIF; } public String getSCPDURL() { return sCPDURL; } public void setSCPDURL(String sCPDURL) { this.sCPDURL = sCPDURL; } public String getSCPDURLCIF() { return sCPDURLCIF; } public void setSCPDURLCIF(String sCPDURLCIF) { this.sCPDURLCIF = sCPDURLCIF; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getDeviceTypeCIF() { return deviceTypeCIF; } public void setDeviceTypeCIF(String deviceTypeCIF) { this.deviceTypeCIF = deviceTypeCIF; } public String getURLBase() { return urlBase; } public void setURLBase(String uRLBase) { this.urlBase = uRLBase; } public String getFriendlyName() { return friendlyName; } public void setFriendlyName(String friendlyName) { this.friendlyName = friendlyName; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getModelDescription() { return modelDescription; } public void setModelDescription(String modelDescription) { this.modelDescription = modelDescription; } public String getPresentationURL() { return presentationURL; } public void setPresentationURL(String presentationURL) { this.presentationURL = presentationURL; } public String getModelName() { return modelName; } public void setModelName(String modelName) { this.modelName = modelName; } public String getModelNumber() { return modelNumber; } public void setModelNumber(String modelNumber) { this.modelNumber = modelNumber; } /** * Gets the timeout for actions on the device. * @return timeout in milliseconds */ public static int getHttpReadTimeout() { return httpReadTimeout; } /** * Sets the timeout for actions on the device. * @param milliseconds the new timeout in milliseconds */ public static void setHttpReadTimeout(int milliseconds) { httpReadTimeout = milliseconds; } // private methods private String copyOrCatUrl(String dst, String src) { if (src != null) { if (src.startsWith("http://")) { dst = src; } else { if (!src.startsWith("/")) { dst += "/"; } dst += src; } } return dst; } } weupnp-weupnp-0.1.4/src/main/java/org/bitlet/weupnp/GatewayDeviceHandler.java000066400000000000000000000175571260505236500272770ustar00rootroot00000000000000/* * weupnp - Trivial upnp java library * * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com * Daniele Castagna - daniele dot castagna at gmail dot com * */ package org.bitlet.weupnp; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * A SAX handler used to parse XML data representing a GatewayDevice * * @see org.xml.sax.helpers.DefaultHandler */ public class GatewayDeviceHandler extends DefaultHandler { /** * The device that should be populated with data coming from the stream * being parsed */ private GatewayDevice device; /** * Creates a new instance of GatewayDeviceHandler that will populate the * fields of the supplied device * * @param device the device to configure */ public GatewayDeviceHandler(final GatewayDevice device) { this.device = device; } /** state variables */ private String currentElement; private int level = 0; private short state = 0; /** * Receive notification of the start of an element. * * Caches the element as {@link #currentElement}, and keeps track of some * basic state information. * * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @param attributes The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#startElement */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { currentElement = localName; level++; if (state < 1 && "serviceList".compareTo(currentElement) == 0) { state = 1; } } /** * Receive notification of the end of an element. * * Used to update state information. * *

By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the end of * each element (such as finalising a tree node or writing * output to a file).

* * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#endElement */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { currentElement = ""; level--; if (localName.compareTo("service")==0){ if (device.getServiceTypeCIF() != null && device.getServiceTypeCIF().compareTo("urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1") == 0) state = 2; if (device.getServiceType() != null && ( device.getServiceType().contains("urn:schemas-upnp-org:service:WANIPConnection:") || device.getServiceType().contains("urn:schemas-upnp-org:service:WANPPPConnection:") )) state = 3; } } /** * Receive notification of character data inside an element. * * It is used to read the values of the relevant fields of the device being * configured. * * @param ch The characters. * @param start The start position in the character array. * @param length The number of characters to use from the * character array. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#characters */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (currentElement.compareTo("URLBase") == 0) device.setURLBase(new String(ch,start,length)); else if (state<=1) { if (state == 0) { if ("friendlyName".compareTo(currentElement) == 0) device.setFriendlyName(new String(ch,start,length)); else if ("manufacturer".compareTo(currentElement) == 0) device.setManufacturer(new String(ch,start,length)); else if ("modelDescription".compareTo(currentElement) == 0) device.setModelDescription(new String(ch,start,length)); else if ("presentationURL".compareTo(currentElement) == 0) device.setPresentationURL(new String(ch,start,length)); else if ("modelNumber".compareTo(currentElement) == 0) device.setModelNumber(new String(ch,start,length)); else if ("modelName".compareTo(currentElement) == 0) device.setModelName(new String(ch,start,length)); } if( currentElement.compareTo("serviceType") == 0 ) device.setServiceTypeCIF(new String(ch,start,length)); else if( currentElement.compareTo( "controlURL") == 0) device.setControlURLCIF(new String(ch,start,length)); else if( currentElement.compareTo( "eventSubURL") == 0 ) device.setEventSubURLCIF(new String(ch,start,length)); else if( currentElement.compareTo( "SCPDURL") == 0 ) device.setSCPDURLCIF(new String(ch,start,length)); else if( currentElement.compareTo( "deviceType") == 0 ) device.setDeviceTypeCIF(new String(ch,start,length)); }else if (state==2){ if( currentElement.compareTo("serviceType") == 0 ) device.setServiceType(new String(ch,start,length)); else if( currentElement.compareTo( "controlURL") == 0) device.setControlURL(new String(ch,start,length)); else if( currentElement.compareTo( "eventSubURL") == 0 ) device.setEventSubURL(new String(ch,start,length)); else if( currentElement.compareTo( "SCPDURL") == 0 ) device.setSCPDURL(new String(ch,start,length)); else if( currentElement.compareTo( "deviceType") == 0 ) device.setDeviceType(new String(ch,start,length)); } } } weupnp-weupnp-0.1.4/src/main/java/org/bitlet/weupnp/GatewayDiscover.java000066400000000000000000000314121260505236500263420ustar00rootroot00000000000000/* * weupnp - Trivial upnp java library * * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com * Daniele Castagna - daniele dot castagna at gmail dot com * */ package org.bitlet.weupnp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * Handles the discovery of GatewayDevices, via the {@link org.bitlet.weupnp.GatewayDiscover#discover()} method. */ public class GatewayDiscover { /** * The SSDP port */ public static final int PORT = 1900; /** * The broadcast address to use when trying to contact UPnP devices */ public static final String IP = "239.255.255.250"; /** * The default timeout for the initial broadcast request */ private static final int DEFAULT_TIMEOUT = 3000; /** * The timeout for the initial broadcast request */ private int timeout = DEFAULT_TIMEOUT; /** * The gateway types the discover have to search. */ private String[] searchTypes; /** * The default gateway types to use in search */ private static final String[] DEFAULT_SEARCH_TYPES = { "urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1" }; /** * A map of the GatewayDevices discovered so far. * The assumption is that a machine is connected to up to a Gateway Device * per InetAddress */ private final Map devices = new HashMap(); /* * Thread class for sending a search datagram and process the response. */ private class SendDiscoveryThread extends Thread { InetAddress ip; String searchMessage; SendDiscoveryThread(InetAddress localIP, String searchMessage) { this.ip = localIP; this.searchMessage = searchMessage; } @Override public void run() { DatagramSocket ssdp = null; try { // Create socket bound to specified local address ssdp = new DatagramSocket(new InetSocketAddress(ip, 0)); byte[] searchMessageBytes = searchMessage.getBytes(); DatagramPacket ssdpDiscoverPacket = new DatagramPacket(searchMessageBytes, searchMessageBytes.length); ssdpDiscoverPacket.setAddress(InetAddress.getByName(IP)); ssdpDiscoverPacket.setPort(PORT); ssdp.send(ssdpDiscoverPacket); ssdp.setSoTimeout(GatewayDiscover.this.timeout); boolean waitingPacket = true; while (waitingPacket) { DatagramPacket receivePacket = new DatagramPacket(new byte[1536], 1536); try { ssdp.receive(receivePacket); byte[] receivedData = new byte[receivePacket.getLength()]; System.arraycopy(receivePacket.getData(), 0, receivedData, 0, receivePacket.getLength()); // Create GatewayDevice from response GatewayDevice gatewayDevice = parseMSearchReply(receivedData); gatewayDevice.setLocalAddress(ip); gatewayDevice.loadDescription(); // verify that the search type is among the requested ones if (Arrays.asList(searchTypes).contains(gatewayDevice.getSt())) { synchronized (devices) { devices.put(ip, gatewayDevice); break; // device added for this ip, nothing further to do } } } catch (SocketTimeoutException ste) { waitingPacket = false; } } } catch (Exception e) { // e.printStackTrace(); } finally { if (null != ssdp) { ssdp.close(); } } } } /** * Constructor. * * By default it's looking for 3 types of gateways. * */ public GatewayDiscover() { this(DEFAULT_SEARCH_TYPES); } /** * Constructor of the gateway discover service. * * @param st The search type you are looking for */ public GatewayDiscover(String st) { this(new String[]{st}); } /** * Constructor. * * @param types The search types the discover have to look for */ public GatewayDiscover(String[] types) { this.searchTypes = types; } /** * Gets the timeout for socket connections of the initial broadcast request. * @return timeout in milliseconds */ public int getTimeout() { return this.timeout; } /** * Sets the timeout for socket connections of the initial broadcast request. * @param milliseconds the new timeout in milliseconds */ public void setTimeout(int milliseconds) { this.timeout = milliseconds; } /** * Discovers Gateway Devices on the network(s) the executing machine is * connected to. *

* The host may be connected to different networks via different network * interfaces. * Assumes that each network interface has a different InetAddress and * returns a map associating every GatewayDevice (responding to a broadcast * discovery message) with the InetAddress it is connected to. * * @return a map containing a GatewayDevice per InetAddress * @throws SocketException * @throws UnknownHostException * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ public Map discover() throws SocketException, UnknownHostException, IOException, SAXException, ParserConfigurationException { Collection ips = getLocalInetAddresses(true, false, false); for (int i = 0; i < searchTypes.length; i++) { String searchMessage = "M-SEARCH * HTTP/1.1\r\n" + "HOST: " + IP + ":" + PORT + "\r\n" + "ST: " + searchTypes[i] + "\r\n" + "MAN: \"ssdp:discover\"\r\n" + "MX: 2\r\n" + // seconds to delay response "\r\n"; // perform search requests for multiple network adapters concurrently Collection threads = new ArrayList(); for (InetAddress ip : ips) { SendDiscoveryThread thread = new SendDiscoveryThread(ip, searchMessage); threads.add(thread); thread.start(); } // wait for all search threads to finish for (SendDiscoveryThread thread : threads) try { thread.join(); } catch (InterruptedException e) { // continue with next thread } // If a search type found devices, don't try with different search type if (!devices.isEmpty()) break; } // loop SEARCHTYPES return devices; } /** * Parses the reply from UPnP devices * * @param reply the raw bytes received as a reply * @return the representation of a GatewayDevice */ private GatewayDevice parseMSearchReply(byte[] reply) { GatewayDevice device = new GatewayDevice(); String replyString = new String(reply); StringTokenizer st = new StringTokenizer(replyString, "\n"); while (st.hasMoreTokens()) { String line = st.nextToken().trim(); if (line.isEmpty()) continue; if (line.startsWith("HTTP/1.") || line.startsWith("NOTIFY *")) continue; String key = line.substring(0, line.indexOf(':')); String value = line.length() > key.length() + 1 ? line.substring(key.length() + 1) : null; key = key.trim(); if (value != null) { value = value.trim(); } if (key.compareToIgnoreCase("location") == 0) { device.setLocation(value); } else if (key.compareToIgnoreCase("st") == 0) { // Search Target device.setSt(value); } } return device; } /** * Gets the first connected gateway * * @return the first GatewayDevice which is connected to the network, or * null if none present */ public GatewayDevice getValidGateway() { for (GatewayDevice device : devices.values()) { try { if (device.isConnected()) { return device; } } catch (Exception e) { } } return null; } /** * Returns list of all discovered gateways. Is empty when no gateway is found. */ public Map getAllGateways() { return devices; } /** * Retrieves all local IP addresses from all present network devices. * * @param getIPv4 boolean flag if IPv4 addresses shall be retrieved * @param getIPv6 boolean flag if IPv6 addresses shall be retrieved * @param sortIPv4BeforeIPv6 if true, IPv4 addresses will be sorted before IPv6 addresses * @return Collection if {@link InetAddress}es */ private List getLocalInetAddresses(boolean getIPv4, boolean getIPv6, boolean sortIPv4BeforeIPv6) { List arrayIPAddress = new ArrayList(); int lastIPv4Index = 0; // Get all network interfaces Enumeration networkInterfaces; try { networkInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { return arrayIPAddress; } if (networkInterfaces == null) return arrayIPAddress; // For every suitable network interface, get all IP addresses while (networkInterfaces.hasMoreElements()) { NetworkInterface card = networkInterfaces.nextElement(); try { // skip devices, not suitable to search gateways for if (card.isLoopback() || card.isPointToPoint() || card.isVirtual() || !card.isUp()) continue; } catch (SocketException e) { continue; } Enumeration addresses = card.getInetAddresses(); if (addresses == null) continue; while (addresses.hasMoreElements()) { InetAddress inetAddress = addresses.nextElement(); int index = arrayIPAddress.size(); if (!getIPv4 || !getIPv6) { if (getIPv4 && !Inet4Address.class.isInstance(inetAddress)) continue; if (getIPv6 && !Inet6Address.class.isInstance(inetAddress)) continue; } else if (sortIPv4BeforeIPv6 && Inet4Address.class.isInstance(inetAddress)) { index = lastIPv4Index++; } arrayIPAddress.add(index, inetAddress); } } return arrayIPAddress; } } weupnp-weupnp-0.1.4/src/main/java/org/bitlet/weupnp/Main.java000066400000000000000000000117171260505236500241340ustar00rootroot00000000000000/* * weupnp - Trivial upnp java library * * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, FΩifth Floor, Boston, MA 02110-1301 USA * * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com * Daniele Castagna - daniele dot castagna at gmail dot com * */ /* * refer to miniupnpc-1.0-RC8 */ package org.bitlet.weupnp; import java.net.InetAddress; import java.text.DateFormat; import java.util.Date; import java.util.Map; /** * This class contains a trivial main method that can be used to test whether * weupnp is able to manipulate port mappings on a IGD (Internet Gateway * Device) on the same network. * * @author Alessandro Bahgat Shehata */ public class Main { private static int SAMPLE_PORT = 6991; private static short WAIT_TIME = 10; private static boolean LIST_ALL_MAPPINGS = false; public static void main(String[] args) throws Exception{ addLogLine("Starting weupnp"); GatewayDiscover gatewayDiscover = new GatewayDiscover(); addLogLine("Looking for Gateway Devices..."); Map gateways = gatewayDiscover.discover(); if (gateways.isEmpty()) { addLogLine("No gateways found"); addLogLine("Stopping weupnp"); return; } addLogLine(gateways.size()+" gateway(s) found\n"); int counter=0; for (GatewayDevice gw: gateways.values()) { counter++; addLogLine("Listing gateway details of device #" + counter+ "\n\tFriendly name: " + gw.getFriendlyName()+ "\n\tPresentation URL: " + gw.getPresentationURL()+ "\n\tModel name: " + gw.getModelName()+ "\n\tModel number: " + gw.getModelNumber()+ "\n\tLocal interface address: " + gw.getLocalAddress().getHostAddress()+"\n"); } // choose the first active gateway for the tests GatewayDevice activeGW = gatewayDiscover.getValidGateway(); if (null != activeGW) { addLogLine("Using gateway: " + activeGW.getFriendlyName()); } else { addLogLine("No active gateway device found"); addLogLine("Stopping weupnp"); return; } // testing PortMappingNumberOfEntries Integer portMapCount = activeGW.getPortMappingNumberOfEntries(); addLogLine("GetPortMappingNumberOfEntries: " + (portMapCount!=null?portMapCount.toString():"(unsupported)")); // testing getGenericPortMappingEntry PortMappingEntry portMapping = new PortMappingEntry(); if (LIST_ALL_MAPPINGS) { int pmCount = 0; do { if (activeGW.getGenericPortMappingEntry(pmCount,portMapping)) addLogLine("Portmapping #"+pmCount+" successfully retrieved ("+portMapping.getPortMappingDescription()+":"+portMapping.getExternalPort()+")"); else{ addLogLine("Portmapping #"+pmCount+" retrieval failed"); break; } pmCount++; } while (portMapping!=null); } else { if (activeGW.getGenericPortMappingEntry(0,portMapping)) addLogLine("Portmapping #0 successfully retrieved ("+portMapping.getPortMappingDescription()+":"+portMapping.getExternalPort()+")"); else addLogLine("Portmapping #0 retrival failed"); } InetAddress localAddress = activeGW.getLocalAddress(); addLogLine("Using local address: "+ localAddress.getHostAddress()); String externalIPAddress = activeGW.getExternalIPAddress(); addLogLine("External address: "+ externalIPAddress); addLogLine("Querying device to see if a port mapping already exists for port "+ SAMPLE_PORT); if (activeGW.getSpecificPortMappingEntry(SAMPLE_PORT,"TCP",portMapping)) { addLogLine("Port "+SAMPLE_PORT+" is already mapped. Aborting test."); return; } else { addLogLine("Mapping free. Sending port mapping request for port "+SAMPLE_PORT); // test static lease duration mapping if (activeGW.addPortMapping(SAMPLE_PORT,SAMPLE_PORT,localAddress.getHostAddress(),"TCP","test")) { addLogLine("Mapping SUCCESSFUL. Waiting "+WAIT_TIME+" seconds before removing mapping..."); Thread.sleep(1000*WAIT_TIME); if (activeGW.deletePortMapping(SAMPLE_PORT,"TCP")) { addLogLine("Port mapping removed, test SUCCESSFUL"); } else { addLogLine("Port mapping removal FAILED"); } } } addLogLine("Stopping weupnp"); } private static void addLogLine(String line) { String timeStamp = DateFormat.getTimeInstance().format(new Date()); String logline = timeStamp+": "+line+"\n"; System.out.print(logline); } } weupnp-weupnp-0.1.4/src/main/java/org/bitlet/weupnp/NameValueHandler.java000066400000000000000000000120231260505236500264120ustar00rootroot00000000000000/* * weupnp - Trivial upnp java library * * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com * Daniele Castagna - daniele dot castagna at gmail dot com * */ package org.bitlet.weupnp; import java.util.Map; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * A simple SAX handler that is used to parse XML name value pairs in the form * <name>value</name> * * @see org.xml.sax.helpers.DefaultHandler */ public class NameValueHandler extends DefaultHandler { /** * A reference to the name-value map to populate with the data being read */ private Map nameValue; /** * The last read element */ private String currentElement; /** * Creates a new instance of a NameValueHandler, storing values in * the supplied map * * @param nameValue the map to store name-value pairs in */ public NameValueHandler(Map nameValue) { this.nameValue = nameValue; } /** * Receive notification of the start of an element. * * Caches the element as {@link #currentElement}, so that it will be stored * as a map key when the corresponding value will be read. * * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @param attributes The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#startElement */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { currentElement = localName; } /** * Receive notification of the end of an element. * * It is used to reset currentElement when the XML node is closed. * Note: this works only when the data we are interested in does not contain * child nodes. * * Based on a patch provided by christophercyll and attached to issue #4: * http://code.google.com/p/weupnp/issues/detail?id=4 * * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @throws SAXException Any SAX exception, possibly * wrapping another exception. */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { currentElement = null; } /** * Receive notification of character data inside an element. * * Stores the characters as value, using {@link #currentElement} as a key * * @param ch The characters. * @param start The start position in the character array. * @param length The number of characters to use from the * character array. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#characters */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (currentElement != null) { String value = new String(ch,start,length); String old = nameValue.put(currentElement, value); if (old != null) { nameValue.put(currentElement, old + value); } } } } weupnp-weupnp-0.1.4/src/main/java/org/bitlet/weupnp/PortMappingEntry.java000066400000000000000000000122751260505236500265320ustar00rootroot00000000000000/* * weupnp - Trivial upnp java library * * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com * Daniele Castagna - daniele dot castagna at gmail dot com * */ package org.bitlet.weupnp; /** * A PortMappingEntry is the class used to represent port mappings on * the GatewayDevice. * * A port mapping on the GatewayDevice will allow all packets directed to port * externalPort of the external IP address of the GatewayDevice * using the specified protocol to be redirected to port * internalPort of internalClient. * * @see org.wetorrent.upnp.GatewayDevice * @see org.wetorrent.upnp.GatewayDevice#getExternalIPAddress() */ public class PortMappingEntry { /** * The internal port */ private int internalPort; /** * The external port of the mapping (the one on the GatewayDevice) */ private int externalPort; /** * The remote host this mapping is associated with */ private String remoteHost; /** * The internal host this mapping is associated with */ private String internalClient; /** * The protocol associated with this mapping (i.e. TCP or * UDP) */ private String protocol; /** * A flag that tells whether the mapping is enabled or not * ("1" for enabled, "0" for disabled) */ private String enabled; /** * A human readable description of the port mapping (used for display * purposes) */ private String portMappingDescription; /** * Creates a new PortMappingEntry */ public PortMappingEntry() { } /** * Gets the internal port for this mapping * @return the {@link #internalPort} */ public int getInternalPort() { return internalPort; } /** * Sets the {@link #internalPort} * @param internalPort the port to use */ public void setInternalPort(int internalPort) { this.internalPort = internalPort; } /** * Gets the external (remote) port for this mapping * @return the {@link #externalPort} */ public int getExternalPort() { return externalPort; } /** * Sets the {@link #externalPort} * @param externalPort the port to use */ public void setExternalPort(int externalPort) { this.externalPort = externalPort; } /** * Gets the remote host this mapping is associated with * @return the {@link #remoteHost} */ public String getRemoteHost() { return remoteHost; } /** * Sets the {@link #remoteHost} * @param remoteHost the host to set */ public void setRemoteHost(String remoteHost) { this.remoteHost = remoteHost; } /** * Gets the internal host this mapping is associated with * @return the {@link internalClient} */ public String getInternalClient() { return internalClient; } /** * Sets the {@link #internalClient} * @param internalClient the client to set */ public void setInternalClient(String internalClient) { this.internalClient = internalClient; } /** * Gets the protocol associated with this mapping * @return {@link #protocol} */ public String getProtocol() { return protocol; } /** * Sets the {@link #protocol} associated with this mapping * @param protocol one of TCP or UDP */ public void setProtocol(String protocol) { this.protocol = protocol; } /** * Gets the enabled flag ("1" if enabled, "0" otherwise) * @return {@link #enabled} */ public String getEnabled() { return enabled; } /** * Sets the {@link #enabled} flag * @param enabled "1" for enabled, "0" for disabled */ public void setEnabled(String enabled) { this.enabled = enabled; } /** * Gets the port mapping description * @return {@link #portMappingDescription} */ public String getPortMappingDescription() { return portMappingDescription; } /** * Sets the {@link #portMappingDescription} * @param portMappingDescription the description to set */ public void setPortMappingDescription(String portMappingDescription) { this.portMappingDescription = portMappingDescription; } } weupnp-weupnp-0.1.4/src/main/resources/000077500000000000000000000000001260505236500200775ustar00rootroot00000000000000weupnp-weupnp-0.1.4/src/main/resources/license.txt000066400000000000000000000625121260505236500222700ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it!