From 312e6071d7eac58fe1b70297789fd8a9d563833b Mon Sep 17 00:00:00 2001
From: zzz Device : "+dev.getFriendlyName()+" - "+ dev.getDeviceType()+"
");
+ if("urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1".equals(serv.getServiceType())){
+ sb.append("WANCommonInterfaceConfig");
+ sb.append(" status: " + toString("GetCommonLinkProperties", "NewPhysicalLinkStatus", serv));
+ sb.append(" type: " + toString("GetCommonLinkProperties", "NewWANAccessType", serv));
+ sb.append(" upstream: " + toString("GetCommonLinkProperties", "NewLayer1UpstreamMaxBitRate", serv));
+ sb.append(" downstream: " + toString("GetCommonLinkProperties", "NewLayer1DownstreamMaxBitRate", serv) + "
");
+ }else if("urn:schemas-upnp-org:service:WANPPPConnection:1".equals(serv.getServiceType())){
+ sb.append("WANPPPConnection");
+ sb.append(" status: " + toString("GetStatusInfo", "NewConnectionStatus", serv));
+ sb.append(" type: " + toString("GetConnectionTypeInfo", "NewConnectionType", serv));
+ sb.append(" upstream: " + toString("GetLinkLayerMaxBitRates", "NewUpstreamMaxBitRate", serv));
+ sb.append(" downstream: " + toString("GetLinkLayerMaxBitRates", "NewDownstreamMaxBitRate", serv) + "
");
+ sb.append(" external IP: " + toString("GetExternalIPAddress", "NewExternalIPAddress", serv) + "
");
+ }else if("urn:schemas-upnp-org:service:Layer3Forwarding:1".equals(serv.getServiceType())){
+ sb.append("Layer3Forwarding");
+ sb.append("DefaultConnectionService: " + toString("GetDefaultConnectionService", "NewDefaultConnectionService", serv));
+ }else if(WAN_IP_CONNECTION.equals(serv.getServiceType())){
+ sb.append("WANIPConnection");
+ sb.append(" status: " + toString("GetStatusInfo", "NewConnectionStatus", serv));
+ sb.append(" type: " + toString("GetConnectionTypeInfo", "NewConnectionType", serv));
+ sb.append(" external IP: " + toString("GetExternalIPAddress", "NewExternalIPAddress", serv) + "
");
+ }else if("urn:schemas-upnp-org:service:WANEthernetLinkConfig:1".equals(serv.getServiceType())){
+ sb.append("WANEthernetLinkConfig");
+ sb.append(" status: " + toString("GetEthernetLinkStatus", "NewEthernetLinkStatus", serv) + "
");
+ }else
+ sb.append("~~~~~~~ "+serv.getServiceType());
+ listActions(serv, sb);
+ listStateTable(serv, sb);
+ sb.append("");
+ }
+ }
+
+ private void listSubDev(String prefix, Device dev, StringBuilder sb){
+ sb.append("
");
+ listSubServices(dev, sb);
+
+ DeviceList dl = dev.getDeviceList();
+ for(int j=0; j
There are following different + * kinds of parser depending on which features are set:
There are two key methods: next() and nextToken(). While next() provides + * access to high level parsing events, nextToken() allows access to lower + * level tokens. + * + *
The current event state of the parser + * can be determined by calling the + * getEventType() method. + * Initially, the parser is in the START_DOCUMENT + * state. + * + *
The method next() advances the parser to the + * next event. The int value returned from next determines the current parser + * state and is identical to the value returned from following calls to + * getEventType (). + * + *
Th following event types are seen by next()
after first next() or nextToken() (or any other next*() method) + * is called user application can obtain + * XML version, standalone and encoding from XML declaration + * in following ways:
+ * import java.io.IOException; + * import java.io.StringReader; + * + * import plugins.JabberLinker.org.xmlpull.v1.XmlPullParser; + * import plugins.JabberLinker.org.xmlpull.v1.XmlPullParserException.html; + * import plugins.JabberLinker.org.xmlpull.v1.XmlPullParserFactory; + * + * public class SimpleXmlPullApp + * { + * + * public static void main (String args[]) + * throws XmlPullParserException, IOException + * { + * XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); + * factory.setNamespaceAware(true); + * XmlPullParser xpp = factory.newPullParser(); + * + * xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) ); + * int eventType = xpp.getEventType(); + * while (eventType != XmlPullParser.END_DOCUMENT) { + * if(eventType == XmlPullParser.START_DOCUMENT) { + * System.out.println("Start document"); + * } else if(eventType == XmlPullParser.END_DOCUMENT) { + * System.out.println("End document"); + * } else if(eventType == XmlPullParser.START_TAG) { + * System.out.println("Start tag "+xpp.getName()); + * } else if(eventType == XmlPullParser.END_TAG) { + * System.out.println("End tag "+xpp.getName()); + * } else if(eventType == XmlPullParser.TEXT) { + * System.out.println("Text "+xpp.getText()); + * } + * eventType = xpp.next(); + * } + * } + * } + *+ * + *
The above example will generate the following output: + *
+ * Start document + * Start tag foo + * Text Hello World! + * End tag foo + *+ * + *
For more details on API usage, please refer to the + * quick Introduction available at http://www.xmlpull.org + * + * @see XmlPullParserFactory + * @see #defineEntityReplacementText + * @see #getName + * @see #getNamespace + * @see #getText + * @see #next + * @see #nextToken + * @see #setInput + * @see #FEATURE_PROCESS_DOCDECL + * @see #FEATURE_VALIDATION + * @see #START_DOCUMENT + * @see #START_TAG + * @see #TEXT + * @see #END_TAG + * @see #END_DOCUMENT + * + * @author Stefan Haustein + * @author Aleksander Slominski + */ + +public interface XmlPullParser { + + /** This constant represents the default namespace (empty string "") */ + String NO_NAMESPACE = ""; + + // ---------------------------------------------------------------------------- + // EVENT TYPES as reported by next() + + /** + * Signalize that parser is at the very beginning of the document + * and nothing was read yet. + * This event type can only be observed by calling getEvent() + * before the first call to next(), nextToken, or nextTag()). + * + * @see #next + * @see #nextToken + */ + int START_DOCUMENT = 0; + + /** + * Logical end of the xml document. Returned from getEventType, next() + * and nextToken() + * when the end of the input document has been reached. + *
NOTE: calling again + * next() or nextToken() + * will result in exception being thrown. + * + * @see #next + * @see #nextToken + */ + int END_DOCUMENT = 1; + + /** + * Returned from getEventType(), + * next(), nextToken() when + * a start tag was read. + * The name of start tag is available from getName(), its namespace and prefix are + * available from getNamespace() and getPrefix() + * if namespaces are enabled. + * See getAttribute* methods to retrieve element attributes. + * See getNamespace* methods to retrieve newly declared namespaces. + * + * @see #next + * @see #nextToken + * @see #getName + * @see #getPrefix + * @see #getNamespace + * @see #getAttributeCount + * @see #getDepth + * @see #getNamespaceCount + * @see #getNamespace + * @see #FEATURE_PROCESS_NAMESPACES + */ + int START_TAG = 2; + + /** + * Returned from getEventType(), next(), or + * nextToken() when an end tag was read. + * The name of start tag is available from getName(), its + * namespace and prefix are + * available from getNamespace() and getPrefix(). + * + * @see #next + * @see #nextToken + * @see #getName + * @see #getPrefix + * @see #getNamespace + * @see #FEATURE_PROCESS_NAMESPACES + */ + int END_TAG = 3; + + + /** + * Character data was read and will is available by calling getText(). + *
Please note: next() will + * accumulate multiple + * events into one TEXT event, skipping IGNORABLE_WHITESPACE, + * PROCESSING_INSTRUCTION and COMMENT events, + * In contrast, nextToken() will stop reading + * text when any other event is observed. + * Also, when the state was reached by calling next(), the text value will + * be normalized, whereas getText() will + * return unnormalized content in the case of nextToken(). This allows + * an exact roundtrip without chnanging line ends when examining low + * level events, whereas for high level applications the text is + * normalized apropriately. + * + * @see #next + * @see #nextToken + * @see #getText + */ + int TEXT = 4; + + // ---------------------------------------------------------------------------- + // additional events exposed by lower level nextToken() + + /** + * A CDATA sections was just read; + * this token is available only from calls to nextToken(). + * A call to next() will accumulate various text events into a single event + * of type TEXT. The text contained in the CDATA section is available + * by callling getText(). + * + * @see #nextToken + * @see #getText + */ + int CDSECT = 5; + + /** + * An entity reference was just read; + * this token is available from nextToken() + * only. The entity name is available by calling getName(). If available, + * the replacement text can be obtained by calling getTextt(); otherwise, + * the user is responsibile for resolving the entity reference. + * This event type is never returned from next(); next() will + * accumulate the replacement text and other text + * events to a single TEXT event. + * + * @see #nextToken + * @see #getText + */ + int ENTITY_REF = 6; + + /** + * Ignorable whitespace was just read. + * This token is available only from nextToken()). + * For non-validating + * parsers, this event is only reported by nextToken() when outside + * the root element. + * Validating parsers may be able to detect ignorable whitespace at + * other locations. + * The ignorable whitespace string is available by calling getText() + * + *
NOTE: this is different from calling the + * isWhitespace() method, since text content + * may be whitespace but not ignorable. + * + * Ignorable whitespace is skipped by next() automatically; this event + * type is never returned from next(). + * + * @see #nextToken + * @see #getText + */ + int IGNORABLE_WHITESPACE = 7; + + /** + * An XML processing instruction declaration was just read. This + * event type is available only via nextToken(). + * getText() will return text that is inside the processing instruction. + * Calls to next() will skip processing instructions automatically. + * @see #nextToken + * @see #getText + */ + int PROCESSING_INSTRUCTION = 8; + + /** + * An XML comment was just read. This event type is this token is + * available via nextToken() only; + * calls to next() will skip comments automatically. + * The content of the comment can be accessed using the getText() + * method. + * + * @see #nextToken + * @see #getText + */ + int COMMENT = 9; + + /** + * An XML document type declaration was just read. This token is + * available from nextToken() only. + * The unparsed text inside the doctype is available via + * the getText() method. + * + * @see #nextToken + * @see #getText + */ + int DOCDECL = 10; + + /** + * This array can be used to convert the event type integer constants + * such as START_TAG or TEXT to + * to a string. For example, the value of TYPES[START_TAG] is + * the string "START_TAG". + * + * This array is intended for diagnostic output only. Relying + * on the contents of the array may be dangerous since malicous + * applications may alter the array, although it is final, due + * to limitations of the Java language. + */ + String [] TYPES = { + "START_DOCUMENT", + "END_DOCUMENT", + "START_TAG", + "END_TAG", + "TEXT", + "CDSECT", + "ENTITY_REF", + "IGNORABLE_WHITESPACE", + "PROCESSING_INSTRUCTION", + "COMMENT", + "DOCDECL" + }; + + + // ---------------------------------------------------------------------------- + // namespace related features + + /** + * This feature determines whether the parser processes + * namespaces. As for all features, the default value is false. + *
NOTE: The value can not be changed during + * parsing an must be set before parsing. + * + * @see #getFeature + * @see #setFeature + */ + String FEATURE_PROCESS_NAMESPACES = + "http://xmlpull.org/v1/doc/features.html#process-namespaces"; + + /** + * This feature determines whether namespace attributes are + * exposed via the attribute access methods. Like all features, + * the default value is false. This feature cannot be changed + * during parsing. + * + * @see #getFeature + * @see #setFeature + */ + String FEATURE_REPORT_NAMESPACE_ATTRIBUTES = + "http://xmlpull.org/v1/doc/features.html#report-namespace-prefixes"; + + /** + * This feature determines whether the document declaration + * is processed. If set to false, + * the DOCDECL event type is reported by nextToken() + * and ignored by next(). + * + * If this featue is activated, then the document declaration + * must be processed by the parser. + * + *
Please note: If the document type declaration + * was ignored, entity references may cause exceptions + * later in the parsing process. + * The default value of this feature is false. It cannot be changed + * during parsing. + * + * @see #getFeature + * @see #setFeature + */ + String FEATURE_PROCESS_DOCDECL = + "http://xmlpull.org/v1/doc/features.html#process-docdecl"; + + /** + * If this feature is activated, all validation errors as + * defined in the XML 1.0 sepcification are reported. + * This implies that FEATURE_PROCESS_DOCDECL is true and both, the + * internal and external document type declaration will be processed. + *
Please Note: This feature can not be changed + * during parsing. The default value is false. + * + * @see #getFeature + * @see #setFeature + */ + String FEATURE_VALIDATION = + "http://xmlpull.org/v1/doc/features.html#validation"; + + /** + * Use this call to change the general behaviour of the parser, + * such as namespace processing or doctype declaration handling. + * This method must be called before the first call to next or + * nextToken. Otherwise, an exception is thrown. + *
Example: call setFeature(FEATURE_PROCESS_NAMESPACES, true) in order + * to switch on namespace processing. The initial settings correspond + * to the properties requested from the XML Pull Parser factory. + * If none were requested, all feautures are deactivated by default. + * + * @exception XmlPullParserException If the feature is not supported or can not be set + * @exception IllegalArgumentException If string with the feature name is null + */ + void setFeature(String name, + boolean state) throws XmlPullParserException; + + /** + * Returns the current value of the given feature. + *
Please note: unknown features are + * always returned as false. + * + * @param name The name of feature to be retrieved. + * @return The value of the feature. + * @exception IllegalArgumentException if string the feature name is null + */ + + boolean getFeature(String name); + + /** + * Set the value of a property. + * + * The property name is any fully-qualified URI. + * + * @exception XmlPullParserException If the property is not supported or can not be set + * @exception IllegalArgumentException If string with the property name is null + */ + void setProperty(String name, + Object value) throws XmlPullParserException; + + /** + * Look up the value of a property. + * + * The property name is any fully-qualified URI. + *
NOTE: unknown properties are always + * returned as null. + * + * @param name The name of property to be retrieved. + * @return The value of named property. + */ + Object getProperty(String name); + + + /** + * Set the input source for parser to the given reader and + * resets the parser. The event type is set to the initial value + * START_DOCUMENT. + * Setting the reader to null will just stop parsing and + * reset parser state, + * allowing the parser to free internal resources + * such as parsing buffers. + */ + void setInput(Reader in) throws XmlPullParserException; + + + /** + * Sets the input stream the parser is going to process. + * This call resets the parser state and sets the event type + * to the initial value START_DOCUMENT. + * + *
NOTE: If an input encoding string is passed, + * it MUST be used. Otherwise, + * if inputEncoding is null, the parser SHOULD try to determine + * input encoding following XML 1.0 specification (see below). + * If encoding detection is supported then following feature + * http://xmlpull.org/v1/doc/features.html#detect-encoding + * MUST be true amd otherwise it must be false + * + * @param inputStream contains a raw byte input stream of possibly + * unknown encoding (when inputEncoding is null). + * + * @param inputEncoding if not null it MUST be used as encoding for inputStream + */ + void setInput(InputStream inputStream, String inputEncoding) + throws XmlPullParserException; + + /** + * Returns the input encoding if known, null otherwise. + * If setInput(InputStream, inputEncoding) was called with an inputEncoding + * value other than null, this value must be returned + * from this method. Otherwise, if inputEncoding is null and + * the parser suppports the encoding detection feature + * (http://xmlpull.org/v1/doc/features.html#detect-encoding), + * it must return the detected encoding. + * If setInput(Reader) was called, null is returned. + * After first call to next if XML declaration was present this method + * will return encoding declared. + */ + String getInputEncoding(); + + /** + * Set new value for entity replacement text as defined in + * XML 1.0 Section 4.5 + * Construction of Internal Entity Replacement Text. + * If FEATURE_PROCESS_DOCDECL or FEATURE_VALIDATION are set, calling this + * function will result in an exception -- when processing of DOCDECL is + * enabled, there is no need to the entity replacement text manually. + * + *
The motivation for this function is to allow very small + * implementations of XMLPULL that will work in J2ME environments. + * Though these implementations may not be able to process the document type + * declaration, they still can work with known DTDs by using this function. + * + *
Please notes: The given value is used literally as replacement text + * and it corresponds to declaring entity in DTD that has all special characters + * escaped: left angle bracket is replaced with <, ampersnad with & + * and so on. + * + *
Note: The given value is the literal replacement text and must not + * contain any other entity reference (if it contains any entity reference + * there will be no further replacement). + * + *
Note: The list of pre-defined entity names will + * always contain standard XML entities such as + * amp (&), lt (<), gt (>), quot ("), and apos ('). + * Those cannot be redefined by this method! + * + * @see #setInput + * @see #FEATURE_PROCESS_DOCDECL + * @see #FEATURE_VALIDATION + */ + void defineEntityReplacementText( String entityName, + String replacementText ) throws XmlPullParserException; + + /** + * Returns the numbers of elements in the namespace stack for the given + * depth. + * If namespaces are not enabled, 0 is returned. + * + *
NOTE: when parser is on END_TAG then it is allowed to call + * this function with getDepth()+1 argument to retrieve position of namespace + * prefixes and URIs that were declared on corresponding START_TAG. + *
NOTE: to retrieve lsit of namespaces declared in current element:
+ * XmlPullParser pp = ... + * int nsStart = pp.getNamespaceCount(pp.getDepth()-1); + * int nsEnd = pp.getNamespaceCount(pp.getDepth()); + * for (int i = nsStart; i < nsEnd; i++) { + * String prefix = pp.getNamespacePrefix(i); + * String ns = pp.getNamespaceUri(i); + * // ... + * } + *+ * + * @see #getNamespacePrefix + * @see #getNamespaceUri + * @see #getNamespace() + * @see #getNamespace(String) + */ + int getNamespaceCount(int depth) throws XmlPullParserException; + + /** + * Returns the namespace prefixe for the given position + * in the namespace stack. + * Default namespace declaration (xmlns='...') will have null as prefix. + * If the given index is out of range, an exception is thrown. + *
Please note: when the parser is on an END_TAG, + * namespace prefixes that were declared + * in the corresponding START_TAG are still accessible + * although they are no longer in scope. + */ + String getNamespacePrefix(int pos) throws XmlPullParserException; + + /** + * Returns the namespace URI for the given position in the + * namespace stack + * If the position is out of range, an exception is thrown. + *
NOTE: when parser is on END_TAG then namespace prefixes that were declared + * in corresponding START_TAG are still accessible even though they are not in scope + */ + String getNamespaceUri(int pos) throws XmlPullParserException; + + /** + * Returns the URI corresponding to the given prefix, + * depending on current state of the parser. + * + *
If the prefix was not declared in the current scope, + * null is returned. The default namespace is included + * in the namespace table and is available via + * getNamespace (null). + * + *
This method is a convenience method for + * + *
+ * for (int i = getNamespaceCount(getDepth ())-1; i >= 0; i--) { + * if (getNamespacePrefix(i).equals( prefix )) { + * return getNamespaceUri(i); + * } + * } + * return null; + *+ * + *
Please note: parser implementations + * may provide more efifcient lookup, e.g. using a Hashtable. + * The 'xml' prefix is bound to "http://www.w3.org/XML/1998/namespace", as + * defined in the + * Namespaces in XML + * specification. Analogous, the 'xmlns' prefix is resolved to + * http://www.w3.org/2000/xmlns/ + * + * @see #getNamespaceCount + * @see #getNamespacePrefix + * @see #getNamespaceUri + */ + String getNamespace (String prefix); + + + // -------------------------------------------------------------------------- + // miscellaneous reporting methods + + /** + * Returns the current depth of the element. + * Outside the root element, the depth is 0. The + * depth is incremented by 1 when a start tag is reached. + * The depth is decremented AFTER the end tag + * event was observed. + * + *
+ * <!-- outside --> 0 + * <root> 1 + * sometext 1 + * <foobar> 2 + * </foobar> 2 + * </root> 1 + * <!-- outside --> 0 + *+ */ + int getDepth(); + + /** + * Returns a short text describing the current parser state, including + * the position, a + * description of the current event and the data source if known. + * This method is especially useful to provide meaningful + * error messages and for debugging purposes. + */ + String getPositionDescription (); + + + /** + * Returns the current line number, starting from 1. + * When the parser does not know the current line number + * or can not determine it, -1 is returned (e.g. for WBXML). + * + * @return current line number or -1 if unknown. + */ + int getLineNumber(); + + /** + * Returns the current column number, starting from 0. + * When the parser does not know the current column number + * or can not determine it, -1 is returned (e.g. for WBXML). + * + * @return current column number or -1 if unknown. + */ + int getColumnNumber(); + + + // -------------------------------------------------------------------------- + // TEXT related methods + + /** + * Checks whether the current TEXT event contains only whitespace + * characters. + * For IGNORABLE_WHITESPACE, this is always true. + * For TEXT and CDSECT, false is returned when the current event text + * contains at least one non-white space character. For any other + * event type an exception is thrown. + * + *
Please note: non-validating parsers are not + * able to distinguish whitespace and ignorable whitespace, + * except from whitespace outside the root element. Ignorable + * whitespace is reported as separate event, which is exposed + * via nextToken only. + * + */ + boolean isWhitespace() throws XmlPullParserException; + + /** + * Returns the text content of the current event as String. + * The value returned depends on current event type, + * for example for TEXT event it is element content + * (this is typical case when next() is used). + * + * See description of nextToken() for detailed description of + * possible returned values for different types of events. + * + *
NOTE: in case of ENTITY_REF, this method returns + * the entity replacement text (or null if not available). This is + * the only case where + * getText() and getTextCharacters() return different values. + * + * @see #getEventType + * @see #next + * @see #nextToken + */ + String getText (); + + + /** + * Returns the buffer that contains the text of the current event, + * as well as the start offset and length relevant for the current + * event. See getText(), next() and nextToken() for description of possible returned values. + * + *
Please note: this buffer must not + * be modified and its content MAY change after a call to + * next() or nextToken(). This method will always return the + * same value as getText(), except for ENTITY_REF. In the case + * of ENTITY ref, getText() returns the replacement text and + * this method returns the actual input buffer containing the + * entity name. + * If getText() returns null, this method returns null as well and + * the values returned in the holder array MUST be -1 (both start + * and length). + * + * @see #getText + * @see #next + * @see #nextToken + * + * @param holderForStartAndLength Must hold an 2-element int array + * into which the start offset and length values will be written. + * @return char buffer that contains the text of the current event + * (null if the current event has no text associated). + */ + char[] getTextCharacters(int [] holderForStartAndLength); + + // -------------------------------------------------------------------------- + // START_TAG / END_TAG shared methods + + /** + * Returns the namespace URI of the current element. + * The default namespace is represented + * as empty string. + * If namespaces are not enabled, an empty String ("") is always returned. + * The current event must be START_TAG or END_TAG; otherwise, + * null is returned. + */ + String getNamespace (); + + /** + * For START_TAG or END_TAG events, the (local) name of the current + * element is returned when namespaces are enabled. When namespace + * processing is disabled, the raw name is returned. + * For ENTITY_REF events, the entity name is returned. + * If the current event is not START_TAG, END_TAG, or ENTITY_REF, + * null is returned. + *
Please note: To reconstruct the raw element name + * when namespaces are enabled and the prefix is not null, + * you will need to add the prefix and a colon to localName.. + * + */ + String getName(); + + /** + * Returns the prefix of the current element. + * If the element is in the default namespace (has no prefix), + * null is returned. + * If namespaces are not enabled, or the current event + * is not START_TAG or END_TAG, null is returned. + */ + String getPrefix(); + + /** + * Returns true if the current event is START_TAG and the tag + * is degenerated + * (e.g. <foobar/>). + *
NOTE: if the parser is not on START_TAG, an exception + * will be thrown. + */ + boolean isEmptyElementTag() throws XmlPullParserException; + + // -------------------------------------------------------------------------- + // START_TAG Attributes retrieval methods + + /** + * Returns the number of attributes of the current start tag, or + * -1 if the current event type is not START_TAG + * + * @see #getAttributeNamespace + * @see #getAttributeName + * @see #getAttributePrefix + * @see #getAttributeValue + */ + int getAttributeCount(); + + /** + * Returns the namespace URI of the attribute + * with the given index (starts from 0). + * Returns an empty string ("") if namespaces are not enabled + * or the attribute has no namespace. + * Throws an IndexOutOfBoundsException if the index is out of range + * or the current event type is not START_TAG. + * + *
NOTE: if FEATURE_REPORT_NAMESPACE_ATTRIBUTES is set + * then namespace attributes (xmlns:ns='...') must be reported + * with namespace + * http://www.w3.org/2000/xmlns/ + * (visit this URL for description!). + * The default namespace attribute (xmlns="...") will be reported with empty namespace. + *
NOTE:The xml prefix is bound as defined in + * Namespaces in XML + * specification to "http://www.w3.org/XML/1998/namespace". + * + * @param zero based index of attribute + * @return attribute namespace, + * empty string ("") is returned if namesapces processing is not enabled or + * namespaces processing is enabled but attribute has no namespace (it has no prefix). + */ + String getAttributeNamespace (int index); + + /** + * Returns the local name of the specified attribute + * if namespaces are enabled or just attribute name if namespaces are disabled. + * Throws an IndexOutOfBoundsException if the index is out of range + * or current event type is not START_TAG. + * + * @param zero based index of attribute + * @return attribute name (null is never returned) + */ + String getAttributeName (int index); + + /** + * Returns the prefix of the specified attribute + * Returns null if the element has no prefix. + * If namespaces are disabled it will always return null. + * Throws an IndexOutOfBoundsException if the index is out of range + * or current event type is not START_TAG. + * + * @param zero based index of attribute + * @return attribute prefix or null if namespaces processing is not enabled. + */ + String getAttributePrefix(int index); + + /** + * Returns the type of the specified attribute + * If parser is non-validating it MUST return CDATA. + * + * @param zero based index of attribute + * @return attribute type (null is never returned) + */ + String getAttributeType(int index); + + /** + * Returns if the specified attribute was not in input was declared in XML. + * If parser is non-validating it MUST always return false. + * This information is part of XML infoset: + * + * @param zero based index of attribute + * @return false if attribute was in input + */ + boolean isAttributeDefault(int index); + + /** + * Returns the given attributes value. + * Throws an IndexOutOfBoundsException if the index is out of range + * or current event type is not START_TAG. + * + *
NOTE: attribute value must be normalized + * (including entity replacement text if PROCESS_DOCDECL is false) as described in + * XML 1.0 section + * 3.3.3 Attribute-Value Normalization + * + * @see #defineEntityReplacementText + * + * @param zero based index of attribute + * @return value of attribute (null is never returned) + */ + String getAttributeValue(int index); + + /** + * Returns the attributes value identified by namespace URI and namespace localName. + * If namespaces are disabled namespace must be null. + * If current event type is not START_TAG then IndexOutOfBoundsException will be thrown. + * + *
NOTE: attribute value must be normalized + * (including entity replacement text if PROCESS_DOCDECL is false) as described in + * XML 1.0 section + * 3.3.3 Attribute-Value Normalization + * + * @see #defineEntityReplacementText + * + * @param namespace Namespace of the attribute if namespaces are enabled otherwise must be null + * @param name If namespaces enabled local name of attribute otherwise just attribute name + * @return value of attribute or null if attribute with given name does not exist + */ + String getAttributeValue(String namespace, + String name); + + // -------------------------------------------------------------------------- + // actual parsing methods + + /** + * Returns the type of the current event (START_TAG, END_TAG, TEXT, etc.) + * + * @see #next() + * @see #nextToken() + */ + int getEventType() + throws XmlPullParserException; + + /** + * Get next parsing event - element content wil be coalesced and only one + * TEXT event must be returned for whole element content + * (comments and processing instructions will be ignored and emtity references + * must be expanded or exception mus be thrown if entity reerence can not be exapnded). + * If element content is empty (content is "") then no TEXT event will be reported. + * + *
NOTE: empty element (such as <tag/>) will be reported + * with two separate events: START_TAG, END_TAG - it must be so to preserve + * parsing equivalency of empty element to <tag></tag>. + * (see isEmptyElementTag ()) + * + * @see #isEmptyElementTag + * @see #START_TAG + * @see #TEXT + * @see #END_TAG + * @see #END_DOCUMENT + */ + + int next() + throws XmlPullParserException, IOException; + + + /** + * This method works similarly to next() but will expose + * additional event types (COMMENT, CDSECT, DOCDECL, ENTITY_REF, PROCESSING_INSTRUCTION, or + * IGNORABLE_WHITESPACE) if they are available in input. + * + *
If special feature + * FEATURE_XML_ROUNDTRIP + * (identified by URI: http://xmlpull.org/v1/doc/features.html#xml-roundtrip) + * is enabled it is possible to do XML document round trip ie. reproduce + * exectly on output the XML input using getText(): + * returned content is always unnormalized (exactly as in input). + * Otherwise returned content is end-of-line normalized as described + * XML 1.0 End-of-Line Handling + * and. Also when this feature is enabled exact content of START_TAG, END_TAG, + * DOCDECL and PROCESSING_INSTRUCTION is available. + * + *
Here is the list of tokens that can be returned from nextToken() + * and what getText() and getTextCharacters() returns:
+ * " titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd" + * [<!ENTITY % active.links "INCLUDE">]"+ *
for input document that contained:
+ * <!DOCTYPE titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd" + * [<!ENTITY % active.links "INCLUDE">]>+ * otherwise if FEATURE_XML_ROUNDTRIP is false and PROCESS_DOCDECL is true + * then what is returned is undefined (it may be even null) + *
NOTE: there is no gurantee that there will only one TEXT or + * IGNORABLE_WHITESPACE event from nextToken() as parser may chose to deliver element content in + * multiple tokens (dividing element content into chunks) + * + *
NOTE: whether returned text of token is end-of-line normalized + * is depending on FEATURE_XML_ROUNDTRIP. + * + *
NOTE: XMLDecl (<?xml ...?>) is not reported but its content + * is available through optional properties (see class description above). + * + * @see #next + * @see #START_TAG + * @see #TEXT + * @see #END_TAG + * @see #END_DOCUMENT + * @see #COMMENT + * @see #DOCDECL + * @see #PROCESSING_INSTRUCTION + * @see #ENTITY_REF + * @see #IGNORABLE_WHITESPACE + */ + int nextToken() + throws XmlPullParserException, IOException; + + //----------------------------------------------------------------------------- + // utility methods to mak XML parsing easier ... + + /** + * Test if the current event is of the given type and if the + * namespace and name do match. null will match any namespace + * and any name. If the test is not passed, an exception is + * thrown. The exception text indicates the parser position, + * the expected event and the current event that is not meeting the + * requirement. + * + *
Essentially it does this + *
+ * if (type != getEventType() + * || (namespace != null && !namespace.equals( getNamespace () ) ) + * || (name != null && !name.equals( getName() ) ) ) + * throw new XmlPullParserException( "expected "+ TYPES[ type ]+getPositionDescription()); + *+ */ + void require(int type, String namespace, String name) + throws XmlPullParserException, IOException; + + /** + * If current event is START_TAG then if next element is TEXT then element content is returned + * or if next event is END_TAG then empty string is returned, otherwise exception is thrown. + * After calling this function successfully parser will be positioned on END_TAG. + * + *
The motivation for this function is to allow to parse consistently both + * empty elements and elements that has non empty content, for example for input:
+ * p.nextTag() + * p.requireEvent(p.START_TAG, "", "tag"); + * String content = p.nextText(); + * p.requireEvent(p.END_TAG, "", "tag"); + *+ * This function together with nextTag make it very easy to parse XML that has + * no mixed content. + * + * + *
Essentially it does this + *
+ * if(getEventType() != START_TAG) { + * throw new XmlPullParserException( + * "parser must be on START_TAG to read next text", this, null); + * } + * int eventType = next(); + * if(eventType == TEXT) { + * String result = getText(); + * eventType = next(); + * if(eventType != END_TAG) { + * throw new XmlPullParserException( + * "event TEXT it must be immediately followed by END_TAG", this, null); + * } + * return result; + * } else if(eventType == END_TAG) { + * return ""; + * } else { + * throw new XmlPullParserException( + * "parser must be on START_TAG or TEXT to read text", this, null); + * } + *+ */ + String nextText() throws XmlPullParserException, IOException; + + /** + * Call next() and return event if it is START_TAG or END_TAG + * otherwise throw an exception. + * It will skip whitespace TEXT before actual tag if any. + * + *
essentially it does this + *
+ * int eventType = next(); + * if(eventType == TEXT && isWhitespace()) { // skip whitespace + * eventType = next(); + * } + * if (eventType != START_TAG && eventType != END_TAG) { + * throw new XmlPullParserException("expected start or end tag", this, null); + * } + * return eventType; + *+ */ + int nextTag() throws XmlPullParserException, IOException; + +} + diff --git a/router/java/src/org/xmlpull/v1/XmlPullParserException.java b/router/java/src/org/xmlpull/v1/XmlPullParserException.java new file mode 100644 index 000000000..0faba7e20 --- /dev/null +++ b/router/java/src/org/xmlpull/v1/XmlPullParserException.java @@ -0,0 +1,80 @@ +/* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- //------100-columns-wide------>|*/ +// for license please see accompanying LICENSE.txt file (available also at http://www.xmlpull.org/) + +package org.xmlpull.v1; + +/** + * This exception is thrown to signal XML Pull Parser related faults. + * + * @author Aleksander Slominski + */ +public class XmlPullParserException extends Exception { + /** + * + */ + private static final long serialVersionUID = 1L; + protected Throwable detail; + protected int row = -1; + protected int column = -1; + + /* public XmlPullParserException() { + }*/ + + public XmlPullParserException(String s) { + super(s); + } + + /* + public XmlPullParserException(String s, Throwable thrwble) { + super(s); + this.detail = thrwble; + } + + public XmlPullParserException(String s, int row, int column) { + super(s); + this.row = row; + this.column = column; + } + */ + + public XmlPullParserException(String msg, XmlPullParser parser, Throwable chain) { + super ((msg == null ? "" : msg+" ") + + (parser == null ? "" : "(position:"+parser.getPositionDescription()+") ") + + (chain == null ? "" : "caused by: "+chain)); + + if (parser != null) { + this.row = parser.getLineNumber(); + this.column = parser.getColumnNumber(); + } + this.detail = chain; + } + + public Throwable getDetail() { return detail; } + // public void setDetail(Throwable cause) { this.detail = cause; } + public int getLineNumber() { return row; } + public int getColumnNumber() { return column; } + + /* + public String getMessage() { + if(detail == null) + return super.getMessage(); + else + return super.getMessage() + "; nested exception is: \n\t" + + detail.getMessage(); + } + */ + + //NOTE: code that prints this and detail is difficult in J2ME + public void printStackTrace() { + if (detail == null) { + super.printStackTrace(); + } else { + synchronized(System.err) { + System.err.println(super.getMessage() + "; nested exception is:"); + detail.printStackTrace(); + } + } + } + +} + diff --git a/router/java/src/org/xmlpull/v1/XmlPullParserFactory.java b/router/java/src/org/xmlpull/v1/XmlPullParserFactory.java new file mode 100644 index 000000000..af6c27adb --- /dev/null +++ b/router/java/src/org/xmlpull/v1/XmlPullParserFactory.java @@ -0,0 +1,356 @@ +/* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- //------100-columns-wide------>|*/ +// for license please see accompanying LICENSE.txt file (available also at http://www.xmlpull.org/) + +package org.xmlpull.v1; + +import java.io.InputStream; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This class is used to create implementations of XML Pull Parser defined in XMPULL V1 API. + * The name of actual factory class will be determined based on several parameters. + * It works similar to JAXP but tailored to work in J2ME environments + * (no access to system properties or file system) so name of parser class factory to use + * and its class used for loading (no class loader - on J2ME no access to context class loaders) + * must be passed explicitly. If no name of parser factory was passed (or is null) + * it will try to find name by searching in CLASSPATH for + * META-INF/services/plugins.JabberLinker.org.xmlpull.v1.XmlPullParserFactory resource that should contain + * a comma separated list of class names of factories or parsers to try (in order from + * left to the right). If none found, it will throw an exception. + * + *
newInstance(property, classLoaderCtx)
+ * where first argument is
+ * System.getProperty(XmlPullParserFactory.PROPERTY_NAME)
+ * and second is Thread.getContextClassLoader().getClass()
.
+ *
+ * @see XmlPullParser
+ *
+ * @author Aleksander Slominski
+ * @author Stefan Haustein
+ */
+
+public class XmlPullParserFactory {
+ /** used as default class to server as context class in newInstance() */
+ final static Class referenceContextClass;
+
+ static {
+ XmlPullParserFactory f = new XmlPullParserFactory();
+ referenceContextClass = f.getClass();
+ }
+
+ /** Name of the system or midlet property that should be used for
+ a system property containing a comma separated list of factory
+ or parser class names (value:
+ plugins.JabberLinker.org.xmlpull.v1.XmlPullParserFactory). */
+
+
+ public static final String PROPERTY_NAME =
+ "plugins.JabberLinker.org.xmlpull.v1.XmlPullParserFactory";
+
+ private static final String RESOURCE_NAME =
+ "/META-INF/services/" + PROPERTY_NAME;
+
+
+ // public static final String DEFAULT_PROPERTY =
+ // "plugins.JabberLinker.org.xmlpull.xpp3.XmlPullParser,org.kxml2.io.KXmlParser";
+
+
+ protected Vector parserClasses;
+ protected String classNamesLocation;
+
+ protected Vector serializerClasses;
+
+
+ // features are kept there
+ protected Hashtable features = new Hashtable();
+
+
+ /**
+ * Protected constructor to be called by factory implementations.
+ */
+
+ protected XmlPullParserFactory() {
+ }
+
+
+
+ /**
+ * Set the features to be set when XML Pull Parser is created by this factory.
+ * NOTE: factory features are not used for XML Serializer. + * + * @param name string with URI identifying feature + * @param state if true feature will be set; if false will be ignored + */ + + public void setFeature(String name, + boolean state) throws XmlPullParserException { + + features.put(name, new Boolean(state)); + } + + + /** + * Return the current value of the feature with given name. + *
NOTE: factory features are not used for XML Serializer.
+ *
+ * @param name The name of feature to be retrieved.
+ * @return The value of named feature.
+ * Unknown features are NOTE: factory features are not used for XML Serializer.
+ *
+ * @return A new instance of a XML Serializer.
+ * @throws XmlPullParserException if a parser cannot be created which satisfies the
+ * requested configuration.
+ */
+
+ public XmlSerializer newSerializer() throws XmlPullParserException {
+
+ if (serializerClasses == null) {
+ throw new XmlPullParserException
+ ("Factory initialization incomplete - has not tried "+classNamesLocation);
+ }
+ if(serializerClasses.size() == 0) {
+ throw new XmlPullParserException
+ ("No valid serializer classes found in "+classNamesLocation);
+ }
+
+ final StringBuilder issues = new StringBuilder ();
+
+ for (int i = 0; i < serializerClasses.size (); i++) {
+ final Class ppClass = (Class) serializerClasses.elementAt (i);
+ try {
+ final XmlSerializer ser = (XmlSerializer) ppClass.newInstance();
+
+ // for (Enumeration e = features.keys (); e.hasMoreElements ();) {
+ // String key = (String) e.nextElement();
+ // Boolean value = (Boolean) features.get(key);
+ // if(value != null && value.booleanValue()) {
+ // ser.setFeature(key, true);
+ // }
+ // }
+ return ser;
+
+ } catch(Exception ex) {
+ issues.append (ppClass.getName () + ": "+ ex.toString ()+"; ");
+ }
+ }
+
+ throw new XmlPullParserException ("could not create serializer: "+issues);
+ }
+
+ /**
+ * Create a new instance of a PullParserFactory that can be used
+ * to create XML pull parsers (see class description for more
+ * details).
+ *
+ * @return a new instance of a PullParserFactory, as returned by newInstance (null, null);
+ */
+ public static XmlPullParserFactory newInstance () throws XmlPullParserException {
+ return newInstance(null, null);
+ }
+
+ public static XmlPullParserFactory newInstance (String classNames, Class context)
+ throws XmlPullParserException {
+
+ if (context == null) {
+ //NOTE: make sure context uses the same class loader as API classes
+ // this is the best we can do without having access to context classloader in J2ME
+ // if API is in the same classloader as implementation then this will work
+ context = referenceContextClass;
+ }
+
+ String classNamesLocation = null;
+
+ if (classNames == null || classNames.length() == 0 || "DEFAULT".equals(classNames)) {
+ try {
+ InputStream is = context.getResourceAsStream (RESOURCE_NAME);
+
+ if (is == null) throw new XmlPullParserException
+ ("resource not found: "+RESOURCE_NAME
+ +" make sure that parser implementing XmlPull API is available");
+ final StringBuilder sb = new StringBuilder();
+
+ while (true) {
+ final int ch = is.read();
+ if (ch < 0) break;
+ else if (ch > ' ')
+ sb.append((char) ch);
+ }
+ is.close ();
+
+ classNames = sb.toString ();
+ }
+ catch (Exception e) {
+ throw new XmlPullParserException (null, null, e);
+ }
+ classNamesLocation = "resource "+RESOURCE_NAME+" that contained '"+classNames+"'";
+ } else {
+ classNamesLocation =
+ "parameter classNames to newInstance() that contained '"+classNames+"'";
+ }
+
+ XmlPullParserFactory factory = null;
+ final Vector parserClasses = new Vector ();
+ final Vector serializerClasses = new Vector ();
+ int pos = 0;
+
+ while (pos < classNames.length ()) {
+ int cut = classNames.indexOf (',', pos);
+
+ if (cut == -1) cut = classNames.length ();
+ final String name = classNames.substring (pos, cut);
+
+ Class candidate = null;
+ Object instance = null;
+
+ try {
+ candidate = Class.forName (name);
+ // necessary because of J2ME .class issue
+ instance = candidate.newInstance ();
+ }
+ catch (Exception e) {}
+
+ if (candidate != null) {
+ boolean recognized = false;
+ if (instance instanceof XmlPullParser) {
+ parserClasses.addElement (candidate);
+ recognized = true;
+ }
+ if (instance instanceof XmlSerializer) {
+ serializerClasses.addElement (candidate);
+ recognized = true;
+ }
+ if (instance instanceof XmlPullParserFactory) {
+ if (factory == null) {
+ factory = (XmlPullParserFactory) instance;
+ }
+ recognized = true;
+ }
+ if (!recognized) {
+ throw new XmlPullParserException ("incompatible class: "+name);
+ }
+ }
+ pos = cut + 1;
+ }
+
+ if (factory == null) {
+ factory = new XmlPullParserFactory ();
+ }
+ factory.parserClasses = parserClasses;
+ factory.serializerClasses = serializerClasses;
+ factory.classNamesLocation = classNamesLocation;
+ return factory;
+ }
+}
+
+
diff --git a/router/java/src/org/xmlpull/v1/XmlSerializer.java b/router/java/src/org/xmlpull/v1/XmlSerializer.java
new file mode 100644
index 000000000..8e85e2f0e
--- /dev/null
+++ b/router/java/src/org/xmlpull/v1/XmlSerializer.java
@@ -0,0 +1,326 @@
+package org.xmlpull.v1;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.Writer;
+
+/**
+ * Define an interface to serialziation of XML Infoset.
+ * This interface abstracts away if serialized XML is XML 1.0 comaptible text or
+ * other formats of XML 1.0 serializations (such as binary XML for example with WBXML).
+ *
+ * PLEASE NOTE: This interface will be part of XmlPull 1.2 API.
+ * It is included as basis for discussion. It may change in any way.
+ *
+ * Exceptions that may be thrown are: IOException or runtime exception
+ * (more runtime exceptions can be thrown but are not declared and as such
+ * have no semantics defined for this interface):
+ * NOTE: writing CDSECT, ENTITY_REF, IGNORABLE_WHITESPACE,
+ * PROCESSING_INSTRUCTION, COMMENT, and DOCDECL in some implementations
+ * may not be supported (for example when serializing to WBXML).
+ * In such case IllegalStateException will be thrown and it is recommened
+ * to use an optional feature to signal that implementation is not
+ * supporting this kind of output.
+ */
+
+public interface XmlSerializer {
+
+ /**
+ * Set feature identified by name (recommended to be URI for uniqueness).
+ * Some well known optional features are defined in
+ *
+ * http://www.xmlpull.org/v1/doc/features.html.
+ *
+ * If feature is not recocgnized or can not be set
+ * then IllegalStateException MUST be thrown.
+ *
+ * @exception IllegalStateException If the feature is not supported or can not be set
+ */
+ void setFeature(String name,
+ boolean state)
+ throws IllegalArgumentException, IllegalStateException;
+
+
+ /**
+ * Return the current value of the feature with given name.
+ * NOTE: unknown properties are always returned as null
+ *
+ * @param name The name of feature to be retrieved.
+ * @return The value of named feature.
+ * @exception IllegalArgumentException if feature string is null
+ */
+ boolean getFeature(String name);
+
+
+ /**
+ * Set the value of a property.
+ * (the property name is recommened to be URI for uniqueness).
+ * Some well known optional properties are defined in
+ *
+ * http://www.xmlpull.org/v1/doc/properties.html.
+ *
+ * If property is not recocgnized or can not be set
+ * then IllegalStateException MUST be thrown.
+ *
+ * @exception IllegalStateException if the property is not supported or can not be set
+ */
+ void setProperty(String name,
+ Object value)
+ throws IllegalArgumentException, IllegalStateException;
+
+ /**
+ * Look up the value of a property.
+ *
+ * The property name is any fully-qualified URI. I
+ * NOTE: unknown properties are WARNING no information about encoding is available!
+ */
+ void setOutput (Writer writer)
+ throws IOException, IllegalArgumentException, IllegalStateException;
+
+ /**
+ * Write <?xml declaration with encoding (if encoding not null)
+ * and standalone flag (if standalone not null)
+ * This method can only be called just after setOutput.
+ */
+ void startDocument (String encoding, Boolean standalone)
+ throws IOException, IllegalArgumentException, IllegalStateException;
+
+ /**
+ * Finish writing. All unclosed start tags will be closed and output
+ * will be flushed. After calling this method no more output can be
+ * serialized until next call to setOutput()
+ */
+ void endDocument ()
+ throws IOException, IllegalArgumentException, IllegalStateException;
+
+ /**
+ * Binds the given prefix to the given namespace.
+ * This call is valid for the next element including child elements.
+ * The prefix and namespace MUST be always declared even if prefix
+ * is not used in element (startTag() or attribute()) - for XML 1.0
+ * it must result in declaring NOTE: this method MUST be called directly before startTag()
+ * and if anything but startTag() or setPrefix() is called next there will be exception.
+ * NOTE: prefixes "xml" and "xmlns" are already bound
+ * and can not be redefined see:
+ * Namespaces in XML Errata.
+ * NOTE: to set default namespace use as prefix empty string.
+ *
+ * @param prefix must be not null (or IllegalArgumentException is thrown)
+ * @param namespace must be not null
+ */
+ void setPrefix (String prefix, String namespace)
+ throws IOException, IllegalArgumentException, IllegalStateException;
+
+ /**
+ * Return namespace that corresponds to given prefix
+ * If there is no prefix bound to this namespace return null
+ * but if generatePrefix is false then return generated prefix.
+ *
+ * NOTE: if the prefix is empty string "" and defualt namespace is bound
+ * to this prefix then empty string ("") is returned.
+ *
+ * NOTE: prefixes "xml" and "xmlns" are already bound
+ * will have values as defined
+ * Namespaces in XML specification
+ */
+ String getPrefix (String namespace, boolean generatePrefix)
+ throws IllegalArgumentException;
+
+ /**
+ * Returns the current depth of the element.
+ * Outside the root element, the depth is 0. The
+ * depth is incremented by 1 when startTag() is called.
+ * The depth is decremented after the call to endTag()
+ * event was observed.
+ *
+ * NOTE: that measn in particaulr that: Background: in kXML endTag had no arguments, and non matching tags were
+ * very difficult to find...
+ * If namespace is null no namespace prefix is printed but just name.
+ * If namespace is empty string then serialzier will make sure that
+ * default empty namespace is declared (in XML 1.0 xmlns='').
+ */
+ XmlSerializer endTag (String namespace, String name)
+ throws IOException, IllegalArgumentException, IllegalStateException;
+
+
+ // /**
+ // * Writes a start tag with the given namespace and name.
+ // * Background: in kXML endTag had no arguments, and non matching tags were
+ // * very difficult to find... NOTE: if there is need to close start tag
+ * (so no more attribute() calls are allowed) but without flushinging output
+ * call method text() with empty string (text("")).
+ *
+ */
+ void flush ()
+ throws IOException;
+
+}
+
From 78075cb3aaf08ad6ef5c9e7ad0796944cc26e7dd Mon Sep 17 00:00:00 2001
From: zzz Limiter Status: Pending bandwidth requests:
+ *
+ *
+ * xmlns:prefix='namespace'
+ * (or xmlns:prefix="namespace"
depending what character is used
+ * to quote attribute value).
+ *
+ *
+ * <!-- outside --> 0
+ * <root> 1
+ * sometext 1
+ * <foobar> 2
+ * </foobar> 2
+ * </root> 1
+ * <!-- outside --> 0
+ *
+ */
+ int getDepth();
+
+ /**
+ * Returns the namespace URI of the current element as set by startTag().
+ *
+ *
+ *
+ *
+ * @return namespace set by startTag() that is currently in scope
+ */
+ String getNamespace ();
+
+ /**
+ * Returns the name of the current element as set by startTag().
+ * It can only be null before first call to startTag()
+ * or when last endTag() is called to close first startTag().
+ *
+ * @return namespace set by startTag() that is currently in scope
+ */
+ String getName();
+
+ /**
+ * Writes a start tag with the given namespace and name.
+ * If there is no prefix defined for the given namespace,
+ * a prefix will be defined automatically.
+ * The explicit prefixes for namespaces can be established by calling setPrefix()
+ * immediately before this method.
+ * If namespace is null no namespace prefix is printed but just name.
+ * If namespace is empty string then serialzier will make sure that
+ * default empty namespace is declared (in XML 1.0 xmlns='')
+ * or throw IllegalStateException if default namespace is already bound
+ * to non-empty string.
+ */
+ XmlSerializer startTag (String namespace, String name)
+ throws IOException, IllegalArgumentException, IllegalStateException;
+
+ /**
+ * Write an attribute. Calls to attribute() MUST follow a call to
+ * startTag() immediately. If there is no prefix defined for the
+ * given namespace, a prefix will be defined automatically.
+ * If namespace is null or empty string
+ * no namespace prefix is printed but just name.
+ */
+ XmlSerializer attribute (String namespace, String name, String value)
+ throws IOException, IllegalArgumentException, IllegalStateException;
+
+ /**
+ * Write end tag. Repetition of namespace and name is just for avoiding errors.
+ *
If there is no prefix defined (prefix == null) for the given namespace,
+ // * a prefix will be defined automatically.
+ // *
If explicit prefixes is passed (prefix != null) then it will be used
+ // *and namespace declared if not already declared or
+ // * throw IllegalStateException the same prefix was already set on this
+ // * element (setPrefix()) and was bound to different namespace.
+ // *
If namespace is null then prefix must be null too or IllegalStateException is thrown.
+ // *
If namespace is null then no namespace prefix is printed but just name.
+ // *
If namespace is empty string then serializer will make sure that
+ // * default empty namespace is declared (in XML 1.0 xmlns='')
+ // * or throw IllegalStateException if default namespace is already bound
+ // * to non-empty string.
+ // */
+ // XmlSerializer startTag (String prefix, String namespace, String name)
+ // throws IOException, IllegalArgumentException, IllegalStateException;
+ //
+ // /**
+ // * Write an attribute. Calls to attribute() MUST follow a call to
+ // * startTag() immediately.
+ // *
If there is no prefix defined (prefix == null) for the given namespace,
+ // * a prefix will be defined automatically.
+ // *
If explicit prefixes is passed (prefix != null) then it will be used
+ // * and namespace declared if not already declared or
+ // * throw IllegalStateException the same prefix was already set on this
+ // * element (setPrefix()) and was bound to different namespace.
+ // *
If namespace is null then prefix must be null too or IllegalStateException is thrown.
+ // *
If namespace is null then no namespace prefix is printed but just name.
+ // *
If namespace is empty string then serializer will make sure that
+ // * default empty namespace is declared (in XML 1.0 xmlns='')
+ // * or throw IllegalStateException if default namespace is already bound
+ // * to non-empty string.
+ // */
+ // XmlSerializer attribute (String prefix, String namespace, String name, String value)
+ // throws IOException, IllegalArgumentException, IllegalStateException;
+ //
+ // /**
+ // * Write end tag. Repetition of namespace, prefix, and name is just for avoiding errors.
+ // *
If namespace or name arguments are different from corresponding startTag call
+ // * then IllegalArgumentException is thrown, if prefix argument is not null and is different
+ // * from corresponding starTag then IllegalArgumentException is thrown.
+ // *
If namespace is null then prefix must be null too or IllegalStateException is thrown.
+ // *
If namespace is null then no namespace prefix is printed but just name.
+ // *
If namespace is empty string then serializer will make sure that
+ // * default empty namespace is declared (in XML 1.0 xmlns='').
+ // *
Limiter status: ").append(getStatus().toString()).append("
\n");
- buf.append("Pending bandwidth requests:");
+ buf.append("
").append(getStatus().toString()).append("");
buf.append("
");
synchronized (_pendingInboundRequests) {
for (int i = 0; i < _pendingInboundRequests.size(); i++) {
@@ -643,7 +643,7 @@ public class FIFOBandwidthLimiter {
buf.append("ms ago
\n"); + buf.append("Router Transport Addresses:
\n"); for (int i = 0; i < _transports.size(); i++) { Transport t = (Transport)_transports.get(i); if (t.getCurrentAddress() != null) @@ -379,6 +379,8 @@ public class TransportManager implements TransportEventListener { } buf.append("\n"); out.write(buf.toString()); + out.write(_upnpManager.renderStatusHTML()); + buf.append("\n"); out.flush(); } } diff --git a/router/java/src/net/i2p/router/transport/UPnP.java b/router/java/src/net/i2p/router/transport/UPnP.java index aef65adc5..61ce5183b 100644 --- a/router/java/src/net/i2p/router/transport/UPnP.java +++ b/router/java/src/net/i2p/router/transport/UPnP.java @@ -108,11 +108,17 @@ public class UPnP extends ControlPoint implements DeviceChangeListener { DetectedIP result = null; final String natAddress = getNATAddress(); + if (natAddress == null || natAddress.length() <= 0) { + _log.warn("No external address returned"); + return null; + } try { InetAddress detectedIP = InetAddress.getByName(natAddress); + short status = DetectedIP.NOT_SUPPORTED; thinksWeAreDoubleNatted = !TransportImpl.isPubliclyRoutable(detectedIP.getAddress()); // If we have forwarded a port AND we don't have a private address + _log.warn("NATAddress: \"" + natAddress + "\" detectedIP: " + detectedIP + " double? " + thinksWeAreDoubleNatted); if((portsForwarded.size() > 1) && (!thinksWeAreDoubleNatted)) status = DetectedIP.FULL_INTERNET; @@ -291,6 +297,7 @@ public class UPnP extends ControlPoint implements DeviceChangeListener { return Integer.valueOf(getIP.getOutputArgumentList().getArgument("NewDownstreamMaxBitRate").getValue()); } +/*** private void listStateTable(Service serv, StringBuilder sb) { ServiceStateTable table = serv.getServiceStateTable(); sb.append(""); @@ -320,6 +327,7 @@ public class UPnP extends ControlPoint implements DeviceChangeListener { sb.append(""); } } +***/ private String toString(String action, String Argument, Service serv) { Action getIP = serv.getAction(action); @@ -333,122 +341,103 @@ public class UPnP extends ControlPoint implements DeviceChangeListener { // TODO: extend it! RTFM private void listSubServices(Device dev, StringBuilder sb) { ServiceList sl = dev.getServiceList(); + if (sl.size() <= 0) + return; + sb.append("
Device : "+dev.getFriendlyName()+" - "+ dev.getDeviceType()+"
");
+ if (prefix == null)
+ sb.append("Device: ");
+ else
+ sb.append("
Found ");
+ listSubDev(null, _router, sb);
+ sb.append("
The current external IP address reported by UPnP is " + getNATAddress());
int downstreamMaxBitRate = getDownstreamMaxBitRate();
int upstreamMaxBitRate = getUpstramMaxBitRate();
if(downstreamMaxBitRate > 0)
- foundInfoboxContent.addChild("p", "Our reported max downstream bit rate is : " + getDownstreamMaxBitRate()+ " bits/sec");
+ sb.append("
UPnP reports the max downstream bit rate is : " + getDownstreamMaxBitRate()+ " bits/sec\n");
if(upstreamMaxBitRate > 0)
- foundInfoboxContent.addChild("p", "Our reported max upstream bit rate is : " + getUpstramMaxBitRate()+ " bits/sec");
+ sb.append("
UPnP reports the max upstream bit rate is : " + getUpstramMaxBitRate()+ " bits/sec\n");
synchronized(lock) {
if(portsToForward != null) {
for(ForwardPort port : portsToForward) {
- if(portsForwarded.contains(port)) {
- foundInfoboxContent.addChild("p", "The "+port.name+" port "+port.portNumber+" / "+port.protocol+" has been forwarded successfully.");
- } else {
- foundInfoboxContent.addChild("p", "The "+port.name+" port "+port.portNumber+" / "+port.protocol+" has not been forwarded.");
- }
+ sb.append("
" + protoToString(port.protocol) + " port " + port.portNumber + " for " + port.name);
+ if(portsForwarded.contains(port))
+ sb.append(" has been forwarded successfully by UPnP.\n");
+ else
+ sb.append(" has not been forwarded UPnP.\n");
}
}
}
- return pageNode.generate();
+ sb.append("
If you can, please poke a hole in your NAT or firewall to allow unsolicited UDP packets to reach
you on your external UDP address. If you can't, I2P now includes supports UDP hole punching
diff --git a/router/java/src/net/i2p/router/RouterVersion.java b/router/java/src/net/i2p/router/RouterVersion.java
index 46331081d..4922b069a 100644
--- a/router/java/src/net/i2p/router/RouterVersion.java
+++ b/router/java/src/net/i2p/router/RouterVersion.java
@@ -20,7 +20,7 @@ public class RouterVersion {
public final static String VERSION = CoreVersion.VERSION;
public final static long BUILD = 5;
/** for example "-test" */
- public final static String EXTRA = "";
+ public final static String EXTRA = "-upnp";
public final static String FULL_VERSION = VERSION + "-" + BUILD + EXTRA;
public static void main(String args[]) {
System.out.println("I2P Router version: " + FULL_VERSION);
diff --git a/router/java/src/net/i2p/router/transport/udp/UDPTransport.java b/router/java/src/net/i2p/router/transport/udp/UDPTransport.java
index 45de86244..69e5190fb 100644
--- a/router/java/src/net/i2p/router/transport/udp/UDPTransport.java
+++ b/router/java/src/net/i2p/router/transport/udp/UDPTransport.java
@@ -99,6 +99,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
public static final String STYLE = "SSU";
public static final String PROP_INTERNAL_PORT = "i2np.udp.internalPort";
+ public static final int DEFAULT_INTERNAL_PORT = 8887;
/** define this to explicitly set an external IP address */
public static final String PROP_EXTERNAL_HOST = "i2np.udp.host";
@@ -215,20 +216,12 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
int port = -1;
if (_externalListenPort <= 0) {
// no explicit external port, so lets try an internal one
- String portStr = _context.getProperty(PROP_INTERNAL_PORT);
- if (portStr != null) {
- try {
- port = Integer.parseInt(portStr);
- } catch (NumberFormatException nfe) {
- if (_log.shouldLog(Log.ERROR))
- _log.error("Invalid port specified [" + portStr + "]");
- }
- }
+ port = _context.getProperty(PROP_INTERNAL_PORT, DEFAULT_INTERNAL_PORT);
if (port <= 0) {
- port = 8887;
+ port = DEFAULT_INTERNAL_PORT;
//port = 1024 + _context.random().nextInt(31*1024);
- if (_log.shouldLog(Log.INFO))
- _log.info("Selecting an arbitrary port to bind to: " + port);
+ //if (_log.shouldLog(Log.INFO))
+ // _log.info("Selecting an arbitrary port to bind to: " + port);
_context.router().setConfigSetting(PROP_INTERNAL_PORT, port+"");
}
// attempt to use it as our external port - this will be overridden by
@@ -1013,14 +1006,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
void rebuildExternalAddress(boolean allowRebuildRouterInfo) {
// if the external port is specified, we want to use that to bind to even
// if we don't know the external host.
- String port = _context.getProperty(PROP_EXTERNAL_PORT);
- if (port != null) {
- try {
- _externalListenPort = Integer.parseInt(port);
- } catch (NumberFormatException nfe) {
- _externalListenPort = -1;
- }
- }
+ _externalListenPort = _context.getProperty(PROP_EXTERNAL_PORT, -1);
if (explicitAddressSpecified()) {
try {
From accf3dbf3fca6100e4f7f5f009aa1f697b55dff8 Mon Sep 17 00:00:00 2001
From: zzz
+ UPnP Configuration:
+ Open firewall port using UPnP:
+ />
+
Note: changing any of these settings will terminate all of your connections and effectively restart your router.
diff --git a/router/java/src/net/i2p/router/transport/TransportManager.java b/router/java/src/net/i2p/router/transport/TransportManager.java index c1b9ed0f4..e0eefe9a5 100644 --- a/router/java/src/net/i2p/router/transport/TransportManager.java +++ b/router/java/src/net/i2p/router/transport/TransportManager.java @@ -41,6 +41,7 @@ public class TransportManager implements TransportEventListener { private final static String PROP_ENABLE_NTCP = "i2np.ntcp.enable"; private final static String DEFAULT_ENABLE_NTCP = "true"; private final static String DEFAULT_ENABLE_UDP = "true"; + public final static String PROP_ENABLE_UPNP = "i2np.upnp.enable"; public TransportManager(RouterContext context) { _context = context; @@ -52,7 +53,8 @@ public class TransportManager implements TransportEventListener { _context.statManager().createRateStat("transport.bidFailNoTransports", "Could not attempt to bid on message, as none of the transports could attempt it", "Transport", new long[] { 60*1000, 10*60*1000, 60*60*1000 }); _context.statManager().createRateStat("transport.bidFailAllTransports", "Could not attempt to bid on message, as all of the transports had failed", "Transport", new long[] { 60*1000, 10*60*1000, 60*60*1000 }); _transports = new ArrayList(); - _upnpManager = new UPnPManager(context); + if (Boolean.valueOf(_context.getProperty(PROP_ENABLE_UPNP)).booleanValue()) + _upnpManager = new UPnPManager(context); } public void addTransport(Transport transport) { @@ -93,7 +95,8 @@ public class TransportManager implements TransportEventListener { } public void startListening() { - _upnpManager.start(); + if (_upnpManager != null) + _upnpManager.start(); configTransports(); _log.debug("Starting up the transport manager"); for (int i = 0; i < _transports.size(); i++) { @@ -112,7 +115,8 @@ public class TransportManager implements TransportEventListener { } public void stopListening() { - _upnpManager.stop(); + if (_upnpManager != null) + _upnpManager.stop(); for (int i = 0; i < _transports.size(); i++) { ((Transport)_transports.get(i)).stopListening(); } @@ -359,7 +363,8 @@ public class TransportManager implements TransportEventListener { } public void transportAddressChanged() { - _upnpManager.update(getAddresses()); + if (_upnpManager != null) + _upnpManager.update(getAddresses()); } public List getMostRecentErrorMessages() { @@ -392,7 +397,8 @@ public class TransportManager implements TransportEventListener { } buf.append("\n"); out.write(buf.toString()); - out.write(_upnpManager.renderStatusHTML()); + if (_upnpManager != null) + out.write(_upnpManager.renderStatusHTML()); buf.append("\n"); out.flush(); } From fc10031ff010c7d0de44cb01add263f7318b9d02 Mon Sep 17 00:00:00 2001 From: zzz
Inbound TCP connection configuration:
- Externally reachable hostname or IP address:
+ Externally reachable hostname or IP address:
+ />
+ Disable
+ />
+ Use IP address detected by SSU
+ (currently
+ />
+ Specify hostname or IP:
" />
(dyndns and the like are fine)
- OR use IP address detected by SSU
- (currently
- Externally reachable TCP port:
+ Externally reachable TCP port:
+ />
+ Disable
+ />
+ Use the same port configured for SSU
+ (currently
+ />
+ Specify Port:
" />
- OR use the same port configured for SSU
- (currently
A hostname entered here will be published in the network database.
It is not private.
Also, do not enter a private IP address like 127.0.0.1 or 192.168.1.1.
From 35b5eb74f6df3883cf4e988809151491bc6e8fd2 Mon Sep 17 00:00:00 2001
From: zzz If you can, please poke a hole in your NAT or firewall to allow unsolicited UDP packets to reach
you on your external UDP address. If you can't, I2P now includes supports UDP hole punching
with "SSU introductions" - peers who will relay a request from someone you don't know to your
router for your router so that you can make an outbound connection to them. I2P will use these
introductions automatically if it detects that the port is not forwarded (as shown by
- the Status: Firewalled line), or you can manually require them here.
+ the Reachability: Firewalled line), or you can manually require them here.
Users behind symmetric NATs, such as OpenBSD's pf, are not currently supported.
@@ -88,18 +117,18 @@
Disable
Externally reachable TCP port:
Current External UDP address: If you can, please poke a hole in your NAT or firewall to allow unsolicited UDP packets to reach
+ If you can, please poke a hole in your NAT or firewall to allow unsolicited UDP packets to reach
you on your external UDP address. If you can't, I2P now includes supports UDP hole punching
with "SSU introductions" - peers who will relay a request from someone you don't know to your
router for your router so that you can make an outbound connection to them. I2P will use these
diff --git a/apps/routerconsole/jsp/verifyupdate.jsp b/apps/routerconsole/jsp/verifyupdate.jsp
deleted file mode 100644
index 2d13d3508..000000000
--- a/apps/routerconsole/jsp/verifyupdate.jsp
+++ /dev/null
@@ -1,12 +0,0 @@
-<%@page contentType="text/html" %>
-
-
-
Externally reachable TCP port:
Inbound TCP connection configuration:
+ UPnP Configuration:
+ IP Configuration:
+ UDP Configuration:
+
Current External UDP address: If you can, please poke a hole in your NAT or firewall to allow unsolicited UDP packets to reach
you on your external UDP address. If you can't, I2P now includes supports UDP hole punching
@@ -111,8 +118,8 @@
the Reachability: Firewalled line), or you can manually require them here.
Users behind symmetric NATs, such as OpenBSD's pf, are not currently supported.
- Inbound TCP connection configuration:
+ Inbound TCP Configuration:
+
Externally reachable TCP port: A hostname entered here will be published in the network database.
- It is not private.
+ Hostnames entered here will be published in the network database.
+ They are not private.
Also, do not enter a private IP address like 127.0.0.1 or 192.168.1.1.
You do not need to allow inbound TCP connections - outbound connections work with no
@@ -142,11 +149,6 @@
in your NAT or firewall for unsolicited TCP connections. If you specify the wrong IP address or
hostname, or do not properly configure your NAT or firewall, your network performance will degrade
substantially. When in doubt, leave the hostname and port number blank.
- UPnP Configuration: Note: changing any of these settings will terminate all of your connections and effectively
restart your router.
+
<% int share = nethelper.getShareBandwidth();
if (share < 12) {
out.print("NOTE: You have configured I2P to share only " + share + "KBps. ");
@@ -54,7 +62,7 @@
out.print("The higher the share bandwidth the more you improve your anonymity and help the network.
+
- Inbound TCP Configuration:
Externally reachable TCP port: Hostnames entered here will be published in the network database.
They are not private.
Also, do not enter a private IP address like 127.0.0.1 or 192.168.1.1.
diff --git a/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java b/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java
index ce8c6fb29..871c9eb4c 100644
--- a/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java
+++ b/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java
@@ -27,6 +27,7 @@ import net.i2p.router.RouterContext;
import net.i2p.router.transport.ntcp.NTCPAddress;
import net.i2p.router.transport.ntcp.NTCPTransport;
import net.i2p.router.transport.udp.UDPAddress;
+import net.i2p.router.transport.udp.UDPTransport;
import net.i2p.util.Log;
public class CommSystemFacadeImpl extends CommSystemFacade {
@@ -151,8 +152,8 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
@Override
public short getReachabilityStatus() {
- if (_manager == null) return CommSystemFacade.STATUS_UNKNOWN;
- if (_context.router().isHidden()) return CommSystemFacade.STATUS_OK;
+ if (_manager == null) return STATUS_UNKNOWN;
+ if (_context.router().isHidden()) return STATUS_OK;
return _manager.getReachabilityStatus();
}
@Override
@@ -303,10 +304,14 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
String name = _context.getProperty(PROP_I2NP_NTCP_HOSTNAME);
if (name != null && name.length() > 0)
enabled = "false";
+ Transport udp = _manager.getTransport(UDPTransport.STYLE);
+ short status = STATUS_UNKNOWN;
+ if (udp != null)
+ status = udp.getReachabilityStatus();
if (_log.shouldLog(Log.INFO))
- _log.info("old: " + ohost + " config: " + name + " auto: " + enabled + " status: " + getReachabilityStatus());
+ _log.info("old: " + ohost + " config: " + name + " auto: " + enabled + " status: " + status);
if (enabled.equalsIgnoreCase("always") ||
- (enabled.equalsIgnoreCase("true") && getReachabilityStatus() == CommSystemFacade.STATUS_OK)) {
+ (enabled.equalsIgnoreCase("true") && status == STATUS_OK)) {
String nhost = UDPProps.getProperty(UDPAddress.PROP_HOST);
if (_log.shouldLog(Log.INFO))
_log.info("old: " + ohost + " config: " + name + " new: " + nhost);
diff --git a/router/java/src/net/i2p/router/transport/TransportManager.java b/router/java/src/net/i2p/router/transport/TransportManager.java
index 40b23e062..291e2f6c1 100644
--- a/router/java/src/net/i2p/router/transport/TransportManager.java
+++ b/router/java/src/net/i2p/router/transport/TransportManager.java
@@ -40,10 +40,10 @@ public class TransportManager implements TransportEventListener {
private RouterContext _context;
private UPnPManager _upnpManager;
- private final static String PROP_ENABLE_UDP = "i2np.udp.enable";
- private final static String PROP_ENABLE_NTCP = "i2np.ntcp.enable";
- private final static String DEFAULT_ENABLE_NTCP = "true";
- private final static String DEFAULT_ENABLE_UDP = "true";
+ public final static String PROP_ENABLE_UDP = "i2np.udp.enable";
+ public final static String PROP_ENABLE_NTCP = "i2np.ntcp.enable";
+ public final static String DEFAULT_ENABLE_NTCP = "true";
+ public final static String DEFAULT_ENABLE_UDP = "true";
/** default true */
public final static String PROP_ENABLE_UPNP = "i2np.upnp.enable";
diff --git a/router/java/src/net/i2p/router/transport/udp/UDPTransport.java b/router/java/src/net/i2p/router/transport/udp/UDPTransport.java
index ee9c7d9b7..720eaed46 100644
--- a/router/java/src/net/i2p/router/transport/udp/UDPTransport.java
+++ b/router/java/src/net/i2p/router/transport/udp/UDPTransport.java
@@ -100,6 +100,8 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
public static final String STYLE = "SSU";
public static final String PROP_INTERNAL_PORT = "i2np.udp.internalPort";
public static final int DEFAULT_INTERNAL_PORT = 8887;
+ /** since fixed port defaults to true, this doesnt do anything at the moment.
+ * We should have an exception if it matches the existing low port. */
private static final int MIN_EXTERNAL_PORT = 1024;
/** define this to explicitly set an external IP address */
@@ -386,7 +388,8 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
* @param ourPort >= 1024
*/
void externalAddressReceived(Hash from, byte ourIP[], int ourPort) {
- boolean isValid = isValid(ourIP) && ourPort >= MIN_EXTERNAL_PORT;
+ boolean isValid = isValid(ourIP) &&
+ (ourPort >= MIN_EXTERNAL_PORT || ourPort == _externalListenPort || _externalListenPort <= 0);
boolean explicitSpecified = explicitAddressSpecified();
boolean inboundRecent = _lastInboundReceivedOn + ALLOW_IP_CHANGE_INTERVAL > System.currentTimeMillis();
if (_log.shouldLog(Log.INFO))
@@ -422,6 +425,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
* @param ourPort >= 1024 or 0 for no change
*/
private boolean changeAddress(byte ourIP[], int ourPort) {
+ /** this defaults to true, which means we never change our external port based on what somebody tells us */
boolean fixedPort = getIsPortFixed();
boolean updated = false;
boolean fireTest = false;
@@ -437,9 +441,10 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
_log.info("Trying to change our external address...");
try {
_externalListenHost = InetAddress.getByAddress(ourIP);
+ // fixed port defaults to true so we never do this
if (ourPort >= MIN_EXTERNAL_PORT && !fixedPort)
_externalListenPort = ourPort;
- if (_externalListenPort >= MIN_EXTERNAL_PORT) {
+ if (_externalListenPort > 0) {
rebuildExternalAddress();
replaceAddress(_externalAddress);
updated = true;
@@ -1171,12 +1176,18 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
}
public boolean introducersRequired() {
+ /******************
+ * Don't do this anymore, as we are removing the checkbox from the UI,
+ * and we rarely if ever see the problem of false negatives for firewall detection -
+ * it's usually false positives.
+ ******************
String forceIntroducers = _context.getProperty(PROP_FORCE_INTRODUCERS);
if ( (forceIntroducers != null) && (Boolean.valueOf(forceIntroducers).booleanValue()) ) {
if (_log.shouldLog(Log.INFO))
_log.info("Force introducers specified");
return true;
}
+ *******************/
short status = getReachabilityStatus();
switch (status) {
case CommSystemFacade.STATUS_REJECT_UNSOLICITED:
@@ -1194,6 +1205,7 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
}
}
+ /** default true */
private boolean allowDirectUDP() {
String allowDirect = _context.getProperty(PROP_ALLOW_DIRECT);
return ( (allowDirect == null) || (Boolean.valueOf(allowDirect).booleanValue()) );
From ee7e70b98a792bc404f4f4b2d6db4d2bacf8dd12 Mon Sep 17 00:00:00 2001
From: zzz
+ I2P will work best if you configure your rates to match the speed of your internet connection.
+
+ The default settings will work for most people. There is help below.
+
UPnP Configuration:
UDP Configuration:
Externally reachable TCP port:
UPnP Configuration:
IP Configuration:
@@ -155,30 +155,45 @@
If you can, please poke a hole in your NAT or firewall to allow unsolicited UDP packets to reach
- you on your external UDP address. If you can't, I2P now includes supports UDP hole punching
- with "SSU introductions" - peers who will relay a request from someone you don't know to your
- router for your router so that you can make an outbound connection to them. I2P will use these
- introductions automatically if it detects that the port is not forwarded (as shown by
- the Reachability: Firewalled line).
- Users behind symmetric NATs, such as OpenBSD's pf, are not currently supported.
+ While I2P will work fine behind most firewalls, your speeds and network integration will generally improve
+ if the I2P port (generally 8887) is forwarded for both UDP and TCP.
+
+ If you can, please poke a hole in your firewall to allow unsolicited UDP and TCP packets to reach
+ you. If you can't, I2P supports UPnP (Universal Plug and Play) and UDP hole punching
+ with "SSU introductions" to relay traffic. Most of the options above are for special situations,
+ for example where UPnP does not work correctly, or a firewall not under your control is doing
+ harm. Certain firewalls such as symmetric NATs may not work well with I2P.
+ Hostnames entered here will be published in the network database.
+
+ UPnP is used to communicate with Internet Gateway Devices (IGDs) to detect the external IP address
+ and forward ports.
+ UPnP support is beta, and may not work for any number of reasons:
+ Hostnames entered above will be published in the network database.
They are not private.
Also, do not enter a private IP address like 127.0.0.1 or 192.168.1.1.
- You do not need to allow inbound TCP connections - outbound connections work with no
- configuration. However, if you want to receive inbound TCP connections, you must poke a hole
- in your NAT or firewall for unsolicited TCP connections. If you specify the wrong IP address or
+ If you specify the wrong IP address or
hostname, or do not properly configure your NAT or firewall, your network performance will degrade
- substantially. When in doubt, leave the hostname and port number blank.
- While I2P will work adequately behind a firewall, your speeds and network integration will generally improve
- if you open up your port (generally 8887) to both UDP and TCP, and enable inbound TCP above.
+ While I2P will work fine behind most firewalls, your speeds and network integration will generally improve
+ if the I2P port (generally 8887) to both UDP and TCP.
If you think you have opened up your firewall and I2P still thinks you are firewalled, remember
that you may have multiple firewalls, for example both software packages and external hardware routers.
If there is an error, the logs may also help diagnose the problem.
diff --git a/router/java/src/net/i2p/router/transport/TransportManager.java b/router/java/src/net/i2p/router/transport/TransportManager.java
index 291e2f6c1..aa66ae068 100644
--- a/router/java/src/net/i2p/router/transport/TransportManager.java
+++ b/router/java/src/net/i2p/router/transport/TransportManager.java
@@ -131,7 +131,12 @@ public class TransportManager implements TransportEventListener {
}
public void startListening() {
- if (_upnpManager != null)
+ // For now, only start UPnP if we have no publicly-routable addresses
+ // so we don't open the listener ports to the world.
+ // Maybe we need a config option to force on? Probably not.
+ // What firewall supports UPnP and is configured with a public address on the LAN side?
+ // Unlikely.
+ if (_upnpManager != null && Addresses.getAnyAddress() == null)
_upnpManager.start();
configTransports();
_log.debug("Starting up the transport manager");
From aa2f9e34c012ba7d2447c851597ea7c368b941ce Mon Sep 17 00:00:00 2001
From: zzz
-->
UDP Configuration:
+ Externally reachable hostname or IP address:
+ />
+ Use SSU detection only
+ />
+ Use local public address if available, then UPnP detection, then SSU detection
+ />
+ Use local public address if available, then SSU detection
+ />
+ Use UPnP detection if available, then SSU detection
+ />
+ Specify hostname or IP:
+ " />
+ <% String[] ips = nethelper.getAddresses();
+ if (ips.length > 0) {
+ out.print(" or \n");
+ }
+ %>
+
+ />
+ Hidden mode - do not publish IP(not recommended)
Internal UDP port:
" />
- External UDP address:
- Require SSU introductions?
- />
+ />
+ Require SSU introductions
+ (Enable if you cannot open your firewall)
+ Current External UDP address:
/>
Use IP address detected by SSU
- (currently
+ (currently
/>
Specify hostname or IP:
" />
- (dyndns and the like are fine)
+ (dyndns and the like are fine)
/>
Disable
/>
Use the same port configured for SSU
- (currently
+ (currently
/>
Specify Port:
" />
diff --git a/router/java/src/net/i2p/router/transport/Addresses.java b/router/java/src/net/i2p/router/transport/Addresses.java
new file mode 100644
index 000000000..cd82a9086
--- /dev/null
+++ b/router/java/src/net/i2p/router/transport/Addresses.java
@@ -0,0 +1,80 @@
+package net.i2p.router.transport;
+
+/*
+ * public domain
+ */
+
+import java.net.InetAddress;
+import java.net.Inet4Address;
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.net.UnknownHostException;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+
+
+/**
+ * Get the local addresses
+ *
+ * @author zzz
+ */
+public class Addresses {
+
+ /** return the first non-local address it finds, or null */
+ public static String getAnyAddress() {
+ String[] a = getAddresses();
+ if (a.length > 0)
+ return a[0];
+ return null;
+ }
+
+ /**
+ * Return an array of all addresses, excluding
+ * IPv6, local, broadcast, multicast, etc.
+ */
+ public static String[] getAddresses() {
+ Set
/>
Require SSU introductions
- (Enable if you cannot open your firewall)
+ (Enable if you cannot open your firewall)
+
-
- />
- Disable
/>
Use the same port configured for SSU
(currently
diff --git a/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java b/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java
index 9060ede84..fa62fdc31 100644
--- a/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java
+++ b/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java
@@ -193,6 +193,9 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
public final static String PROP_I2NP_NTCP_AUTO_PORT = "i2np.ntcp.autoport";
public final static String PROP_I2NP_NTCP_AUTO_IP = "i2np.ntcp.autoip";
+ /**
+ * This should really be moved to ntcp/NTCPTransport.java, why is it here?
+ */
public static RouterAddress createNTCPAddress(RouterContext ctx) {
if (!TransportManager.enableNTCP(ctx)) return null;
RouterAddress addr = new RouterAddress();
@@ -236,6 +239,7 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
/**
* UDP changed addresses, tell NTCP and restart
+ * This should really be moved to ntcp/NTCPTransport.java, why is it here?
*/
@Override
public void notifyReplaceAddress(RouterAddress UDPAddr) {
@@ -249,7 +253,8 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
return;
Properties newProps;
RouterAddress oldAddr = t.getCurrentAddress();
- //_log.warn("Changing NTCP Address? was " + oldAddr);
+ if (_log.shouldLog(Log.INFO))
+ _log.info("Changing NTCP Address? was " + oldAddr);
RouterAddress newAddr = oldAddr;
if (newAddr == null) {
newAddr = new RouterAddress();
@@ -264,23 +269,27 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
}
boolean changed = false;
+ // old behavior (<= 0.7.3): auto-port defaults to false, and true trumps explicit setting
+ // new behavior (>= 0.7.4): auto-port defaults to true, but explicit setting trumps auto
String oport = newProps.getProperty(NTCPAddress.PROP_PORT);
- String enabled = _context.getProperty(PROP_I2NP_NTCP_AUTO_PORT, "false");
- if ( (enabled != null) && ("true".equalsIgnoreCase(enabled)) ) {
- String nport = UDPProps.getProperty(UDPAddress.PROP_PORT);
- if (nport == null || nport.length() <= 0)
- return;
- if (oport == null || ! oport.equals(nport)) {
- newProps.setProperty(NTCPAddress.PROP_PORT, nport);
- changed = true;
- }
- } else if (oport == null || oport.length() <= 0) {
+ String nport = null;
+ String cport = _context.getProperty(PROP_I2NP_NTCP_PORT);
+ if (cport != null && cport.length() > 0) {
+ nport = cport;
+ } else if (Boolean.valueOf(_context.getProperty(PROP_I2NP_NTCP_AUTO_PORT, "true")).booleanValue()) {
+ nport = UDPProps.getProperty(UDPAddress.PROP_PORT);
+ }
+ if (_log.shouldLog(Log.INFO))
+ _log.info("old: " + oport + " config: " + cport + " new: " + nport);
+ if (nport == null || nport.length() <= 0)
return;
+ if (oport == null || ! oport.equals(nport)) {
+ newProps.setProperty(NTCPAddress.PROP_PORT, nport);
+ changed = true;
}
String ohost = newProps.getProperty(NTCPAddress.PROP_HOST);
- enabled = _context.getProperty(PROP_I2NP_NTCP_AUTO_IP, "false");
- if ( (enabled != null) && ("true".equalsIgnoreCase(enabled)) ) {
+ if (Boolean.valueOf(_context.getProperty(PROP_I2NP_NTCP_AUTO_IP)).booleanValue()) {
String nhost = UDPProps.getProperty(UDPAddress.PROP_HOST);
if (nhost == null || nhost.length() <= 0)
return;
@@ -293,12 +302,16 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
}
if (!changed) {
- //_log.warn("No change to NTCP Address");
+ _log.warn("No change to NTCP Address");
return;
}
// stopListening stops the pumper, readers, and writers, so required even if
// oldAddr == null since startListening starts them all again
+ //
+ // really need to fix this so that we can change or create an inbound address
+ // without tearing down everything
+ //
_log.warn("Halting NTCP to change address");
t.stopListening();
newAddr.setOptions(newProps);
From b21e0112034d5c63f1ef39681427f5ff695ed4f3 Mon Sep 17 00:00:00 2001
From: zzz
Externally reachable hostname or IP address:
- />
- Disable
- />
- Use IP address detected by SSU
+ />
+ Disable (Firewalled)
+ />
+ Use IP address detected by SSU (Not firewalled)
(currently
- />
+ />
+ Use IP address detected by SSU, only if we do not appear to be firewalled
+ />
Specify hostname or IP:
" />
(dyndns and the like are fine)
diff --git a/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java b/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java
index fa62fdc31..ce8c6fb29 100644
--- a/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java
+++ b/router/java/src/net/i2p/router/transport/CommSystemFacadeImpl.java
@@ -269,6 +269,8 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
}
boolean changed = false;
+
+ // Auto Port Setting
// old behavior (<= 0.7.3): auto-port defaults to false, and true trumps explicit setting
// new behavior (>= 0.7.4): auto-port defaults to true, but explicit setting trumps auto
String oport = newProps.getProperty(NTCPAddress.PROP_PORT);
@@ -288,9 +290,26 @@ public class CommSystemFacadeImpl extends CommSystemFacade {
changed = true;
}
+ // Auto IP Setting
+ // old behavior (<= 0.7.3): auto-ip defaults to false, and trumps configured hostname,
+ // and ignores reachability status - leading to
+ // "firewalled with inbound TCP enabled" warnings.
+ // new behavior (>= 0.7.4): auto-ip defaults to true, and explicit setting trumps auto,
+ // and only takes effect if reachability is OK.
+ // And new "always" setting ignores reachability status, like
+ // "true" was in 0.7.3
String ohost = newProps.getProperty(NTCPAddress.PROP_HOST);
- if (Boolean.valueOf(_context.getProperty(PROP_I2NP_NTCP_AUTO_IP)).booleanValue()) {
+ String enabled = _context.getProperty(PROP_I2NP_NTCP_AUTO_IP, "true");
+ String name = _context.getProperty(PROP_I2NP_NTCP_HOSTNAME);
+ if (name != null && name.length() > 0)
+ enabled = "false";
+ if (_log.shouldLog(Log.INFO))
+ _log.info("old: " + ohost + " config: " + name + " auto: " + enabled + " status: " + getReachabilityStatus());
+ if (enabled.equalsIgnoreCase("always") ||
+ (enabled.equalsIgnoreCase("true") && getReachabilityStatus() == CommSystemFacade.STATUS_OK)) {
String nhost = UDPProps.getProperty(UDPAddress.PROP_HOST);
+ if (_log.shouldLog(Log.INFO))
+ _log.info("old: " + ohost + " config: " + name + " new: " + nhost);
if (nhost == null || nhost.length() <= 0)
return;
if (ohost == null || ! ohost.equalsIgnoreCase(nhost)) {
diff --git a/router/java/src/net/i2p/router/transport/udp/UDPTransport.java b/router/java/src/net/i2p/router/transport/udp/UDPTransport.java
index c9e4bc538..a43213a9c 100644
--- a/router/java/src/net/i2p/router/transport/udp/UDPTransport.java
+++ b/router/java/src/net/i2p/router/transport/udp/UDPTransport.java
@@ -2102,7 +2102,10 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
if ( (status != old) && (status != CommSystemFacade.STATUS_UNKNOWN) ) {
if (_log.shouldLog(Log.INFO))
_log.info("Old status: " + old + " New status: " + status + " from: ", new Exception("traceback"));
- if (needsRebuild())
+ // Always rebuild when the status changes, even if our address hasn't changed,
+ // as rebuildExternalAddress() calls replaceAddress() which calls CSFI.notifyReplaceAddress()
+ // which will start up NTCP inbound when we transition to OK.
+ // if (needsRebuild())
rebuildExternalAddress();
}
}
From 79a963fcab6ab7a7f0466d6b95085c0c26c2e84e Mon Sep 17 00:00:00 2001
From: zzz
-->
- UDP Configuration:
+
+ />
+ Enable UPnP to open firewall ports
+
Externally reachable hostname or IP address:
- />
- Use SSU detection only
- />
+ />
Use local public address if available, then UPnP detection, then SSU detection
- />
+ />
Use local public address if available, then SSU detection
- />
+ />
Use UPnP detection if available, then SSU detection
- />
+ />
+ Use SSU detection only
+ />
Specify hostname or IP:
- " />
+ " />
<% String[] ips = nethelper.getAddresses();
if (ips.length > 0) {
- out.print(" or
Internal UDP port:
" />
/>
Require SSU introductions
(Enable if you cannot open your firewall)
-
+
Externally reachable hostname or IP address:
/>
Disable (Firewalled)
@@ -125,7 +132,7 @@
Specify hostname or IP:
" />
(dyndns and the like are fine)
-
/>
Use the same port configured for SSU
@@ -133,8 +140,8 @@
/>
Specify Port:
" />
-
- Open firewall port using UPnP:
- />
-
- Inbound rate:
- " /> KBps
+
+
+ " /> KBps
+ In (
+
+ " /> KBps
+ Out (
+
+ (
+
");
}
%>
-
+ TCP Configuration:
Externally reachable hostname or IP address:
/>
Use auto-detected IP address
@@ -128,11 +130,12 @@
/>
Always use auto-detected IP address (Not firewalled)
/>
- Disable (Firewalled)
+ Disable inbound (Firewalled)
/>
Specify hostname or IP:
- " />
-
+ " />
+ />
+ Completely disable (select only if behind a firewall that throttles or blocks outbound TCP - restart required)
/>
@@ -152,9 +155,11 @@
with "SSU introductions" - peers who will relay a request from someone you don't know to your
router for your router so that you can make an outbound connection to them. I2P will use these
introductions automatically if it detects that the port is not forwarded (as shown by
- the Reachability: Firewalled line), or you can manually require them here.
+ the Reachability: Firewalled line).
Users behind symmetric NATs, such as OpenBSD's pf, are not currently supported.
+ Bandwidth limiter
" /> KBps
In (
@@ -75,7 +77,10 @@
test.rtt and related stats.
-->
+ IP and Transport Configuration
/>
Enable UPnP to open firewall ports UPnP status
@@ -108,7 +113,7 @@
%>
/>
- Hidden mode - do not publish IP(not recommended; change restarts router)
+ Hidden mode - do not publish IP(prevents participating traffic; change restarts router)
UDP port:
@@ -135,7 +140,7 @@
Specify hostname or IP:
" />
/>
- Completely disable (select only if behind a firewall that throttles or blocks outbound TCP - restart required)
+ Completely disable (select only if behind a firewall that throttles or blocks outbound TCP - change requires restart)
/>
diff --git a/apps/routerconsole/jsp/confignav.jsp b/apps/routerconsole/jsp/confignav.jsp
index 851ab79b5..ec1e7f5c1 100644
--- a/apps/routerconsole/jsp/confignav.jsp
+++ b/apps/routerconsole/jsp/confignav.jsp
@@ -1,3 +1,26 @@
+
+<% if (request.getRequestURI().indexOf("config.jsp") != -1) {
+ %>Network<% }
+ else if (request.getRequestURI().indexOf("configservice.jsp") != -1) {
+ %>Service<% }
+ else if (request.getRequestURI().indexOf("configupdate.jsp") != -1) {
+ %>Update<% }
+ else if (request.getRequestURI().indexOf("configtunnels.jsp") != -1) {
+ %>Tunnels<% }
+ else if (request.getRequestURI().indexOf("configclients.jsp") != -1) {
+ %>Clients<% }
+ else if (request.getRequestURI().indexOf("configpeer.jsp") != -1) {
+ %>Peers<% }
+ else if (request.getRequestURI().indexOf("configkeyring.jsp") != -1) {
+ %>Keyring<% }
+ else if (request.getRequestURI().indexOf("configlogging.jsp") != -1) {
+ %>Logging<% }
+ else if (request.getRequestURI().indexOf("configstats.jsp") != -1) {
+ %>Stats<% }
+ else if (request.getRequestURI().indexOf("configadvanced.jsp") != -1) {
+ %>Advanced<% }%>
+Configuration
<% if (request.getRequestURI().indexOf("config.jsp") != -1) {
%>Network | <% } else { %>Network | <% }
if (request.getRequestURI().indexOf("configservice.jsp") != -1) {
@@ -18,3 +41,5 @@
%>Stats | <% } else { %>Stats | <% }
if (request.getRequestURI().indexOf("configadvanced.jsp") != -1) {
%>Advanced<% } else { %>Advanced<% } %>
+
From 47fc3b0d0bae81901e683a5ae0eeb23240ff8a97 Mon Sep 17 00:00:00 2001
From: zzz
/>
- Enable UPnP to open firewall ports UPnP status
+ Enable UPnP to open firewall ports - UPnP status
Externally reachable hostname or IP address:
@@ -134,11 +134,11 @@
if we are not firewalled
/>
Always use auto-detected IP address (Not firewalled)
- />
- Disable inbound (Firewalled)
/>
Specify hostname or IP:
" />
+ />
+ Disable inbound (Firewalled)
/>
Completely disable (select only if behind a firewall that throttles or blocks outbound TCP - change requires restart)
Configuration Help:
-
+
+ Reviewing the UPnP status may help.
+ UPnP may be enabled or disabled above, but a change requires a router restart to take effect.
+
Reachability Help:
idle");
+ buf.append(" dir/intro idle");
appendSortLinks(buf, urlBase, sortFlags, "Sort by idle inbound", FLAG_IDLE_IN);
buf.append("/");
appendSortLinks(buf, urlBase, sortFlags, "Sort by idle outbound", FLAG_IDLE_OUT);
@@ -1809,32 +1813,11 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
buf.append(name);
buf.append("\">");
buf.append(name);
-/*
- buf.append("@");
- byte ip[] = peer.getRemoteIP();
- for (int j = 0; j < ip.length; j++) {
- int num = ip[j] & 0xFF;
- if (num < 10)
- buf.append("00");
- else if (num < 100)
- buf.append("0");
- buf.append(num);
- if (j + 1 < ip.length)
- buf.append('.');
- }
- buf.append(':');
- int port = peer.getRemotePort();
- if (port < 10)
- buf.append("0000");
- else if (port < 100)
- buf.append("000");
- else if (port < 1000)
- buf.append("00");
- else if (port < 10000)
- buf.append("0");
- buf.append(port);
-*/
- buf.append(" ");
+ buf.append("");
+ //byte ip[] = peer.getRemoteIP();
+ //if (ip != null)
+ // buf.append(' ').append(_context.blocklist().toStr(ip));
+ buf.append(" ");
if (peer.isInbound())
buf.append("in ");
else
@@ -1990,8 +1973,8 @@ public class UDPTransport extends TransportImpl implements TimedWeightedPriority
numPeers++;
}
- buf.append(" \n");
- buf.append(" Total ");
+ buf.append(" \n");
+ buf.append(" Total ");
buf.append(" ");
buf.append(formatKBps(bpsIn)).append("/").append(formatKBps(bpsOut));
buf.append("KBps ");