Search in sources :

Example 66 with DataFormatException

use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.

the class InboundEstablishState method buildIdentity.

/**
 *  Construct Alice's RouterIdentity.
 *  Must have received all fragments.
 *  Sets _receivedUnconfirmedIdentity, unless invalid.
 *
 *  Caller must synch on this.
 *
 *  @since 0.9.16 was in verifyIdentity()
 */
private void buildIdentity() {
    if (_receivedUnconfirmedIdentity != null)
        // dup pkt?
        return;
    int frags = _receivedIdentity.length;
    byte[] ident;
    if (frags > 1) {
        int identSize = 0;
        for (int i = 0; i < _receivedIdentity.length; i++) identSize += _receivedIdentity[i].length;
        ident = new byte[identSize];
        int off = 0;
        for (int i = 0; i < _receivedIdentity.length; i++) {
            int len = _receivedIdentity[i].length;
            System.arraycopy(_receivedIdentity[i], 0, ident, off, len);
            off += len;
        }
    } else {
        // no need to copy
        ident = _receivedIdentity[0];
    }
    ByteArrayInputStream in = new ByteArrayInputStream(ident);
    RouterIdentity peer = new RouterIdentity();
    try {
        peer.readBytes(in);
        _receivedUnconfirmedIdentity = peer;
    } catch (DataFormatException dfe) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("Improperly formatted yet fully received ident", dfe);
    } catch (IOException ioe) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("Improperly formatted yet fully received ident", ioe);
    }
}
Also used : DataFormatException(net.i2p.data.DataFormatException) ByteArrayInputStream(java.io.ByteArrayInputStream) RouterIdentity(net.i2p.data.router.RouterIdentity) IOException(java.io.IOException)

Example 67 with DataFormatException

use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.

the class LocalHTTPServer method serveLocalFile.

/**
 *  Very simple web server.
 *
 *  Serve local files in the docs/ directory, for CSS and images in
 *  error pages, using the reserved address proxy.i2p
 *  (similar to p.p in privoxy).
 *  This solves the problems with including links to the router console,
 *  as assuming the router console is at 127.0.0.1 leads to broken
 *  links if it isn't.
 *
 *  Ignore all request headers (If-Modified-Since, etc.)
 *
 *  There is basic protection here -
 *  FileUtil.readFile() prevents traversal above the base directory -
 *  but inproxy/gateway ops would be wise to block proxy.i2p to prevent
 *  exposing the docs/ directory or perhaps other issues through
 *  uncaught vulnerabilities.
 *  Restrict to the /themes/ directory for now.
 *
 *  @param targetRequest decoded path only, non-null
 *  @param query raw (encoded), may be null
 */
