├── .gitignore
├── CONTRIBUTING.md
├── README.md
├── pom.xml
└── src
└── main
├── java
└── org
│ └── bitlet
│ └── weupnp
│ ├── GatewayDevice.java
│ ├── GatewayDeviceHandler.java
│ ├── GatewayDiscover.java
│ ├── Main.java
│ ├── NameValueHandler.java
│ └── PortMappingEntry.java
└── resources
└── license.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | target/*
2 | .DS_Store
3 | .classpath
4 | .project
5 | .settings
6 | *.iml
7 | *.ipr
8 | *.iws
9 | .idea/*
10 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Thank you for consdering constributing to weupnp.
2 |
3 | Before you submit your pull request, please considering the following:
4 |
5 | 1. be consistent with the style of the existing code (brackets, newlines, whitespace)
6 | 2. weupnp was designed to be minimal, so do not introduce dependencies to new libraries unless there is some strong reason to do so,
7 | 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.
8 |
9 | Other than that, we would be happy to get your help!
10 |
11 | Thank you
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # weupnp
2 |
3 | A lightweight Java library designed to implement the UPnP protocol and handle
4 | port mappings on Gateway Devices.
5 |
6 | You can find more information on the library at the project website:
7 | http://bitletorg.github.io/weupnp/
8 |
9 | If you use Maven, you can start using weupnp by including the following
10 | dependency:
11 |
12 | ```xml
13 |
14 | org.bitlet
15 | weupnp
16 | RELEASE
17 |
18 | ```
19 |
20 | We recommend starting development against the latest released version and pin
21 | it's version in your release `pom.xml` so that you can control which version you
22 | use. The list of released versions is available on the Maven
23 | [Central Repository][mvn].
24 |
25 | [mvn]: http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.bitlet%22%20AND%20a%3A%22weupnp%22
26 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | org.bitlet
4 | weupnp
5 | bundle
6 | 0.1.5-SNAPSHOT
7 | weupnp
8 | https://github.com/bitletorg/weupnp
9 |
10 | org.sonatype.oss
11 | oss-parent
12 | 7
13 |
14 |
15 |
16 |
17 | org.apache.maven.plugins
18 | maven-compiler-plugin
19 |
20 | 1.5
21 | 1.5
22 | ${project.build.sourceEncoding}
23 |
24 | 3.1
25 |
26 |
27 | org.apache.maven.plugins
28 | maven-resources-plugin
29 |
30 | ${project.build.sourceEncoding}
31 |
32 | 2.6
33 |
34 |
35 | org.apache.maven.plugins
36 | maven-jar-plugin
37 |
38 |
39 |
40 | org.bitlet.weupnp.Main
41 | org.bitlet.weupnp
42 | true
43 | true
44 |
45 |
46 |
47 | 2.4
48 |
49 |
50 | org.apache.felix
51 | maven-bundle-plugin
52 | 2.5.4
53 | true
54 |
55 |
56 |
57 |
58 |
59 | UTF-8
60 |
61 | Weupnp is a lightweight Java library, released under the LGPL licence, designed to implement the UPnP protocol to handle port mappings on Gateway Devices.
62 |
63 | scm:git:https://github.com/bitletorg/weupnp.git
64 | scm:git:https://github.com/bitletorg/weupnp.git
65 | https://github.com/bitletorg/weupnp
66 |
67 |
68 |
69 | GNU Lesser General Public License (LGPL)
70 |
71 |
72 |
73 |
74 | ale.bahgat
75 | Alessandro Bahgat Shehata
76 |
77 |
78 | daniele.castagna
79 | Daniele Castagna
80 |
81 |
82 | christophercyll
83 | Cristopher Cyll
84 |
85 |
86 |
87 |
88 | release-sign-artifacts
89 |
90 |
91 | performRelease
92 | true
93 |
94 |
95 |
96 |
97 |
98 | org.apache.maven.plugins
99 | maven-gpg-plugin
100 |
101 |
102 | sign-artifacts
103 | verify
104 |
105 | sign
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
--------------------------------------------------------------------------------
/src/main/java/org/bitlet/weupnp/GatewayDevice.java:
--------------------------------------------------------------------------------
1 | /*
2 | * weupnp - Trivial upnp java library
3 | *
4 | * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna
5 | *
6 | * This library is free software; you can redistribute it and/or
7 | * modify it under the terms of the GNU Lesser General Public
8 | * License as published by the Free Software Foundation; either
9 | * version 2.1 of the License, or (at your option) any later version.
10 | *
11 | * This library is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 | * Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public
17 | * License along with this library; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 | *
20 | * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com
21 | * Daniele Castagna - daniele dot castagna at gmail dot com
22 | *
23 | */
24 | package org.bitlet.weupnp;
25 |
26 | import java.io.IOException;
27 | import java.net.HttpURLConnection;
28 | import java.net.InetAddress;
29 | import java.net.URL;
30 | import java.net.URLConnection;
31 | import java.util.HashMap;
32 | import java.util.LinkedHashMap;
33 | import java.util.Map;
34 | import java.util.Set;
35 |
36 | import org.xml.sax.InputSource;
37 | import org.xml.sax.SAXException;
38 | import org.xml.sax.XMLReader;
39 | import org.xml.sax.helpers.XMLReaderFactory;
40 |
41 | /**
42 | * A GatewayDevice is a class that abstracts UPnP-compliant gateways
43 | *
44 | * It holds all the information that comes back as UPnP responses, and
45 | * provides methods to issue UPnP commands to a gateway.
46 | *
47 | * @author casta
48 | */
49 | public class GatewayDevice {
50 |
51 | /**
52 | * Receive timeout when requesting data from device
53 | */
54 | private static final int DEFAULT_HTTP_RECEIVE_TIMEOUT = 7000;
55 |
56 | private String st;
57 | private String location;
58 | private String serviceType;
59 | private String serviceTypeCIF;
60 | private String urlBase;
61 | private String controlURL;
62 | private String controlURLCIF;
63 | private String eventSubURL;
64 | private String eventSubURLCIF;
65 | private String sCPDURL;
66 | private String sCPDURLCIF;
67 | private String deviceType;
68 | private String deviceTypeCIF;
69 |
70 | // description data
71 |
72 | /**
73 | * The friendly (human readable) name associated with this device
74 | */
75 | private String friendlyName;
76 |
77 | /**
78 | * The device manufacturer name
79 | */
80 | private String manufacturer;
81 |
82 | /**
83 | * The model description as a string
84 | */
85 | private String modelDescription;
86 |
87 | /**
88 | * The URL that can be used to access the IGD interface
89 | */
90 | private String presentationURL;
91 |
92 | /**
93 | * The address used to reach this machine from the GatewayDevice
94 | */
95 | private InetAddress localAddress;
96 |
97 | /**
98 | * The model number (used by the manufacturer to identify the product)
99 | */
100 | private String modelNumber;
101 |
102 | /**
103 | * The model name
104 | */
105 | private String modelName;
106 |
107 | /**
108 | * Timeout in milliseconds for HTTP reads
109 | */
110 | private static int httpReadTimeout = DEFAULT_HTTP_RECEIVE_TIMEOUT;
111 |
112 | /**
113 | * Creates a new instance of GatewayDevice
114 | */
115 | public GatewayDevice() {
116 | }
117 |
118 | /**
119 | * Retrieves the properties and description of the GatewayDevice.
120 | *
121 | * Connects to the device's {@link #location} and parses the response
122 | * using a {@link GatewayDeviceHandler} to populate the fields of this
123 | * class
124 | *
125 | * @throws SAXException if an error occurs while parsing the request
126 | * @throws IOException on communication errors
127 | * @see org.bitlet.weupnp.GatewayDeviceHandler
128 | */
129 | public void loadDescription() throws SAXException, IOException {
130 |
131 | URLConnection urlConn = new URL(getLocation()).openConnection();
132 | urlConn.setReadTimeout(httpReadTimeout);
133 |
134 | XMLReader parser = XMLReaderFactory.createXMLReader();
135 | parser.setContentHandler(new GatewayDeviceHandler(this));
136 | parser.parse(new InputSource(urlConn.getInputStream()));
137 |
138 |
139 | /* fix urls */
140 | String ipConDescURL;
141 | if (urlBase != null && urlBase.trim().length() > 0) {
142 | ipConDescURL = urlBase;
143 | } else {
144 | ipConDescURL = location;
145 | }
146 |
147 | int lastSlashIndex = ipConDescURL.indexOf('/', 7);
148 | if (lastSlashIndex > 0) {
149 | ipConDescURL = ipConDescURL.substring(0, lastSlashIndex);
150 | }
151 |
152 |
153 | sCPDURL = copyOrCatUrl(ipConDescURL, sCPDURL);
154 | controlURL = copyOrCatUrl(ipConDescURL, controlURL);
155 | controlURLCIF = copyOrCatUrl(ipConDescURL, controlURLCIF);
156 | presentationURL = copyOrCatUrl(ipConDescURL, presentationURL);
157 | }
158 |
159 | /**
160 | * Issues UPnP commands to a GatewayDevice that can be reached at the
161 | * specified url
162 | *
163 | * The command is identified by a service and an action
164 | * and can receive arguments
165 | *
166 | * @param url the url to use to contact the device
167 | * @param service the service to invoke
168 | * @param action the specific action to perform
169 | * @param args the command arguments
170 | * @return the response to the performed command, as a name-value map.
171 | * In case errors occur, the returned map will be empty.
172 | * @throws IOException on communication errors
173 | * @throws SAXException if errors occur while parsing the response
174 | */
175 | public static Map simpleUPnPcommand(String url,
176 | String service, String action, Map args)
177 | throws IOException, SAXException {
178 | String soapAction = "\"" + service + "#" + action + "\"";
179 | StringBuilder soapBody = new StringBuilder();
180 |
181 | soapBody.append("\r\n" +
182 | "" +
185 | "" +
186 | "");
187 |
188 | if (args != null && args.size() > 0) {
189 |
190 | Set> entrySet = args.entrySet();
191 |
192 | for (Map.Entry entry : entrySet) {
193 | soapBody.append("<" + entry.getKey() + ">" + entry.getValue() +
194 | "" + entry.getKey() + ">");
195 | }
196 |
197 | }
198 |
199 | soapBody.append("");
200 | soapBody.append("");
201 |
202 | URL postUrl = new URL(url);
203 | HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
204 |
205 | conn.setRequestMethod("POST");
206 | conn.setConnectTimeout(httpReadTimeout);
207 | conn.setReadTimeout(httpReadTimeout);
208 | conn.setDoOutput(true);
209 | conn.setRequestProperty("Content-Type", "text/xml");
210 | conn.setRequestProperty("SOAPAction", soapAction);
211 | conn.setRequestProperty("Connection", "Close");
212 |
213 | byte[] soapBodyBytes = soapBody.toString().getBytes();
214 |
215 | conn.setRequestProperty("Content-Length",
216 | String.valueOf(soapBodyBytes.length));
217 |
218 | conn.getOutputStream().write(soapBodyBytes);
219 |
220 | Map nameValue = new HashMap();
221 | XMLReader parser = XMLReaderFactory.createXMLReader();
222 | parser.setContentHandler(new NameValueHandler(nameValue));
223 | if (conn.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
224 | try {
225 | // attempt to parse the error message
226 | parser.parse(new InputSource(conn.getErrorStream()));
227 | } catch (SAXException e) {
228 | // ignore the exception
229 | // FIXME We probably need to find a better way to return
230 | // significant information when we reach this point
231 | }
232 | conn.disconnect();
233 | return nameValue;
234 | } else {
235 | parser.parse(new InputSource(conn.getInputStream()));
236 | conn.disconnect();
237 | return nameValue;
238 | }
239 | }
240 |
241 | /**
242 | * Retrieves the connection status of this device
243 | *
244 | * @return true if connected, false otherwise
245 | * @throws IOException
246 | * @throws SAXException
247 | * @see #simpleUPnPcommand(java.lang.String, java.lang.String,
248 | * java.lang.String, java.util.Map)
249 | */
250 | public boolean isConnected() throws IOException, SAXException {
251 | Map nameValue = simpleUPnPcommand(controlURL,
252 | serviceType, "GetStatusInfo", null);
253 |
254 | String connectionStatus = nameValue.get("NewConnectionStatus");
255 | if (connectionStatus != null
256 | && connectionStatus.equalsIgnoreCase("Connected")) {
257 | return true;
258 | }
259 |
260 | return false;
261 | }
262 |
263 | /**
264 | * Retrieves the external IP address associated with this device
265 | *
266 | * The external address is the address that can be used to connect to the
267 | * GatewayDevice from the external network
268 | *
269 | * @return the external IP
270 | * @throws IOException
271 | * @throws SAXException
272 | * @see #simpleUPnPcommand(java.lang.String, java.lang.String,
273 | * java.lang.String, java.util.Map)
274 | */
275 | public String getExternalIPAddress() throws IOException, SAXException {
276 | Map nameValue = simpleUPnPcommand(controlURL,
277 | serviceType, "GetExternalIPAddress", null);
278 |
279 | return nameValue.get("NewExternalIPAddress");
280 | }
281 |
282 | /**
283 | * Adds a new port mapping to the GatewayDevices using the supplied
284 | * parameters.
285 | *
286 | * @param externalPort the external associated with the new mapping
287 | * @param internalPort the internal port associated with the new mapping
288 | * @param internalClient the internal client associated with the new mapping
289 | * @param protocol the protocol associated with the new mapping
290 | * @param description the mapping description
291 | * @return true if the mapping was successfully added, false otherwise
292 | * @throws IOException
293 | * @throws SAXException
294 | * @see #simpleUPnPcommand(java.lang.String, java.lang.String,
295 | * java.lang.String, java.util.Map)
296 | * @see PortMappingEntry
297 | */
298 | public boolean addPortMapping(int externalPort, int internalPort,
299 | String internalClient, String protocol, String description)
300 | throws IOException, SAXException {
301 | Map args = new LinkedHashMap();
302 | args.put("NewRemoteHost", ""); // wildcard, any remote host matches
303 | args.put("NewExternalPort", Integer.toString(externalPort));
304 | args.put("NewProtocol", protocol);
305 | args.put("NewInternalPort", Integer.toString(internalPort));
306 | args.put("NewInternalClient", internalClient);
307 | args.put("NewEnabled", Integer.toString(1));
308 | args.put("NewPortMappingDescription", description);
309 | args.put("NewLeaseDuration", Integer.toString(0));
310 |
311 | Map nameValue = simpleUPnPcommand(controlURL,
312 | serviceType, "AddPortMapping", args);
313 |
314 | return nameValue.get("errorCode") == null;
315 | }
316 |
317 | /**
318 | * Queries the GatewayDevice to retrieve a specific port mapping entry,
319 | * corresponding to specified criteria, if present.
320 | *
321 | * Retrieves the PortMappingEntry associated with
322 | * externalPort and protocol, if present.
323 | *
324 | * @param externalPort the external port
325 | * @param protocol the protocol (TCP or UDP)
326 | * @param portMappingEntry the entry containing the details, in any is
327 | * present, null otherwise. (used as return value)
328 | * @return true if a valid mapping is found
329 | * @throws IOException
330 | * @throws SAXException
331 | * @todo consider refactoring this method to make it consistent with
332 | * Java practices (return the port mapping)
333 | * @see #simpleUPnPcommand(java.lang.String, java.lang.String,
334 | * java.lang.String, java.util.Map)
335 | * @see PortMappingEntry
336 | */
337 | public boolean getSpecificPortMappingEntry(int externalPort,
338 | String protocol, final PortMappingEntry portMappingEntry)
339 | throws IOException, SAXException {
340 |
341 | portMappingEntry.setExternalPort(externalPort);
342 | portMappingEntry.setProtocol(protocol);
343 |
344 | Map args = new LinkedHashMap();
345 | args.put("NewRemoteHost", ""); // wildcard, any remote host matches
346 | args.put("NewExternalPort", Integer.toString(externalPort));
347 | args.put("NewProtocol", protocol);
348 |
349 | Map nameValue = simpleUPnPcommand(controlURL,
350 | serviceType, "GetSpecificPortMappingEntry", args);
351 |
352 | if (nameValue.isEmpty() || nameValue.containsKey("errorCode"))
353 | return false;
354 |
355 | if (!nameValue.containsKey("NewInternalClient") ||
356 | !nameValue.containsKey("NewInternalPort"))
357 | return false;
358 |
359 | portMappingEntry.setProtocol(protocol);
360 | portMappingEntry.setEnabled(nameValue.get("NewEnabled"));
361 | portMappingEntry.setInternalClient(nameValue.get("NewInternalClient"));
362 | portMappingEntry.setExternalPort(externalPort);
363 | portMappingEntry.setPortMappingDescription(nameValue.get("NewPortMappingDescription"));
364 | portMappingEntry.setRemoteHost(nameValue.get("NewRemoteHost"));
365 |
366 | try {
367 | portMappingEntry.setInternalPort(Integer.parseInt(nameValue.get("NewInternalPort")));
368 | } catch (NumberFormatException nfe) {
369 | // skip bad port
370 | }
371 |
372 |
373 | return true;
374 | }
375 |
376 | /**
377 | * Returns a specific port mapping entry, depending on a the supplied index.
378 | *
379 | * @param index the index of the desired port mapping
380 | * @param portMappingEntry the entry containing the details, in any is
381 | * present, null otherwise. (used as return value)
382 | * @return true if a valid mapping is found
383 | * @throws IOException
384 | * @throws SAXException
385 | * @todo consider refactoring this method to make it consistent with
386 | * Java practices (return the port mapping)
387 | * @see #simpleUPnPcommand(java.lang.String, java.lang.String,
388 | * java.lang.String, java.util.Map)
389 | * @see PortMappingEntry
390 | */
391 | public boolean getGenericPortMappingEntry(int index,
392 | final PortMappingEntry portMappingEntry)
393 | throws IOException, SAXException {
394 | Map args = new LinkedHashMap();
395 | args.put("NewPortMappingIndex", Integer.toString(index));
396 |
397 | Map nameValue = simpleUPnPcommand(controlURL,
398 | serviceType, "GetGenericPortMappingEntry", args);
399 |
400 | if (nameValue.isEmpty() || nameValue.containsKey("errorCode"))
401 | return false;
402 |
403 | portMappingEntry.setRemoteHost(nameValue.get("NewRemoteHost"));
404 | portMappingEntry.setInternalClient(nameValue.get("NewInternalClient"));
405 | portMappingEntry.setProtocol(nameValue.get("NewProtocol"));
406 | portMappingEntry.setEnabled(nameValue.get("NewEnabled"));
407 | portMappingEntry.setPortMappingDescription(
408 | nameValue.get("NewPortMappingDescription"));
409 |
410 | try {
411 | portMappingEntry.setInternalPort(
412 | Integer.parseInt(nameValue.get("NewInternalPort")));
413 | } catch (Exception e) {
414 | }
415 |
416 | try {
417 | portMappingEntry.setExternalPort(
418 | Integer.parseInt(nameValue.get("NewExternalPort")));
419 | } catch (Exception e) {
420 | }
421 |
422 | return true;
423 | }
424 |
425 | /**
426 | * Retrieves the number of port mappings that are registered on the
427 | * GatewayDevice.
428 | *
429 | * @return the number of port mappings
430 | * @throws IOException
431 | * @throws SAXException
432 | */
433 | public Integer getPortMappingNumberOfEntries()
434 | throws IOException, SAXException {
435 | Map nameValue = simpleUPnPcommand(controlURL,
436 | serviceType, "GetPortMappingNumberOfEntries", null);
437 |
438 | Integer portMappingNumber = null;
439 |
440 | try {
441 | portMappingNumber = Integer.valueOf(
442 | nameValue.get("NewPortMappingNumberOfEntries"));
443 | } catch (Exception e) {
444 | }
445 |
446 | return portMappingNumber;
447 | }
448 |
449 | /**
450 | * Deletes the port mapping associated to externalPort and
451 | * protocol
452 | *
453 | * @param externalPort the external port
454 | * @param protocol the protocol
455 | * @return true if removal was successful
456 | * @throws IOException
457 | * @throws SAXException
458 | */
459 | public boolean deletePortMapping(int externalPort, String protocol)
460 | throws IOException, SAXException {
461 | Map args = new LinkedHashMap();
462 | args.put("NewRemoteHost", "");
463 | args.put("NewExternalPort", Integer.toString(externalPort));
464 | args.put("NewProtocol", protocol);
465 | Map nameValue = simpleUPnPcommand(controlURL,
466 | serviceType, "DeletePortMapping", args);
467 |
468 | return true;
469 | }
470 |
471 | // getters and setters
472 |
473 | /**
474 | * Gets the local address to connect the gateway through
475 | *
476 | * @return the {@link #localAddress}
477 | */
478 | public InetAddress getLocalAddress() {
479 | return localAddress;
480 | }
481 |
482 | /**
483 | * Sets the {@link #localAddress}
484 | *
485 | * @param localAddress the address to set
486 | */
487 | public void setLocalAddress(InetAddress localAddress) {
488 | this.localAddress = localAddress;
489 | }
490 |
491 | public String getSt() {
492 | return st;
493 | }
494 |
495 | public void setSt(String st) {
496 | this.st = st;
497 | }
498 |
499 | public String getLocation() {
500 | return location;
501 | }
502 |
503 | public void setLocation(String location) {
504 | this.location = location;
505 | }
506 |
507 | public String getServiceType() {
508 | return serviceType;
509 | }
510 |
511 | public void setServiceType(String serviceType) {
512 | this.serviceType = serviceType;
513 | }
514 |
515 | public String getServiceTypeCIF() {
516 | return serviceTypeCIF;
517 | }
518 |
519 | public void setServiceTypeCIF(String serviceTypeCIF) {
520 | this.serviceTypeCIF = serviceTypeCIF;
521 | }
522 |
523 | public String getControlURL() {
524 | return controlURL;
525 | }
526 |
527 | public void setControlURL(String controlURL) {
528 | this.controlURL = controlURL;
529 | }
530 |
531 | public String getControlURLCIF() {
532 | return controlURLCIF;
533 | }
534 |
535 | public void setControlURLCIF(String controlURLCIF) {
536 | this.controlURLCIF = controlURLCIF;
537 | }
538 |
539 | public String getEventSubURL() {
540 | return eventSubURL;
541 | }
542 |
543 | public void setEventSubURL(String eventSubURL) {
544 | this.eventSubURL = eventSubURL;
545 | }
546 |
547 | public String getEventSubURLCIF() {
548 | return eventSubURLCIF;
549 | }
550 |
551 | public void setEventSubURLCIF(String eventSubURLCIF) {
552 | this.eventSubURLCIF = eventSubURLCIF;
553 | }
554 |
555 | public String getSCPDURL() {
556 | return sCPDURL;
557 | }
558 |
559 | public void setSCPDURL(String sCPDURL) {
560 | this.sCPDURL = sCPDURL;
561 | }
562 |
563 | public String getSCPDURLCIF() {
564 | return sCPDURLCIF;
565 | }
566 |
567 | public void setSCPDURLCIF(String sCPDURLCIF) {
568 | this.sCPDURLCIF = sCPDURLCIF;
569 | }
570 |
571 | public String getDeviceType() {
572 | return deviceType;
573 | }
574 |
575 | public void setDeviceType(String deviceType) {
576 | this.deviceType = deviceType;
577 | }
578 |
579 | public String getDeviceTypeCIF() {
580 | return deviceTypeCIF;
581 | }
582 |
583 | public void setDeviceTypeCIF(String deviceTypeCIF) {
584 | this.deviceTypeCIF = deviceTypeCIF;
585 | }
586 |
587 | public String getURLBase() {
588 | return urlBase;
589 | }
590 |
591 | public void setURLBase(String uRLBase) {
592 | this.urlBase = uRLBase;
593 | }
594 |
595 | public String getFriendlyName() {
596 | return friendlyName;
597 | }
598 |
599 | public void setFriendlyName(String friendlyName) {
600 | this.friendlyName = friendlyName;
601 | }
602 |
603 | public String getManufacturer() {
604 | return manufacturer;
605 | }
606 |
607 | public void setManufacturer(String manufacturer) {
608 | this.manufacturer = manufacturer;
609 | }
610 |
611 | public String getModelDescription() {
612 | return modelDescription;
613 | }
614 |
615 | public void setModelDescription(String modelDescription) {
616 | this.modelDescription = modelDescription;
617 | }
618 |
619 | public String getPresentationURL() {
620 | return presentationURL;
621 | }
622 |
623 | public void setPresentationURL(String presentationURL) {
624 | this.presentationURL = presentationURL;
625 | }
626 |
627 | public String getModelName() {
628 | return modelName;
629 | }
630 |
631 | public void setModelName(String modelName) {
632 | this.modelName = modelName;
633 | }
634 |
635 | public String getModelNumber() {
636 | return modelNumber;
637 | }
638 |
639 | public void setModelNumber(String modelNumber) {
640 | this.modelNumber = modelNumber;
641 | }
642 |
643 | /**
644 | * Gets the timeout for actions on the device.
645 | * @return timeout in milliseconds
646 | */
647 | public static int getHttpReadTimeout() {
648 | return httpReadTimeout;
649 | }
650 |
651 | /**
652 | * Sets the timeout for actions on the device.
653 | * @param milliseconds the new timeout in milliseconds
654 | */
655 | public static void setHttpReadTimeout(int milliseconds) {
656 | httpReadTimeout = milliseconds;
657 | }
658 |
659 | // private methods
660 | private String copyOrCatUrl(String dst, String src) {
661 | if (src != null) {
662 | if (src.startsWith("http://")) {
663 | dst = src;
664 | } else {
665 | if (!src.startsWith("/")) {
666 | dst += "/";
667 | }
668 | dst += src;
669 | }
670 | }
671 | return dst;
672 | }
673 | }
674 |
--------------------------------------------------------------------------------
/src/main/java/org/bitlet/weupnp/GatewayDeviceHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * weupnp - Trivial upnp java library
3 | *
4 | * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna
5 | *
6 | * This library is free software; you can redistribute it and/or
7 | * modify it under the terms of the GNU Lesser General Public
8 | * License as published by the Free Software Foundation; either
9 | * version 2.1 of the License, or (at your option) any later version.
10 | *
11 | * This library is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 | * Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public
17 | * License along with this library; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 | *
20 | * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com
21 | * Daniele Castagna - daniele dot castagna at gmail dot com
22 | *
23 | */
24 |
25 | package org.bitlet.weupnp;
26 |
27 | import org.xml.sax.Attributes;
28 | import org.xml.sax.SAXException;
29 | import org.xml.sax.helpers.DefaultHandler;
30 |
31 | /**
32 | * A SAX handler used to parse XML data representing a GatewayDevice
33 | *
34 | * @see org.xml.sax.helpers.DefaultHandler
35 | */
36 | public class GatewayDeviceHandler extends DefaultHandler {
37 |
38 | /**
39 | * The device that should be populated with data coming from the stream
40 | * being parsed
41 | */
42 | private GatewayDevice device;
43 |
44 | /**
45 | * Creates a new instance of GatewayDeviceHandler that will populate the
46 | * fields of the supplied device
47 | *
48 | * @param device the device to configure
49 | */
50 | public GatewayDeviceHandler(final GatewayDevice device) {
51 | this.device = device;
52 | }
53 |
54 | /** state variables */
55 | private String currentElement;
56 | private int level = 0;
57 | private short state = 0;
58 |
59 | /**
60 | * Receive notification of the start of an element.
61 | *
62 | * Caches the element as {@link #currentElement}, and keeps track of some
63 | * basic state information.
64 | *
65 | * @param uri The Namespace URI, or the empty string if the
66 | * element has no Namespace URI or if Namespace
67 | * processing is not being performed.
68 | * @param localName The local name (without prefix), or the
69 | * empty string if Namespace processing is not being
70 | * performed.
71 | * @param qName The qualified name (with prefix), or the
72 | * empty string if qualified names are not available.
73 | * @param attributes The attributes attached to the element. If
74 | * there are no attributes, it shall be an empty
75 | * Attributes object.
76 | * @exception org.xml.sax.SAXException Any SAX exception, possibly
77 | * wrapping another exception.
78 | * @see org.xml.sax.ContentHandler#startElement
79 | */
80 | @Override
81 | public void startElement(String uri, String localName, String qName,
82 | Attributes attributes) throws SAXException {
83 | currentElement = localName;
84 | level++;
85 | if (state < 1 && "serviceList".compareTo(currentElement) == 0) {
86 | state = 1;
87 | }
88 | }
89 |
90 | /**
91 | * Receive notification of the end of an element.
92 | *
93 | * Used to update state information.
94 | *
95 | *
By default, do nothing. Application writers may override this
96 | * method in a subclass to take specific actions at the end of
97 | * each element (such as finalising a tree node or writing
98 | * output to a file).
99 | *
100 | * @param uri The Namespace URI, or the empty string if the
101 | * element has no Namespace URI or if Namespace
102 | * processing is not being performed.
103 | * @param localName The local name (without prefix), or the
104 | * empty string if Namespace processing is not being
105 | * performed.
106 | * @param qName The qualified name (with prefix), or the
107 | * empty string if qualified names are not available.
108 | * @exception org.xml.sax.SAXException Any SAX exception, possibly
109 | * wrapping another exception.
110 | * @see org.xml.sax.ContentHandler#endElement
111 | */
112 | @Override
113 | public void endElement(String uri, String localName, String qName) throws SAXException {
114 | currentElement = "";
115 | level--;
116 | if (localName.compareTo("service")==0){
117 | if (device.getServiceTypeCIF() != null &&
118 | device.getServiceTypeCIF().compareTo("urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1") == 0)
119 | state = 2;
120 | if (device.getServiceType() != null &&
121 | (
122 | device.getServiceType().contains("urn:schemas-upnp-org:service:WANIPConnection:") ||
123 | device.getServiceType().contains("urn:schemas-upnp-org:service:WANPPPConnection:")
124 | ))
125 | state = 3;
126 | }
127 | }
128 |
129 | /**
130 | * Receive notification of character data inside an element.
131 | *
132 | * It is used to read the values of the relevant fields of the device being
133 | * configured.
134 | *
135 | * @param ch The characters.
136 | * @param start The start position in the character array.
137 | * @param length The number of characters to use from the
138 | * character array.
139 | * @exception org.xml.sax.SAXException Any SAX exception, possibly
140 | * wrapping another exception.
141 | * @see org.xml.sax.ContentHandler#characters
142 | */
143 | @Override
144 | public void characters(char[] ch, int start, int length) throws SAXException {
145 | if (currentElement.compareTo("URLBase") == 0)
146 | device.setURLBase(new String(ch,start,length));
147 | else if (state<=1) {
148 | if (state == 0) {
149 | if ("friendlyName".compareTo(currentElement) == 0)
150 | device.setFriendlyName(new String(ch,start,length));
151 | else if ("manufacturer".compareTo(currentElement) == 0)
152 | device.setManufacturer(new String(ch,start,length));
153 | else if ("modelDescription".compareTo(currentElement) == 0)
154 | device.setModelDescription(new String(ch,start,length));
155 | else if ("presentationURL".compareTo(currentElement) == 0)
156 | device.setPresentationURL(new String(ch,start,length));
157 | else if ("modelNumber".compareTo(currentElement) == 0)
158 | device.setModelNumber(new String(ch,start,length));
159 | else if ("modelName".compareTo(currentElement) == 0)
160 | device.setModelName(new String(ch,start,length));
161 | }
162 | if( currentElement.compareTo("serviceType") == 0 )
163 | device.setServiceTypeCIF(new String(ch,start,length));
164 | else if( currentElement.compareTo( "controlURL") == 0)
165 | device.setControlURLCIF(new String(ch,start,length));
166 | else if( currentElement.compareTo( "eventSubURL") == 0 )
167 | device.setEventSubURLCIF(new String(ch,start,length));
168 | else if( currentElement.compareTo( "SCPDURL") == 0 )
169 | device.setSCPDURLCIF(new String(ch,start,length));
170 | else if( currentElement.compareTo( "deviceType") == 0 )
171 | device.setDeviceTypeCIF(new String(ch,start,length));
172 | }else if (state==2){
173 | if( currentElement.compareTo("serviceType") == 0 )
174 | device.setServiceType(new String(ch,start,length));
175 | else if( currentElement.compareTo( "controlURL") == 0)
176 | device.setControlURL(new String(ch,start,length));
177 | else if( currentElement.compareTo( "eventSubURL") == 0 )
178 | device.setEventSubURL(new String(ch,start,length));
179 | else if( currentElement.compareTo( "SCPDURL") == 0 )
180 | device.setSCPDURL(new String(ch,start,length));
181 | else if( currentElement.compareTo( "deviceType") == 0 )
182 | device.setDeviceType(new String(ch,start,length));
183 |
184 | }
185 | }
186 |
187 | }
188 |
--------------------------------------------------------------------------------
/src/main/java/org/bitlet/weupnp/GatewayDiscover.java:
--------------------------------------------------------------------------------
1 | /*
2 | * weupnp - Trivial upnp java library
3 | *
4 | * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna
5 | *
6 | * This library is free software; you can redistribute it and/or
7 | * modify it under the terms of the GNU Lesser General Public
8 | * License as published by the Free Software Foundation; either
9 | * version 2.1 of the License, or (at your option) any later version.
10 | *
11 | * This library is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 | * Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public
17 | * License along with this library; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 | *
20 | * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com
21 | * Daniele Castagna - daniele dot castagna at gmail dot com
22 | *
23 | */
24 | package org.bitlet.weupnp;
25 |
26 | import java.io.IOException;
27 | import java.net.DatagramPacket;
28 | import java.net.DatagramSocket;
29 | import java.net.Inet4Address;
30 | import java.net.Inet6Address;
31 | import java.net.InetAddress;
32 | import java.net.InetSocketAddress;
33 | import java.net.NetworkInterface;
34 | import java.net.SocketException;
35 | import java.net.SocketTimeoutException;
36 | import java.net.UnknownHostException;
37 | import java.util.ArrayList;
38 | import java.util.Arrays;
39 | import java.util.Collection;
40 | import java.util.Enumeration;
41 | import java.util.HashMap;
42 | import java.util.List;
43 | import java.util.Map;
44 | import java.util.StringTokenizer;
45 |
46 | import javax.xml.parsers.ParserConfigurationException;
47 |
48 | import org.xml.sax.SAXException;
49 |
50 | /**
51 | * Handles the discovery of GatewayDevices, via the {@link org.bitlet.weupnp.GatewayDiscover#discover()} method.
52 | */
53 | public class GatewayDiscover {
54 |
55 | /**
56 | * The SSDP port
57 | */
58 | public static final int PORT = 1900;
59 |
60 | /**
61 | * The broadcast address to use when trying to contact UPnP devices
62 | */
63 | public static final String IP = "239.255.255.250";
64 |
65 | /**
66 | * The default timeout for the initial broadcast request
67 | */
68 | private static final int DEFAULT_TIMEOUT = 3000;
69 |
70 | /**
71 | * The timeout for the initial broadcast request
72 | */
73 | private int timeout = DEFAULT_TIMEOUT;
74 |
75 | /**
76 | * The gateway types the discover have to search.
77 | */
78 | private String[] searchTypes;
79 |
80 | /**
81 | * The default gateway types to use in search
82 | */
83 | private static final String[] DEFAULT_SEARCH_TYPES =
84 | {
85 | "urn:schemas-upnp-org:device:InternetGatewayDevice:1",
86 | "urn:schemas-upnp-org:service:WANIPConnection:1",
87 | "urn:schemas-upnp-org:service:WANPPPConnection:1"
88 | };
89 |
90 |
91 | /**
92 | * A map of the GatewayDevices discovered so far.
93 | * The assumption is that a machine is connected to up to a Gateway Device
94 | * per InetAddress
95 | */
96 | private final Map devices = new HashMap();
97 |
98 | /*
99 | * Thread class for sending a search datagram and process the response.
100 | */
101 | private class SendDiscoveryThread extends Thread {
102 | InetAddress ip;
103 | String searchMessage;
104 |
105 | SendDiscoveryThread(InetAddress localIP, String searchMessage) {
106 | this.ip = localIP;
107 | this.searchMessage = searchMessage;
108 | }
109 |
110 | @Override
111 | public void run() {
112 |
113 | DatagramSocket ssdp = null;
114 |
115 | try {
116 | // Create socket bound to specified local address
117 | ssdp = new DatagramSocket(new InetSocketAddress(ip, 0));
118 |
119 | byte[] searchMessageBytes = searchMessage.getBytes();
120 | DatagramPacket ssdpDiscoverPacket = new DatagramPacket(searchMessageBytes, searchMessageBytes.length);
121 | ssdpDiscoverPacket.setAddress(InetAddress.getByName(IP));
122 | ssdpDiscoverPacket.setPort(PORT);
123 |
124 | ssdp.send(ssdpDiscoverPacket);
125 | ssdp.setSoTimeout(GatewayDiscover.this.timeout);
126 |
127 | boolean waitingPacket = true;
128 | while (waitingPacket) {
129 | DatagramPacket receivePacket = new DatagramPacket(new byte[1536], 1536);
130 | try {
131 | ssdp.receive(receivePacket);
132 | byte[] receivedData = new byte[receivePacket.getLength()];
133 | System.arraycopy(receivePacket.getData(), 0, receivedData, 0, receivePacket.getLength());
134 |
135 | // Create GatewayDevice from response
136 | GatewayDevice gatewayDevice = parseMSearchReply(receivedData);
137 |
138 | gatewayDevice.setLocalAddress(ip);
139 | gatewayDevice.loadDescription();
140 |
141 | // verify that the search type is among the requested ones
142 | if (Arrays.asList(searchTypes).contains(gatewayDevice.getSt())) {
143 | synchronized (devices) {
144 | devices.put(ip, gatewayDevice);
145 | break; // device added for this ip, nothing further to do
146 | }
147 | }
148 | } catch (SocketTimeoutException ste) {
149 | waitingPacket = false;
150 | }
151 | }
152 |
153 | } catch (Exception e) {
154 | // e.printStackTrace();
155 | } finally {
156 | if (null != ssdp) {
157 | ssdp.close();
158 | }
159 | }
160 | }
161 | }
162 |
163 | /**
164 | * Constructor.
165 | *
166 | * By default it's looking for 3 types of gateways.
167 | *
168 | */
169 | public GatewayDiscover() {
170 | this(DEFAULT_SEARCH_TYPES);
171 | }
172 |
173 | /**
174 | * Constructor of the gateway discover service.
175 | *
176 | * @param st The search type you are looking for
177 | */
178 | public GatewayDiscover(String st) {
179 | this(new String[]{st});
180 | }
181 |
182 | /**
183 | * Constructor.
184 | *
185 | * @param types The search types the discover have to look for
186 | */
187 | public GatewayDiscover(String[] types) {
188 | this.searchTypes = types;
189 | }
190 |
191 | /**
192 | * Gets the timeout for socket connections of the initial broadcast request.
193 | * @return timeout in milliseconds
194 | */
195 | public int getTimeout() {
196 | return this.timeout;
197 | }
198 |
199 | /**
200 | * Sets the timeout for socket connections of the initial broadcast request.
201 | * @param milliseconds the new timeout in milliseconds
202 | */
203 | public void setTimeout(int milliseconds) {
204 | this.timeout = milliseconds;
205 | }
206 |
207 | /**
208 | * Discovers Gateway Devices on the network(s) the executing machine is
209 | * connected to.
210 | *
211 | * The host may be connected to different networks via different network
212 | * interfaces.
213 | * Assumes that each network interface has a different InetAddress and
214 | * returns a map associating every GatewayDevice (responding to a broadcast
215 | * discovery message) with the InetAddress it is connected to.
216 | *
217 | * @return a map containing a GatewayDevice per InetAddress
218 | * @throws SocketException
219 | * @throws UnknownHostException
220 | * @throws IOException
221 | * @throws SAXException
222 | * @throws ParserConfigurationException
223 | */
224 | public Map discover() throws SocketException, UnknownHostException, IOException, SAXException, ParserConfigurationException {
225 |
226 | Collection ips = getLocalInetAddresses(true, false, false);
227 |
228 | for (int i = 0; i < searchTypes.length; i++) {
229 |
230 | String searchMessage = "M-SEARCH * HTTP/1.1\r\n" +
231 | "HOST: " + IP + ":" + PORT + "\r\n" +
232 | "ST: " + searchTypes[i] + "\r\n" +
233 | "MAN: \"ssdp:discover\"\r\n" +
234 | "MX: 2\r\n" + // seconds to delay response
235 | "\r\n";
236 |
237 | // perform search requests for multiple network adapters concurrently
238 | Collection threads = new ArrayList();
239 | for (InetAddress ip : ips) {
240 | SendDiscoveryThread thread = new SendDiscoveryThread(ip, searchMessage);
241 | threads.add(thread);
242 | thread.start();
243 | }
244 |
245 | // wait for all search threads to finish
246 | for (SendDiscoveryThread thread : threads)
247 | try {
248 | thread.join();
249 | } catch (InterruptedException e) {
250 | // continue with next thread
251 | }
252 |
253 | // If a search type found devices, don't try with different search type
254 | if (!devices.isEmpty())
255 | break;
256 |
257 | } // loop SEARCHTYPES
258 |
259 | return devices;
260 | }
261 |
262 | /**
263 | * Parses the reply from UPnP devices
264 | *
265 | * @param reply the raw bytes received as a reply
266 | * @return the representation of a GatewayDevice
267 | */
268 | private GatewayDevice parseMSearchReply(byte[] reply) {
269 |
270 | GatewayDevice device = new GatewayDevice();
271 |
272 | String replyString = new String(reply);
273 | StringTokenizer st = new StringTokenizer(replyString, "\n");
274 |
275 | while (st.hasMoreTokens()) {
276 | String line = st.nextToken().trim();
277 |
278 | if (line.isEmpty())
279 | continue;
280 |
281 | if (line.startsWith("HTTP/1.") || line.startsWith("NOTIFY *"))
282 | continue;
283 |
284 | String key = line.substring(0, line.indexOf(':'));
285 | String value = line.length() > key.length() + 1 ? line.substring(key.length() + 1) : null;
286 |
287 | key = key.trim();
288 | if (value != null) {
289 | value = value.trim();
290 | }
291 |
292 | if (key.compareToIgnoreCase("location") == 0) {
293 | device.setLocation(value);
294 |
295 | } else if (key.compareToIgnoreCase("st") == 0) { // Search Target
296 | device.setSt(value);
297 | }
298 | }
299 |
300 | return device;
301 | }
302 |
303 | /**
304 | * Gets the first connected gateway
305 | *
306 | * @return the first GatewayDevice which is connected to the network, or
307 | * null if none present
308 | */
309 | public GatewayDevice getValidGateway() {
310 |
311 | for (GatewayDevice device : devices.values()) {
312 | try {
313 | if (device.isConnected()) {
314 | return device;
315 | }
316 | } catch (Exception e) {
317 | }
318 | }
319 |
320 | return null;
321 | }
322 |
323 | /**
324 | * Returns list of all discovered gateways. Is empty when no gateway is found.
325 | */
326 | public Map getAllGateways() {
327 | return devices;
328 | }
329 |
330 | /**
331 | * Retrieves all local IP addresses from all present network devices.
332 | *
333 | * @param getIPv4 boolean flag if IPv4 addresses shall be retrieved
334 | * @param getIPv6 boolean flag if IPv6 addresses shall be retrieved
335 | * @param sortIPv4BeforeIPv6 if true, IPv4 addresses will be sorted before IPv6 addresses
336 | * @return Collection if {@link InetAddress}es
337 | */
338 | private List getLocalInetAddresses(boolean getIPv4, boolean getIPv6, boolean sortIPv4BeforeIPv6) {
339 | List arrayIPAddress = new ArrayList();
340 | int lastIPv4Index = 0;
341 |
342 | // Get all network interfaces
343 | Enumeration networkInterfaces;
344 | try {
345 | networkInterfaces = NetworkInterface.getNetworkInterfaces();
346 | } catch (SocketException e) {
347 | return arrayIPAddress;
348 | }
349 |
350 | if (networkInterfaces == null)
351 | return arrayIPAddress;
352 |
353 | // For every suitable network interface, get all IP addresses
354 | while (networkInterfaces.hasMoreElements()) {
355 | NetworkInterface card = networkInterfaces.nextElement();
356 |
357 | try {
358 | // skip devices, not suitable to search gateways for
359 | if (card.isLoopback() || card.isPointToPoint() ||
360 | card.isVirtual() || !card.isUp())
361 | continue;
362 | } catch (SocketException e) {
363 | continue;
364 | }
365 |
366 | Enumeration addresses = card.getInetAddresses();
367 |
368 | if (addresses == null)
369 | continue;
370 |
371 | while (addresses.hasMoreElements()) {
372 | InetAddress inetAddress = addresses.nextElement();
373 | int index = arrayIPAddress.size();
374 |
375 | if (!getIPv4 || !getIPv6) {
376 | if (getIPv4 && !Inet4Address.class.isInstance(inetAddress))
377 | continue;
378 |
379 | if (getIPv6 && !Inet6Address.class.isInstance(inetAddress))
380 | continue;
381 | } else if (sortIPv4BeforeIPv6 && Inet4Address.class.isInstance(inetAddress)) {
382 | index = lastIPv4Index++;
383 | }
384 |
385 | arrayIPAddress.add(index, inetAddress);
386 | }
387 | }
388 |
389 | return arrayIPAddress;
390 | }
391 |
392 | }
393 |
--------------------------------------------------------------------------------
/src/main/java/org/bitlet/weupnp/Main.java:
--------------------------------------------------------------------------------
1 | /*
2 | * weupnp - Trivial upnp java library
3 | *
4 | * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna
5 | *
6 | * This library is free software; you can redistribute it and/or
7 | * modify it under the terms of the GNU Lesser General Public
8 | * License as published by the Free Software Foundation; either
9 | * version 2.1 of the License, or (at your option) any later version.
10 | *
11 | * This library is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 | * Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public
17 | * License along with this library; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin St, FΩifth Floor, Boston, MA 02110-1301 USA
19 | *
20 | * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com
21 | * Daniele Castagna - daniele dot castagna at gmail dot com
22 | *
23 | */
24 |
25 | /*
26 | * refer to miniupnpc-1.0-RC8
27 | */
28 | package org.bitlet.weupnp;
29 |
30 | import java.net.InetAddress;
31 | import java.text.DateFormat;
32 | import java.util.Date;
33 | import java.util.Map;
34 |
35 | /**
36 | * This class contains a trivial main method that can be used to test whether
37 | * weupnp is able to manipulate port mappings on a IGD (Internet Gateway
38 | * Device) on the same network.
39 | *
40 | * @author Alessandro Bahgat Shehata
41 | */
42 | public class Main {
43 |
44 | private static int SAMPLE_PORT = 6991;
45 | private static short WAIT_TIME = 10;
46 | private static boolean LIST_ALL_MAPPINGS = false;
47 |
48 | public static void main(String[] args) throws Exception{
49 |
50 | addLogLine("Starting weupnp");
51 |
52 | GatewayDiscover gatewayDiscover = new GatewayDiscover();
53 | addLogLine("Looking for Gateway Devices...");
54 |
55 | Map gateways = gatewayDiscover.discover();
56 |
57 | if (gateways.isEmpty()) {
58 | addLogLine("No gateways found");
59 | addLogLine("Stopping weupnp");
60 | return;
61 | }
62 | addLogLine(gateways.size()+" gateway(s) found\n");
63 |
64 | int counter=0;
65 | for (GatewayDevice gw: gateways.values()) {
66 | counter++;
67 | addLogLine("Listing gateway details of device #" + counter+
68 | "\n\tFriendly name: " + gw.getFriendlyName()+
69 | "\n\tPresentation URL: " + gw.getPresentationURL()+
70 | "\n\tModel name: " + gw.getModelName()+
71 | "\n\tModel number: " + gw.getModelNumber()+
72 | "\n\tLocal interface address: " + gw.getLocalAddress().getHostAddress()+"\n");
73 | }
74 |
75 | // choose the first active gateway for the tests
76 | GatewayDevice activeGW = gatewayDiscover.getValidGateway();
77 |
78 | if (null != activeGW) {
79 | addLogLine("Using gateway: " + activeGW.getFriendlyName());
80 | } else {
81 | addLogLine("No active gateway device found");
82 | addLogLine("Stopping weupnp");
83 | return;
84 | }
85 |
86 |
87 | // testing PortMappingNumberOfEntries
88 | Integer portMapCount = activeGW.getPortMappingNumberOfEntries();
89 | addLogLine("GetPortMappingNumberOfEntries: " + (portMapCount!=null?portMapCount.toString():"(unsupported)"));
90 |
91 | // testing getGenericPortMappingEntry
92 | PortMappingEntry portMapping = new PortMappingEntry();
93 | if (LIST_ALL_MAPPINGS) {
94 | int pmCount = 0;
95 | do {
96 | if (activeGW.getGenericPortMappingEntry(pmCount,portMapping))
97 | addLogLine("Portmapping #"+pmCount+" successfully retrieved ("+portMapping.getPortMappingDescription()+":"+portMapping.getExternalPort()+")");
98 | else{
99 | addLogLine("Portmapping #"+pmCount+" retrieval failed");
100 | break;
101 | }
102 | pmCount++;
103 | } while (portMapping!=null);
104 | } else {
105 | if (activeGW.getGenericPortMappingEntry(0,portMapping))
106 | addLogLine("Portmapping #0 successfully retrieved ("+portMapping.getPortMappingDescription()+":"+portMapping.getExternalPort()+")");
107 | else
108 | addLogLine("Portmapping #0 retrival failed");
109 | }
110 |
111 | InetAddress localAddress = activeGW.getLocalAddress();
112 | addLogLine("Using local address: "+ localAddress.getHostAddress());
113 | String externalIPAddress = activeGW.getExternalIPAddress();
114 | addLogLine("External address: "+ externalIPAddress);
115 |
116 | addLogLine("Querying device to see if a port mapping already exists for port "+ SAMPLE_PORT);
117 |
118 | if (activeGW.getSpecificPortMappingEntry(SAMPLE_PORT,"TCP",portMapping)) {
119 | addLogLine("Port "+SAMPLE_PORT+" is already mapped. Aborting test.");
120 | return;
121 | } else {
122 | addLogLine("Mapping free. Sending port mapping request for port "+SAMPLE_PORT);
123 |
124 | // test static lease duration mapping
125 | if (activeGW.addPortMapping(SAMPLE_PORT,SAMPLE_PORT,localAddress.getHostAddress(),"TCP","test")) {
126 | addLogLine("Mapping SUCCESSFUL. Waiting "+WAIT_TIME+" seconds before removing mapping...");
127 | Thread.sleep(1000*WAIT_TIME);
128 |
129 | if (activeGW.deletePortMapping(SAMPLE_PORT,"TCP")) {
130 | addLogLine("Port mapping removed, test SUCCESSFUL");
131 | } else {
132 | addLogLine("Port mapping removal FAILED");
133 | }
134 | }
135 | }
136 |
137 | addLogLine("Stopping weupnp");
138 | }
139 |
140 | private static void addLogLine(String line) {
141 |
142 | String timeStamp = DateFormat.getTimeInstance().format(new Date());
143 | String logline = timeStamp+": "+line+"\n";
144 | System.out.print(logline);
145 | }
146 |
147 | }
148 |
--------------------------------------------------------------------------------
/src/main/java/org/bitlet/weupnp/NameValueHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * weupnp - Trivial upnp java library
3 | *
4 | * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna
5 | *
6 | * This library is free software; you can redistribute it and/or
7 | * modify it under the terms of the GNU Lesser General Public
8 | * License as published by the Free Software Foundation; either
9 | * version 2.1 of the License, or (at your option) any later version.
10 | *
11 | * This library is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 | * Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public
17 | * License along with this library; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 | *
20 | * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com
21 | * Daniele Castagna - daniele dot castagna at gmail dot com
22 | *
23 | */
24 |
25 | package org.bitlet.weupnp;
26 |
27 | import java.util.Map;
28 | import org.xml.sax.Attributes;
29 | import org.xml.sax.SAXException;
30 | import org.xml.sax.helpers.DefaultHandler;
31 |
32 | /**
33 | * A simple SAX handler that is used to parse XML name value pairs in the form
34 | * <name>value</name>
35 | *
36 | * @see org.xml.sax.helpers.DefaultHandler
37 | */
38 | public class NameValueHandler extends DefaultHandler {
39 |
40 | /**
41 | * A reference to the name-value map to populate with the data being read
42 | */
43 | private Map nameValue;
44 |
45 | /**
46 | * The last read element
47 | */
48 | private String currentElement;
49 |
50 |
51 | /**
52 | * Creates a new instance of a NameValueHandler, storing values in
53 | * the supplied map
54 | *
55 | * @param nameValue the map to store name-value pairs in
56 | */
57 | public NameValueHandler(Map nameValue) {
58 | this.nameValue = nameValue;
59 | }
60 |
61 | /**
62 | * Receive notification of the start of an element.
63 | *
64 | * Caches the element as {@link #currentElement}, so that it will be stored
65 | * as a map key when the corresponding value will be read.
66 | *
67 | * @param uri The Namespace URI, or the empty string if the
68 | * element has no Namespace URI or if Namespace
69 | * processing is not being performed.
70 | * @param localName The local name (without prefix), or the
71 | * empty string if Namespace processing is not being
72 | * performed.
73 | * @param qName The qualified name (with prefix), or the
74 | * empty string if qualified names are not available.
75 | * @param attributes The attributes attached to the element. If
76 | * there are no attributes, it shall be an empty
77 | * Attributes object.
78 | * @exception org.xml.sax.SAXException Any SAX exception, possibly
79 | * wrapping another exception.
80 | * @see org.xml.sax.ContentHandler#startElement
81 | */
82 | @Override
83 | public void startElement(String uri, String localName, String qName,
84 | Attributes attributes) throws SAXException {
85 | currentElement = localName;
86 | }
87 |
88 | /**
89 | * Receive notification of the end of an element.
90 | *
91 | * It is used to reset currentElement when the XML node is closed.
92 | * Note: this works only when the data we are interested in does not contain
93 | * child nodes.
94 | *
95 | * Based on a patch provided by christophercyll and attached to issue #4:
96 | * http://code.google.com/p/weupnp/issues/detail?id=4
97 | *
98 | * @param uri The Namespace URI, or the empty string if the
99 | * element has no Namespace URI or if Namespace
100 | * processing is not being performed.
101 | * @param localName The local name (without prefix), or the
102 | * empty string if Namespace processing is not being
103 | * performed.
104 | * @param qName The qualified name (with prefix), or the
105 | * empty string if qualified names are not available.
106 | * @throws SAXException Any SAX exception, possibly
107 | * wrapping another exception.
108 | */
109 | @Override
110 | public void endElement(String uri, String localName, String qName)
111 | throws SAXException {
112 | currentElement = null;
113 | }
114 |
115 | /**
116 | * Receive notification of character data inside an element.
117 | *
118 | * Stores the characters as value, using {@link #currentElement} as a key
119 | *
120 | * @param ch The characters.
121 | * @param start The start position in the character array.
122 | * @param length The number of characters to use from the
123 | * character array.
124 | * @exception org.xml.sax.SAXException Any SAX exception, possibly
125 | * wrapping another exception.
126 | * @see org.xml.sax.ContentHandler#characters
127 | */
128 | @Override
129 | public void characters(char[] ch, int start, int length)
130 | throws SAXException {
131 | if (currentElement != null) {
132 | String value = new String(ch,start,length);
133 | String old = nameValue.put(currentElement, value);
134 | if (old != null) {
135 | nameValue.put(currentElement, old + value);
136 | }
137 | }
138 | }
139 |
140 |
141 |
142 | }
143 |
--------------------------------------------------------------------------------
/src/main/java/org/bitlet/weupnp/PortMappingEntry.java:
--------------------------------------------------------------------------------
1 | /*
2 | * weupnp - Trivial upnp java library
3 | *
4 | * Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna
5 | *
6 | * This library is free software; you can redistribute it and/or
7 | * modify it under the terms of the GNU Lesser General Public
8 | * License as published by the Free Software Foundation; either
9 | * version 2.1 of the License, or (at your option) any later version.
10 | *
11 | * This library is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 | * Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public
17 | * License along with this library; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 | *
20 | * Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com
21 | * Daniele Castagna - daniele dot castagna at gmail dot com
22 | *
23 | */
24 | package org.bitlet.weupnp;
25 |
26 | /**
27 | * A PortMappingEntry is the class used to represent port mappings on
28 | * the GatewayDevice.
29 | *
30 | * A port mapping on the GatewayDevice will allow all packets directed to port
31 | * externalPort of the external IP address of the GatewayDevice
32 | * using the specified protocol to be redirected to port
33 | * internalPort of internalClient.
34 | *
35 | * @see org.wetorrent.upnp.GatewayDevice
36 | * @see org.wetorrent.upnp.GatewayDevice#getExternalIPAddress()
37 | */
38 | public class PortMappingEntry {
39 |
40 | /**
41 | * The internal port
42 | */
43 | private int internalPort;
44 | /**
45 | * The external port of the mapping (the one on the GatewayDevice)
46 | */
47 | private int externalPort;
48 | /**
49 | * The remote host this mapping is associated with
50 | */
51 | private String remoteHost;
52 | /**
53 | * The internal host this mapping is associated with
54 | */
55 | private String internalClient;
56 | /**
57 | * The protocol associated with this mapping (i.e. TCP or
58 | * UDP)
59 | */
60 | private String protocol;
61 | /**
62 | * A flag that tells whether the mapping is enabled or not
63 | * ("1" for enabled, "0" for disabled)
64 | */
65 | private String enabled;
66 | /**
67 | * A human readable description of the port mapping (used for display
68 | * purposes)
69 | */
70 | private String portMappingDescription;
71 |
72 | /**
73 | * Creates a new PortMappingEntry
74 | */
75 | public PortMappingEntry() {
76 | }
77 |
78 | /**
79 | * Gets the internal port for this mapping
80 | * @return the {@link #internalPort}
81 | */
82 | public int getInternalPort() {
83 | return internalPort;
84 | }
85 |
86 | /**
87 | * Sets the {@link #internalPort}
88 | * @param internalPort the port to use
89 | */
90 | public void setInternalPort(int internalPort) {
91 | this.internalPort = internalPort;
92 | }
93 |
94 | /**
95 | * Gets the external (remote) port for this mapping
96 | * @return the {@link #externalPort}
97 | */
98 | public int getExternalPort() {
99 | return externalPort;
100 | }
101 |
102 | /**
103 | * Sets the {@link #externalPort}
104 | * @param externalPort the port to use
105 | */
106 | public void setExternalPort(int externalPort) {
107 | this.externalPort = externalPort;
108 | }
109 |
110 | /**
111 | * Gets the remote host this mapping is associated with
112 | * @return the {@link #remoteHost}
113 | */
114 | public String getRemoteHost() {
115 | return remoteHost;
116 | }
117 |
118 | /**
119 | * Sets the {@link #remoteHost}
120 | * @param remoteHost the host to set
121 | */
122 | public void setRemoteHost(String remoteHost) {
123 | this.remoteHost = remoteHost;
124 | }
125 |
126 | /**
127 | * Gets the internal host this mapping is associated with
128 | * @return the {@link internalClient}
129 | */
130 | public String getInternalClient() {
131 | return internalClient;
132 | }
133 |
134 | /**
135 | * Sets the {@link #internalClient}
136 | * @param internalClient the client to set
137 | */
138 | public void setInternalClient(String internalClient) {
139 | this.internalClient = internalClient;
140 | }
141 |
142 | /**
143 | * Gets the protocol associated with this mapping
144 | * @return {@link #protocol}
145 | */
146 | public String getProtocol() {
147 | return protocol;
148 | }
149 |
150 | /**
151 | * Sets the {@link #protocol} associated with this mapping
152 | * @param protocol one of TCP or UDP
153 | */
154 | public void setProtocol(String protocol) {
155 | this.protocol = protocol;
156 | }
157 |
158 | /**
159 | * Gets the enabled flag ("1" if enabled, "0" otherwise)
160 | * @return {@link #enabled}
161 | */
162 | public String getEnabled() {
163 | return enabled;
164 | }
165 |
166 | /**
167 | * Sets the {@link #enabled} flag
168 | * @param enabled "1" for enabled, "0" for disabled
169 | */
170 | public void setEnabled(String enabled) {
171 | this.enabled = enabled;
172 | }
173 |
174 | /**
175 | * Gets the port mapping description
176 | * @return {@link #portMappingDescription}
177 | */
178 | public String getPortMappingDescription() {
179 | return portMappingDescription;
180 | }
181 |
182 | /**
183 | * Sets the {@link #portMappingDescription}
184 | * @param portMappingDescription the description to set
185 | */
186 | public void setPortMappingDescription(String portMappingDescription) {
187 | this.portMappingDescription = portMappingDescription;
188 | }
189 | }
190 |
--------------------------------------------------------------------------------
/src/main/resources/license.txt:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 2.1, February 1999
3 |
4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc.
5 | 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | [This is the first released version of the Lesser GPL. It also counts
10 | as the successor of the GNU Library Public License, version 2, hence
11 | the version number 2.1.]
12 |
13 | Preamble
14 |
15 | The licenses for most software are designed to take away your
16 | freedom to share and change it. By contrast, the GNU General Public
17 | Licenses are intended to guarantee your freedom to share and change
18 | free software--to make sure the software is free for all its users.
19 |
20 | This license, the Lesser General Public License, applies to some
21 | specially designated software packages--typically libraries--of the
22 | Free Software Foundation and other authors who decide to use it. You
23 | can use it too, but we suggest you first think carefully about whether
24 | this license or the ordinary General Public License is the better
25 | strategy to use in any particular case, based on the explanations below.
26 |
27 | When we speak of free software, we are referring to freedom of use,
28 | not price. Our General Public Licenses are designed to make sure that
29 | you have the freedom to distribute copies of free software (and charge
30 | for this service if you wish); that you receive source code or can get
31 | it if you want it; that you can change the software and use pieces of
32 | it in new free programs; and that you are informed that you can do
33 | these things.
34 |
35 | To protect your rights, we need to make restrictions that forbid
36 | distributors to deny you these rights or to ask you to surrender these
37 | rights. These restrictions translate to certain responsibilities for
38 | you if you distribute copies of the library or if you modify it.
39 |
40 | For example, if you distribute copies of the library, whether gratis
41 | or for a fee, you must give the recipients all the rights that we gave
42 | you. You must make sure that they, too, receive or can get the source
43 | code. If you link other code with the library, you must provide
44 | complete object files to the recipients, so that they can relink them
45 | with the library after making changes to the library and recompiling
46 | it. And you must show them these terms so they know their rights.
47 |
48 | We protect your rights with a two-step method: (1) we copyright the
49 | library, and (2) we offer you this license, which gives you legal
50 | permission to copy, distribute and/or modify the library.
51 |
52 | To protect each distributor, we want to make it very clear that
53 | there is no warranty for the free library. Also, if the library is
54 | modified by someone else and passed on, the recipients should know
55 | that what they have is not the original version, so that the original
56 | author's reputation will not be affected by problems that might be
57 | introduced by others.
58 |
59 | Finally, software patents pose a constant threat to the existence of
60 | any free program. We wish to make sure that a company cannot
61 | effectively restrict the users of a free program by obtaining a
62 | restrictive license from a patent holder. Therefore, we insist that
63 | any patent license obtained for a version of the library must be
64 | consistent with the full freedom of use specified in this license.
65 |
66 | Most GNU software, including some libraries, is covered by the
67 | ordinary GNU General Public License. This license, the GNU Lesser
68 | General Public License, applies to certain designated libraries, and
69 | is quite different from the ordinary General Public License. We use
70 | this license for certain libraries in order to permit linking those
71 | libraries into non-free programs.
72 |
73 | When a program is linked with a library, whether statically or using
74 | a shared library, the combination of the two is legally speaking a
75 | combined work, a derivative of the original library. The ordinary
76 | General Public License therefore permits such linking only if the
77 | entire combination fits its criteria of freedom. The Lesser General
78 | Public License permits more lax criteria for linking other code with
79 | the library.
80 |
81 | We call this license the "Lesser" General Public License because it
82 | does Less to protect the user's freedom than the ordinary General
83 | Public License. It also provides other free software developers Less
84 | of an advantage over competing non-free programs. These disadvantages
85 | are the reason we use the ordinary General Public License for many
86 | libraries. However, the Lesser license provides advantages in certain
87 | special circumstances.
88 |
89 | For example, on rare occasions, there may be a special need to
90 | encourage the widest possible use of a certain library, so that it becomes
91 | a de-facto standard. To achieve this, non-free programs must be
92 | allowed to use the library. A more frequent case is that a free
93 | library does the same job as widely used non-free libraries. In this
94 | case, there is little to gain by limiting the free library to free
95 | software only, so we use the Lesser General Public License.
96 |
97 | In other cases, permission to use a particular library in non-free
98 | programs enables a greater number of people to use a large body of
99 | free software. For example, permission to use the GNU C Library in
100 | non-free programs enables many more people to use the whole GNU
101 | operating system, as well as its variant, the GNU/Linux operating
102 | system.
103 |
104 | Although the Lesser General Public License is Less protective of the
105 | users' freedom, it does ensure that the user of a program that is
106 | linked with the Library has the freedom and the wherewithal to run
107 | that program using a modified version of the Library.
108 |
109 | The precise terms and conditions for copying, distribution and
110 | modification follow. Pay close attention to the difference between a
111 | "work based on the library" and a "work that uses the library". The
112 | former contains code derived from the library, whereas the latter must
113 | be combined with the library in order to run.
114 |
115 | GNU LESSER GENERAL PUBLIC LICENSE
116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
117 |
118 | 0. This License Agreement applies to any software library or other
119 | program which contains a notice placed by the copyright holder or
120 | other authorized party saying it may be distributed under the terms of
121 | this Lesser General Public License (also called "this License").
122 | Each licensee is addressed as "you".
123 |
124 | A "library" means a collection of software functions and/or data
125 | prepared so as to be conveniently linked with application programs
126 | (which use some of those functions and data) to form executables.
127 |
128 | The "Library", below, refers to any such software library or work
129 | which has been distributed under these terms. A "work based on the
130 | Library" means either the Library or any derivative work under
131 | copyright law: that is to say, a work containing the Library or a
132 | portion of it, either verbatim or with modifications and/or translated
133 | straightforwardly into another language. (Hereinafter, translation is
134 | included without limitation in the term "modification".)
135 |
136 | "Source code" for a work means the preferred form of the work for
137 | making modifications to it. For a library, complete source code means
138 | all the source code for all modules it contains, plus any associated
139 | interface definition files, plus the scripts used to control compilation
140 | and installation of the library.
141 |
142 | Activities other than copying, distribution and modification are not
143 | covered by this License; they are outside its scope. The act of
144 | running a program using the Library is not restricted, and output from
145 | such a program is covered only if its contents constitute a work based
146 | on the Library (independent of the use of the Library in a tool for
147 | writing it). Whether that is true depends on what the Library does
148 | and what the program that uses the Library does.
149 |
150 | 1. You may copy and distribute verbatim copies of the Library's
151 | complete source code as you receive it, in any medium, provided that
152 | you conspicuously and appropriately publish on each copy an
153 | appropriate copyright notice and disclaimer of warranty; keep intact
154 | all the notices that refer to this License and to the absence of any
155 | warranty; and distribute a copy of this License along with the
156 | Library.
157 |
158 | You may charge a fee for the physical act of transferring a copy,
159 | and you may at your option offer warranty protection in exchange for a
160 | fee.
161 |
162 | 2. You may modify your copy or copies of the Library or any portion
163 | of it, thus forming a work based on the Library, and copy and
164 | distribute such modifications or work under the terms of Section 1
165 | above, provided that you also meet all of these conditions:
166 |
167 | a) The modified work must itself be a software library.
168 |
169 | b) You must cause the files modified to carry prominent notices
170 | stating that you changed the files and the date of any change.
171 |
172 | c) You must cause the whole of the work to be licensed at no
173 | charge to all third parties under the terms of this License.
174 |
175 | d) If a facility in the modified Library refers to a function or a
176 | table of data to be supplied by an application program that uses
177 | the facility, other than as an argument passed when the facility
178 | is invoked, then you must make a good faith effort to ensure that,
179 | in the event an application does not supply such function or
180 | table, the facility still operates, and performs whatever part of
181 | its purpose remains meaningful.
182 |
183 | (For example, a function in a library to compute square roots has
184 | a purpose that is entirely well-defined independent of the
185 | application. Therefore, Subsection 2d requires that any
186 | application-supplied function or table used by this function must
187 | be optional: if the application does not supply it, the square
188 | root function must still compute square roots.)
189 |
190 | These requirements apply to the modified work as a whole. If
191 | identifiable sections of that work are not derived from the Library,
192 | and can be reasonably considered independent and separate works in
193 | themselves, then this License, and its terms, do not apply to those
194 | sections when you distribute them as separate works. But when you
195 | distribute the same sections as part of a whole which is a work based
196 | on the Library, the distribution of the whole must be on the terms of
197 | this License, whose permissions for other licensees extend to the
198 | entire whole, and thus to each and every part regardless of who wrote
199 | it.
200 |
201 | Thus, it is not the intent of this section to claim rights or contest
202 | your rights to work written entirely by you; rather, the intent is to
203 | exercise the right to control the distribution of derivative or
204 | collective works based on the Library.
205 |
206 |
207 | In addition, mere aggregation of another work not based on the Library
208 | with the Library (or with a work based on the Library) on a volume of
209 | a storage or distribution medium does not bring the other work under
210 | the scope of this License.
211 |
212 | 3. You may opt to apply the terms of the ordinary GNU General Public
213 | License instead of this License to a given copy of the Library. To do
214 | this, you must alter all the notices that refer to this License, so
215 | that they refer to the ordinary GNU General Public License, version 2,
216 | instead of to this License. (If a newer version than version 2 of the
217 | ordinary GNU General Public License has appeared, then you can specify
218 | that version instead if you wish.) Do not make any other change in
219 | these notices.
220 |
221 | Once this change is made in a given copy, it is irreversible for
222 | that copy, so the ordinary GNU General Public License applies to all
223 | subsequent copies and derivative works made from that copy.
224 |
225 | This option is useful when you wish to copy part of the code of
226 | the Library into a program that is not a library.
227 |
228 | 4. You may copy and distribute the Library (or a portion or
229 | derivative of it, under Section 2) in object code or executable form
230 | under the terms of Sections 1 and 2 above provided that you accompany
231 | it with the complete corresponding machine-readable source code, which
232 | must be distributed under the terms of Sections 1 and 2 above on a
233 | medium customarily used for software interchange.
234 |
235 | If distribution of object code is made by offering access to copy
236 | from a designated place, then offering equivalent access to copy the
237 | source code from the same place satisfies the requirement to
238 | distribute the source code, even though third parties are not
239 | compelled to copy the source along with the object code.
240 |
241 | 5. A program that contains no derivative of any portion of the
242 | Library, but is designed to work with the Library by being compiled or
243 | linked with it, is called a "work that uses the Library". Such a
244 | work, in isolation, is not a derivative work of the Library, and
245 | therefore falls outside the scope of this License.
246 |
247 | However, linking a "work that uses the Library" with the Library
248 | creates an executable that is a derivative of the Library (because it
249 | contains portions of the Library), rather than a "work that uses the
250 | library". The executable is therefore covered by this License.
251 | Section 6 states terms for distribution of such executables.
252 |
253 | When a "work that uses the Library" uses material from a header file
254 | that is part of the Library, the object code for the work may be a
255 | derivative work of the Library even though the source code is not.
256 | Whether this is true is especially significant if the work can be
257 | linked without the Library, or if the work is itself a library. The
258 | threshold for this to be true is not precisely defined by law.
259 |
260 | If such an object file uses only numerical parameters, data
261 | structure layouts and accessors, and small macros and small inline
262 | functions (ten lines or less in length), then the use of the object
263 | file is unrestricted, regardless of whether it is legally a derivative
264 | work. (Executables containing this object code plus portions of the
265 | Library will still fall under Section 6.)
266 |
267 | Otherwise, if the work is a derivative of the Library, you may
268 | distribute the object code for the work under the terms of Section 6.
269 | Any executables containing that work also fall under Section 6,
270 | whether or not they are linked directly with the Library itself.
271 |
272 | 6. As an exception to the Sections above, you may also combine or
273 | link a "work that uses the Library" with the Library to produce a
274 | work containing portions of the Library, and distribute that work
275 | under terms of your choice, provided that the terms permit
276 | modification of the work for the customer's own use and reverse
277 | engineering for debugging such modifications.
278 |
279 | You must give prominent notice with each copy of the work that the
280 | Library is used in it and that the Library and its use are covered by
281 | this License. You must supply a copy of this License. If the work
282 | during execution displays copyright notices, you must include the
283 | copyright notice for the Library among them, as well as a reference
284 | directing the user to the copy of this License. Also, you must do one
285 | of these things:
286 |
287 | a) Accompany the work with the complete corresponding
288 | machine-readable source code for the Library including whatever
289 | changes were used in the work (which must be distributed under
290 | Sections 1 and 2 above); and, if the work is an executable linked
291 | with the Library, with the complete machine-readable "work that
292 | uses the Library", as object code and/or source code, so that the
293 | user can modify the Library and then relink to produce a modified
294 | executable containing the modified Library. (It is understood
295 | that the user who changes the contents of definitions files in the
296 | Library will not necessarily be able to recompile the application
297 | to use the modified definitions.)
298 |
299 | b) Use a suitable shared library mechanism for linking with the
300 | Library. A suitable mechanism is one that (1) uses at run time a
301 | copy of the library already present on the user's computer system,
302 | rather than copying library functions into the executable, and (2)
303 | will operate properly with a modified version of the library, if
304 | the user installs one, as long as the modified version is
305 | interface-compatible with the version that the work was made with.
306 |
307 | c) Accompany the work with a written offer, valid for at
308 | least three years, to give the same user the materials
309 | specified in Subsection 6a, above, for a charge no more
310 | than the cost of performing this distribution.
311 |
312 | d) If distribution of the work is made by offering access to copy
313 | from a designated place, offer equivalent access to copy the above
314 | specified materials from the same place.
315 |
316 | e) Verify that the user has already received a copy of these
317 | materials or that you have already sent this user a copy.
318 |
319 | For an executable, the required form of the "work that uses the
320 | Library" must include any data and utility programs needed for
321 | reproducing the executable from it. However, as a special exception,
322 | the materials to be distributed need not include anything that is
323 | normally distributed (in either source or binary form) with the major
324 | components (compiler, kernel, and so on) of the operating system on
325 | which the executable runs, unless that component itself accompanies
326 | the executable.
327 |
328 | It may happen that this requirement contradicts the license
329 | restrictions of other proprietary libraries that do not normally
330 | accompany the operating system. Such a contradiction means you cannot
331 | use both them and the Library together in an executable that you
332 | distribute.
333 |
334 | 7. You may place library facilities that are a work based on the
335 | Library side-by-side in a single library together with other library
336 | facilities not covered by this License, and distribute such a combined
337 | library, provided that the separate distribution of the work based on
338 | the Library and of the other library facilities is otherwise
339 | permitted, and provided that you do these two things:
340 |
341 | a) Accompany the combined library with a copy of the same work
342 | based on the Library, uncombined with any other library
343 | facilities. This must be distributed under the terms of the
344 | Sections above.
345 |
346 | b) Give prominent notice with the combined library of the fact
347 | that part of it is a work based on the Library, and explaining
348 | where to find the accompanying uncombined form of the same work.
349 |
350 | 8. You may not copy, modify, sublicense, link with, or distribute
351 | the Library except as expressly provided under this License. Any
352 | attempt otherwise to copy, modify, sublicense, link with, or
353 | distribute the Library is void, and will automatically terminate your
354 | rights under this License. However, parties who have received copies,
355 | or rights, from you under this License will not have their licenses
356 | terminated so long as such parties remain in full compliance.
357 |
358 | 9. You are not required to accept this License, since you have not
359 | signed it. However, nothing else grants you permission to modify or
360 | distribute the Library or its derivative works. These actions are
361 | prohibited by law if you do not accept this License. Therefore, by
362 | modifying or distributing the Library (or any work based on the
363 | Library), you indicate your acceptance of this License to do so, and
364 | all its terms and conditions for copying, distributing or modifying
365 | the Library or works based on it.
366 |
367 | 10. Each time you redistribute the Library (or any work based on the
368 | Library), the recipient automatically receives a license from the
369 | original licensor to copy, distribute, link with or modify the Library
370 | subject to these terms and conditions. You may not impose any further
371 | restrictions on the recipients' exercise of the rights granted herein.
372 | You are not responsible for enforcing compliance by third parties with
373 | this License.
374 |
375 | 11. If, as a consequence of a court judgment or allegation of patent
376 | infringement or for any other reason (not limited to patent issues),
377 | conditions are imposed on you (whether by court order, agreement or
378 | otherwise) that contradict the conditions of this License, they do not
379 | excuse you from the conditions of this License. If you cannot
380 | distribute so as to satisfy simultaneously your obligations under this
381 | License and any other pertinent obligations, then as a consequence you
382 | may not distribute the Library at all. For example, if a patent
383 | license would not permit royalty-free redistribution of the Library by
384 | all those who receive copies directly or indirectly through you, then
385 | the only way you could satisfy both it and this License would be to
386 | refrain entirely from distribution of the Library.
387 |
388 | If any portion of this section is held invalid or unenforceable under any
389 | particular circumstance, the balance of the section is intended to apply,
390 | and the section as a whole is intended to apply in other circumstances.
391 |
392 | It is not the purpose of this section to induce you to infringe any
393 | patents or other property right claims or to contest validity of any
394 | such claims; this section has the sole purpose of protecting the
395 | integrity of the free software distribution system which is
396 | implemented by public license practices. Many people have made
397 | generous contributions to the wide range of software distributed
398 | through that system in reliance on consistent application of that
399 | system; it is up to the author/donor to decide if he or she is willing
400 | to distribute software through any other system and a licensee cannot
401 | impose that choice.
402 |
403 | This section is intended to make thoroughly clear what is believed to
404 | be a consequence of the rest of this License.
405 |
406 | 12. If the distribution and/or use of the Library is restricted in
407 | certain countries either by patents or by copyrighted interfaces, the
408 | original copyright holder who places the Library under this License may add
409 | an explicit geographical distribution limitation excluding those countries,
410 | so that distribution is permitted only in or among countries not thus
411 | excluded. In such case, this License incorporates the limitation as if
412 | written in the body of this License.
413 |
414 |
415 | 13. The Free Software Foundation may publish revised and/or new
416 | versions of the Lesser General Public License from time to time.
417 | Such new versions will be similar in spirit to the present version,
418 | but may differ in detail to address new problems or concerns.
419 |
420 | Each version is given a distinguishing version number. If the Library
421 | specifies a version number of this License which applies to it and
422 | "any later version", you have the option of following the terms and
423 | conditions either of that version or of any later version published by
424 | the Free Software Foundation. If the Library does not specify a
425 | license version number, you may choose any version ever published by
426 | the Free Software Foundation.
427 |
428 | 14. If you wish to incorporate parts of the Library into other free
429 | programs whose distribution conditions are incompatible with these,
430 | write to the author to ask for permission. For software which is
431 | copyrighted by the Free Software Foundation, write to the Free
432 | Software Foundation; we sometimes make exceptions for this. Our
433 | decision will be guided by the two goals of preserving the free status
434 | of all derivatives of our free software and of promoting the sharing
435 | and reuse of software generally.
436 |
437 | NO WARRANTY
438 |
439 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
440 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
441 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
442 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
443 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
444 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
445 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
446 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
447 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
448 |
449 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
450 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
451 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
452 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
453 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
454 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
455 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
456 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
457 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
458 | DAMAGES.
459 |
460 | END OF TERMS AND CONDITIONS
461 |
462 | How to Apply These Terms to Your New Libraries
463 |
464 | If you develop a new library, and you want it to be of the greatest
465 | possible use to the public, we recommend making it free software that
466 | everyone can redistribute and change. You can do so by permitting
467 | redistribution under these terms (or, alternatively, under the terms of the
468 | ordinary General Public License).
469 |
470 | To apply these terms, attach the following notices to the library. It is
471 | safest to attach them to the start of each source file to most effectively
472 | convey the exclusion of warranty; and each file should have at least the
473 | "copyright" line and a pointer to where the full notice is found.
474 |
475 |
476 | Copyright (C)
477 |
478 | This library is free software; you can redistribute it and/or
479 | modify it under the terms of the GNU Lesser General Public
480 | License as published by the Free Software Foundation; either
481 | version 2.1 of the License, or (at your option) any later version.
482 |
483 | This library is distributed in the hope that it will be useful,
484 | but WITHOUT ANY WARRANTY; without even the implied warranty of
485 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
486 | Lesser General Public License for more details.
487 |
488 | You should have received a copy of the GNU Lesser General Public
489 | License along with this library; if not, write to the Free Software
490 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
491 |
492 | Also add information on how to contact you by electronic and paper mail.
493 |
494 | You should also get your employer (if you work as a programmer) or your
495 | school, if any, to sign a "copyright disclaimer" for the library, if
496 | necessary. Here is a sample; alter the names:
497 |
498 | Yoyodyne, Inc., hereby disclaims all copyright interest in the
499 | library `Frob' (a library for tweaking knobs) written by James Random Hacker.
500 |
501 | , 1 April 1990
502 | Ty Coon, President of Vice
503 |
504 | That's all there is to it!
--------------------------------------------------------------------------------