public static void serveLocalFile(OutputStream out, String method, String targetRequest, String query, String proxyNonce) throws IOException {
    // a home page message for the curious...
    if (targetRequest.equals("/")) {
        out.write(OK.getBytes("UTF-8"));
        out.flush();
        return;
    }
    if ((method.equals("GET") || method.equals("HEAD")) && targetRequest.startsWith("/themes/") && !targetRequest.contains("..")) {
        String filename = null;
        try {
            // "/themes/".length
            filename = targetRequest.substring(8);
        } catch (IndexOutOfBoundsException ioobe) {
            return;
        }
        // theme hack
        if (filename.startsWith("console/default/"))
            filename = filename.replaceFirst("default", I2PAppContext.getGlobalContext().getProperty("routerconsole.theme", "light"));
        File themesDir = new File(I2PAppContext.getGlobalContext().getBaseDir(), "docs/themes");
        File file = new File(themesDir, filename);
        if (file.exists() && !file.isDirectory()) {
            String type;
            if (filename.endsWith(".css"))
                type = "text/css";
            else if (filename.endsWith(".ico"))
                type = "image/x-icon";
            else if (filename.endsWith(".png"))
                type = "image/png";
            else if (filename.endsWith(".jpg"))
                type = "image/jpeg";
            else
                type = "text/html";
            out.write("HTTP/1.1 200 OK\r\nContent-Type: ".getBytes("UTF-8"));
            out.write(type.getBytes("UTF-8"));
            out.write("\r\nCache-Control: max-age=86400\r\nConnection: close\r\nProxy-Connection: close\r\n\r\n".getBytes("UTF-8"));
            FileUtil.readFile(filename, themesDir.getAbsolutePath(), out);
            return;
        }
    }
    // Do the add and redirect.
    if (targetRequest.equals("/add")) {
        if (query == null) {
            out.write(ERR_ADD.getBytes("UTF-8"));
            return;
        }
        Map<String, String> opts = new HashMap<String, String>(8);
        // this only works if all keys are followed by =value
        StringTokenizer tok = new StringTokenizer(query, "=&;");
        while (tok.hasMoreTokens()) {
            String k = tok.nextToken();
            if (!tok.hasMoreTokens())
                break;
            String v = tok.nextToken();
            opts.put(decode(k), decode(v));
        }
        String url = opts.get("url");
        String host = opts.get("host");
        String b64Dest = opts.get("dest");
        String nonce = opts.get("nonce");
        String referer = opts.get("referer");
        String book = "privatehosts.txt";
        if (opts.get("master") != null)
            book = "userhosts.txt";
        else if (opts.get("router") != null)
            book = "hosts.txt";
        Destination dest = null;
        if (b64Dest != null) {
            try {
                dest = new Destination(b64Dest);
            } catch (DataFormatException dfe) {
                System.err.println("Bad dest to save?" + b64Dest);
            }
        }
        // System.err.println("nonce        : \"" + nonce         + "\"");
        if (proxyNonce.equals(nonce) && url != null && host != null && dest != null) {
            NamingService ns = I2PAppContext.getGlobalContext().namingService();
            Properties nsOptions = new Properties();
            nsOptions.setProperty("list", book);
            if (referer != null && referer.startsWith("http")) {
                String ref = DataHelper.escapeHTML(referer);
                String from = "<a href=\"" + ref + "\">" + ref + "</a>";
                nsOptions.setProperty("s", _t("Added via address helper from {0}", from));
            } else {
                nsOptions.setProperty("s", _t("Added via address helper"));
            }
            boolean success = ns.put(host, dest, nsOptions);
            writeRedirectPage(out, success, host, book, url);
            return;
        }
        out.write(ERR_ADD.getBytes("UTF-8"));
    } else {
        out.write(ERR_404.getBytes("UTF-8"));
    }
    out.flush();
}
Also used : Destination(net.i2p.data.Destination) StringTokenizer(java.util.StringTokenizer) DataFormatException(net.i2p.data.DataFormatException) HashMap(java.util.HashMap) NamingService(net.i2p.client.naming.NamingService) Properties(java.util.Properties) File(java.io.File)

Example 68 with DataFormatException

use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.

the class SOCKS5Server method getDestinationI2PSocket.

/**
 * Get an I2PSocket that can be used to send/receive 8-bit clean data
 * to/from the destination of the SOCKS connection.
 *
 * @return an I2PSocket connected with the destination
 */
public I2PSocket getDestinationI2PSocket(I2PSOCKSTunnel t) throws SOCKSException {
    setupServer();
    if (connHostName == null) {
        _log.error("BUG: destination host name has not been initialized!");
        throw new SOCKSException("BUG! See the logs!");
    }
    if (connPort == 0) {
        _log.error("BUG: destination port has not been initialized!");
        throw new SOCKSException("BUG! See the logs!");
    }
    // for errors
    DataOutputStream out;
    try {
        out = new DataOutputStream(clientSock.getOutputStream());
    } catch (IOException e) {
        throw new SOCKSException("Connection error", e);
    }
    // FIXME: here we should read our config file, select an
    // outproxy, and instantiate the proper socket class that
    // handles the outproxy itself (SOCKS4a, SOCKS5, HTTP CONNECT...).
    I2PSocket destSock;
    try {
        if (connHostName.toLowerCase(Locale.US).endsWith(".i2p")) {
            // Let's not do a new Dest for every request, huh?
            // I2PSocketManager sm = I2PSocketManagerFactory.createManager();
            // destSock = sm.connect(I2PTunnel.destFromName(connHostName), null);
            Destination dest = _context.namingService().lookup(connHostName);
            if (dest == null) {
                try {
                    sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                } catch (IOException ioe) {
                }
                throw new SOCKSException("Host not found");
            }
            if (_log.shouldDebug())
                _log.debug("connecting to " + connHostName + "...");
            Properties overrides = new Properties();
            I2PSocketOptions sktOpts = t.buildOptions(overrides);
            sktOpts.setPort(connPort);
            destSock = t.createI2PSocket(dest, sktOpts);
        } else if ("localhost".equals(connHostName) || "127.0.0.1".equals(connHostName)) {
            String err = "No localhost accesses allowed through the Socks Proxy";
            _log.error(err);
            try {
                sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
            } catch (IOException ioe) {
            }
            throw new SOCKSException(err);
        /**
         **
         *            } else if (connPort == 80) {
         *                // rewrite GET line to include hostname??? or add Host: line???
         *                // or forward to local eepProxy (but that's a Socket not an I2PSocket)
         *                // use eepProxy configured outproxies?
         *                String err = "No handler for HTTP outproxy implemented";
         *                _log.error(err);
         *                try {
         *                    sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
         *                } catch (IOException ioe) {}
         *                throw new SOCKSException(err);
         ***
         */
        } else {
            Outproxy outproxy = getOutproxyPlugin();
            if (outproxy != null) {
                // but here, we wrap a Socket in a I2PSocket and use the regular Runner.
                try {
                    destSock = new SocketWrapper(outproxy.connect(connHostName, connPort));
                } catch (IOException ioe) {
                    try {
                        sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                    } catch (IOException ioe2) {
                    }
                    throw new SOCKSException("connect failed via outproxy plugin", ioe);
                }
            } else {
                List<String> proxies = t.getProxies(connPort);
                if (proxies == null || proxies.isEmpty()) {
                    String err = "No outproxy configured for port " + connPort + " and no default configured either";
                    _log.error(err);
                    try {
                        sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                    } catch (IOException ioe) {
                    }
                    throw new SOCKSException(err);
                }
                int p = _context.random().nextInt(proxies.size());
                String proxy = proxies.get(p);
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("connecting to proxy " + proxy + " for " + connHostName + " port " + connPort);
                try {
                    destSock = outproxyConnect(t, proxy);
                } catch (SOCKSException se) {
                    try {
                        sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                    } catch (IOException ioe) {
                    }
                    throw se;
                }
            }
        }
        confirmConnection();
        _log.debug("connection confirmed - exchanging data...");
    } catch (DataFormatException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("socks error", e);
        try {
            sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
        } catch (IOException ioe) {
        }
        throw new SOCKSException("Error in destination format");
    } catch (IOException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("socks error", e);
        try {
            sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
        } catch (IOException ioe) {
        }
        throw new SOCKSException("Connection error", e);
    } catch (I2PException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("socks error", e);
        try {
            sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
        } catch (IOException ioe) {
        }
        throw new SOCKSException("Connection error", e);
    }
    return destSock;
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) DataOutputStream(java.io.DataOutputStream) SOCKSException(net.i2p.socks.SOCKSException) I2PSocket(net.i2p.client.streaming.I2PSocket) Outproxy(net.i2p.app.Outproxy) I2PSocketOptions(net.i2p.client.streaming.I2PSocketOptions) IOException(java.io.IOException) Properties(java.util.Properties) DataFormatException(net.i2p.data.DataFormatException) ArrayList(java.util.ArrayList) List(java.util.List)

Example 69 with DataFormatException

use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.

the class AddressbookBean method getMessages.

/**
 * Perform actions, returning messages about this.
 */
public String getMessages() {
    // Loading config and addressbook moved into getLoadBookMessages()
    String message = "";
    if (action != null) {
        if (_context.getBooleanProperty(PROP_PW_ENABLE) || (serial != null && serial.equals(lastSerial))) {
            boolean changed = false;
            if (action.equals(_t("Add")) || action.equals(_t("Replace"))) {
                if (addressbook != null && hostname != null && destination != null) {
                    try {
                        // throws IAE with translated message
                        String host = AddressBean.toASCII(hostname);
                        String displayHost = host.equals(hostname) ? hostname : hostname + " (" + host + ')';
                        String oldDest = (String) addressbook.get(host);
                        if (destination.equals(oldDest)) {
                            message = _t("Host name {0} is already in address book, unchanged.", displayHost);
                        } else if (oldDest != null && !action.equals(_t("Replace"))) {
                            message = _t("Host name {0} is already in address book with a different destination. Click \"Replace\" to overwrite.", displayHost);
                        } else {
                            boolean valid = true;
                            try {
                                // just to check validity
                                new Destination(destination);
                            } catch (DataFormatException dfe) {
                                valid = false;
                            }
                            if (valid) {
                                addressbook.put(host, destination);
                                changed = true;
                                if (oldDest == null)
                                    message = _t("Destination added for {0}.", displayHost);
                                else
                                    message = _t("Destination changed for {0}.", displayHost);
                                if (!host.endsWith(".i2p"))
                                    message += "<br>" + _t("Warning - host name does not end with \".i2p\"");
                                // clear form
                                hostname = null;
                                destination = null;
                            } else {
                                message = _t("Invalid Base 64 destination.");
                            }
                        }
                    } catch (IllegalArgumentException iae) {
                        message = iae.getMessage();
                        if (message == null)
                            message = _t("Invalid host name \"{0}\".", hostname);
                    }
                } else {
                    message = _t("Please enter a host name and destination");
                }
                // clear search when adding
                search = null;
            } else if (action.equals(_t("Delete Selected")) || action.equals(_t("Delete Entry"))) {
                String name = null;
                int deleted = 0;
                for (String n : deletionMarks) {
                    addressbook.remove(n);
                    String uni = AddressBean.toUnicode(n);
                    String displayHost = uni.equals(n) ? n : uni + " (" + n + ')';
                    if (deleted++ == 0) {
                        changed = true;
                        name = displayHost;
                    }
                }
                if (changed) {
                    if (deleted == 1)
                        message = _t("Destination {0} deleted.", name);
                    else
                        // parameter will always be >= 2
                        message = ngettext("1 destination deleted.", "{0} destinations deleted.", deleted);
                } else {
                    message = _t("No entries selected to delete.");
                }
                if (action.equals(_t("Delete Entry")))
                    search = null;
            } else if (action.equals(_t("Add Alternate"))) {
                // button won't be in UI
                message = "Unsupported";
            }
            if (changed) {
                try {
                    save();
                    message += "<br>" + _t("Address book saved.");
                } catch (IOException e) {
                    warn(e);
                    message += "<br>" + _t("ERROR: Could not write addressbook file.");
                }
            }
        } else {
            message = _t("Invalid form submission, probably because you used the \"back\" or \"reload\" button on your browser. Please resubmit.") + ' ' + _t("If the problem persists, verify that you have cookies enabled in your browser.");
        }
    }
    action = null;
    if (message.length() > 0)
        message = "<p class=\"messages\">" + message + "</p>";
    return message;
}
Also used : Destination(net.i2p.data.Destination) DataFormatException(net.i2p.data.DataFormatException) IOException(java.io.IOException)

Example 70 with DataFormatException

use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.

the class NamingServiceBean method getMessages.

/**
 * Perform actions, returning messages about this.
 */
@Override
public String getMessages() {
    if (isDirect())
        return super.getMessages();
    // Loading config and addressbook moved into getLoadBookMessages()
    String message = "";
    if (action != null) {
        Properties nsOptions = new Properties();
        // only blockfile needs this
        nsOptions.setProperty("list", getFileName());
        if (_context.getBooleanProperty(PROP_PW_ENABLE) || (serial != null && serial.equals(lastSerial))) {
            boolean changed = false;
            if (action.equals(_t("Add")) || action.equals(_t("Replace")) || action.equals(_t("Add Alternate"))) {
                if (hostname != null && destination != null) {
                    try {
                        // throws IAE with translated message
                        String host = AddressBean.toASCII(hostname);
                        String displayHost = host.equals(hostname) ? hostname : hostname + " (" + host + ')';
                        Properties outProperties = new Properties();
                        Destination oldDest = getNamingService().lookup(host, nsOptions, outProperties);
                        if (oldDest != null && destination.equals(oldDest.toBase64())) {
                            message = _t("Host name {0} is already in address book, unchanged.", displayHost);
                        } else if (oldDest == null && action.equals(_t("Add Alternate"))) {
                            message = _t("Host name {0} is not in  the address book.", displayHost);
                        } else if (oldDest != null && action.equals(_t("Add"))) {
                            message = _t("Host name {0} is already in address book with a different destination. Click \"Replace\" to overwrite.", displayHost);
                        } else {
                            try {
                                Destination dest = new Destination(destination);
                                if (oldDest != null) {
                                    nsOptions.putAll(outProperties);
                                    String now = Long.toString(_context.clock().now());
                                    if (action.equals(_t("Add Alternate")))
                                        nsOptions.setProperty("a", now);
                                    else
                                        nsOptions.setProperty("m", now);
                                }
                                nsOptions.setProperty("s", _t("Manually added via SusiDNS"));
                                boolean success;
                                if (action.equals(_t("Add Alternate"))) {
                                    // check all for dups
                                    List<Destination> all = getNamingService().lookupAll(host);
                                    if (all == null || !all.contains(dest)) {
                                        success = getNamingService().addDestination(host, dest, nsOptions);
                                    } else {
                                        // will get generic message below
                                        success = false;
                                    }
                                } else {
                                    success = getNamingService().put(host, dest, nsOptions);
                                }
                                if (success) {
                                    changed = true;
                                    if (oldDest == null || action.equals(_t("Add Alternate")))
                                        message = _t("Destination added for {0}.", displayHost);
                                    else
                                        message = _t("Destination changed for {0}.", displayHost);
                                    if (!host.endsWith(".i2p"))
                                        message += "<br>" + _t("Warning - host name does not end with \".i2p\"");
                                    // clear form
                                    hostname = null;
                                    destination = null;
                                } else {
                                    message = _t("Failed to add Destination for {0} to naming service {1}", displayHost, getNamingService().getName()) + "<br>";
                                }
                            } catch (DataFormatException dfe) {
                                message = _t("Invalid Base 64 destination.");
                            }
                        }
                    } catch (IllegalArgumentException iae) {
                        message = iae.getMessage();
                        if (message == null)
                            message = _t("Invalid host name \"{0}\".", hostname);
                    }
                } else {
                    message = _t("Please enter a host name and destination");
                }
                // clear search when adding
                search = null;
            } else if (action.equals(_t("Delete Selected")) || action.equals(_t("Delete Entry"))) {
                String name = null;
                int deleted = 0;
                Destination matchDest = null;
                if (action.equals(_t("Delete Entry"))) {
                    // remove specified dest only in case there is more than one
                    if (destination != null) {
                        try {
                            matchDest = new Destination(destination);
                        } catch (DataFormatException dfe) {
                        }
                    }
                }
                for (String n : deletionMarks) {
                    boolean success;
                    if (matchDest != null)
                        success = getNamingService().remove(n, matchDest, nsOptions);
                    else
                        success = getNamingService().remove(n, nsOptions);
                    String uni = AddressBean.toUnicode(n);
                    String displayHost = uni.equals(n) ? n : uni + " (" + n + ')';
                    if (!success) {
                        message += _t("Failed to delete Destination for {0} from naming service {1}", displayHost, getNamingService().getName()) + "<br>";
                    } else if (deleted++ == 0) {
                        changed = true;
                        name = displayHost;
                    }
                }
                if (changed) {
                    if (deleted == 1)
                        // parameter is a host name
                        message += _t("Destination {0} deleted.", name);
                    else
                        // parameter will always be >= 2
                        message = ngettext("1 destination deleted.", "{0} destinations deleted.", deleted);
                } else {
                    message = _t("No entries selected to delete.");
                }
                // clear search when deleting
                if (action.equals(_t("Delete Entry")))
                    search = null;
            }
            if (changed) {
                message += "<br>" + _t("Address book saved.");
            }
        } else {
            message = _t("Invalid form submission, probably because you used the \"back\" or \"reload\" button on your browser. Please resubmit.") + ' ' + _t("If the problem persists, verify that you have cookies enabled in your browser.");
        }
    }
    action = null;
    if (message.length() > 0)
        message = "<p class=\"messages\">" + message + "</p>";
    return message;
}
Also used : Destination(net.i2p.data.Destination) DataFormatException(net.i2p.data.DataFormatException) Properties(java.util.Properties)

Aggregations

DataFormatException (net.i2p.data.DataFormatException)112 IOException (java.io.IOException)53 Destination (net.i2p.data.Destination)32 Properties (java.util.Properties)19 ByteArrayOutputStream (java.io.ByteArrayOutputStream)17 FileInputStream (java.io.FileInputStream)16 Hash (net.i2p.data.Hash)14 File (java.io.File)13 SigType (net.i2p.crypto.SigType)13 I2PSessionException (net.i2p.client.I2PSessionException)12 InputStream (java.io.InputStream)11 PrivateKey (net.i2p.data.PrivateKey)11 SigningPrivateKey (net.i2p.data.SigningPrivateKey)11 SigningPublicKey (net.i2p.data.SigningPublicKey)11 RouterInfo (net.i2p.data.router.RouterInfo)11 Signature (net.i2p.data.Signature)10 FileOutputStream (java.io.FileOutputStream)8 InterruptedIOException (java.io.InterruptedIOException)8 HashMap (java.util.HashMap)8 PublicKey (net.i2p.data.PublicKey)8