SdpProvider.java 12.0 KB
Newer Older
A
alanb 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
/*
 * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package sun.net.spi;

import sun.net.NetHooks;
import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.*;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintStream;

import sun.misc.SharedSecrets;
import sun.misc.JavaIOFileDescriptorAccess;

/**
 * A NetHooks provider that converts sockets from the TCP to SDP protocol prior
 * to binding or connecting.
 */

public class SdpProvider extends NetHooks.Provider {
    private static final JavaIOFileDescriptorAccess fdAccess =
        SharedSecrets.getJavaIOFileDescriptorAccess();

    // maximum port
    private static final int MAX_PORT = 65535;

    // indicates if SDP is enabled and the rules for when the protocol is used
    private final boolean enabled;
    private final List<Rule> rules;

    // logging for debug purposes
    private PrintStream log;

    public SdpProvider() {
        // if this property is not defined then there is nothing to do.
        String file = System.getProperty("com.sun.sdp.conf");
        if (file == null) {
            this.enabled = false;
            this.rules = null;
            return;
        }

        // load configuration file
        List<Rule> list = null;
        if (file != null) {
            try {
                list = loadRulesFromFile(file);
            } catch (IOException e) {
                fail("Error reading %s: %s", file, e.getMessage());
            }
        }

        // check if debugging is enabled
        PrintStream out = null;
        String logfile = System.getProperty("com.sun.sdp.debug");
        if (logfile != null) {
            out = System.out;
            if (logfile.length() > 0) {
                try {
                    out = new PrintStream(logfile);
                } catch (IOException ignore) { }
            }
        }

        this.enabled = !list.isEmpty();
        this.rules = list;
        this.log = out;
    }

    // supported actions
    private static enum Action {
        BIND,
        CONNECT;
    }

    // a rule for matching a bind or connect request
    private static interface Rule {
        boolean match(Action action, InetAddress address, int port);
    }

    // rule to match port[-end]
    private static class PortRangeRule implements Rule {
        private final Action action;
        private final int portStart;
        private final int portEnd;
        PortRangeRule(Action action, int portStart, int portEnd) {
            this.action = action;
            this.portStart = portStart;
            this.portEnd = portEnd;
        }
        Action action() {
            return action;
        }
        @Override
        public boolean match(Action action, InetAddress address, int port) {
            return (action == this.action &&
                    port >= this.portStart &&
                    port <= this.portEnd);
        }
    }

    // rule to match address[/prefix] port[-end]
    private static class AddressPortRangeRule extends PortRangeRule {
        private final byte[] addressAsBytes;
        private final int prefixByteCount;
        private final byte mask;
        AddressPortRangeRule(Action action, InetAddress address,
                             int prefix, int port, int end)
        {
            super(action, port, end);
            this.addressAsBytes = address.getAddress();
            this.prefixByteCount = prefix >> 3;
            this.mask = (byte)(0xff << (8 - (prefix % 8)));
        }
        @Override
        public boolean match(Action action, InetAddress address, int port) {
            if (action != action())
                return false;
            byte[] candidate = address.getAddress();
            // same address type?
            if (candidate.length != addressAsBytes.length)
                return false;
            // check bytes
            for (int i=0; i<prefixByteCount; i++) {
                if (candidate[i] != addressAsBytes[i])
                    return false;
            }
            // check remaining bits
            if ((prefixByteCount < addressAsBytes.length) &&
                ((candidate[prefixByteCount] & mask) !=
                 (addressAsBytes[prefixByteCount] & mask)))
                    return false;
            return super.match(action, address, port);
        }
    }

    // parses port:[-end]
    private static int[] parsePortRange(String s) {
        int pos = s.indexOf('-');
        try {
            int[] result = new int[2];
            if (pos < 0) {
                boolean all = s.equals("*");
                result[0] = all ? 0 : Integer.parseInt(s);
                result[1] = all ? MAX_PORT : result[0];
            } else {
                String low = s.substring(0, pos);
                if (low.length() == 0) low = "*";
                String high = s.substring(pos+1);
                if (high.length() == 0) high = "*";
                result[0] = low.equals("*") ? 0 : Integer.parseInt(low);
                result[1] = high.equals("*") ? MAX_PORT : Integer.parseInt(high);
            }
            return result;
        } catch (NumberFormatException e) {
            return new int[0];
        }
    }

    private static void fail(String msg, Object... args) {
        Formatter f = new Formatter();
        f.format(msg, args);
        throw new RuntimeException(f.out().toString());
    }

    // loads rules from the given file
    // Each non-blank/non-comment line must have the format:
    // ("bind" | "connect") 1*LWSP-char (hostname | ipaddress["/" prefix])
    //     1*LWSP-char ("*" | port) [ "-" ("*" | port) ]
    private static List<Rule> loadRulesFromFile(String file)
        throws IOException
    {
        Scanner scanner = new Scanner(new File(file));
        try {
            List<Rule> result = new ArrayList<Rule>();
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();

                // skip blank lines and comments
                if (line.length() == 0 || line.charAt(0) == '#')
                    continue;

                // must have 3 fields
                String[] s = line.split("\\s+");
                if (s.length != 3) {
                    fail("Malformed line '%s'", line);
                    continue;
                }

                // first field is the action ("bind" or "connect")
                Action action = null;
                for (Action a: Action.values()) {
                    if (s[0].equalsIgnoreCase(a.name())) {
                        action = a;
                        break;
                    }
                }
                if (action == null) {
                    fail("Action '%s' not recognized", s[0]);
                    continue;
                }

                // * port[-end]
                int[] ports = parsePortRange(s[2]);
                if (ports.length == 0) {
                    fail("Malformed port range '%s'", s[2]);
                    continue;
                }

                // match all addresses
                if (s[1].equals("*")) {
                    result.add(new PortRangeRule(action, ports[0], ports[1]));
                    continue;
                }

                // hostname | ipaddress[/prefix]
                int pos = s[1].indexOf('/');
                try {
                    if (pos < 0) {
                        // hostname or ipaddress (no prefix)
                        InetAddress[] addresses = InetAddress.getAllByName(s[1]);
                        for (InetAddress address: addresses) {
                            int prefix =
                                (address instanceof Inet4Address) ? 32 : 128;
                            result.add(new AddressPortRangeRule(action, address,
                                prefix, ports[0], ports[1]));
                        }
                    } else {
                        // ipaddress/prefix
                        InetAddress address = InetAddress
                            .getByName(s[1].substring(0, pos));
                        int prefix = -1;
                        try {
                            prefix = Integer.parseInt(s[1].substring(pos+1));
                            if (address instanceof Inet4Address) {
                                // must be 1-31
                                if (prefix < 0 || prefix > 32) prefix = -1;
                            } else {
                                // must be 1-128
                                if (prefix < 0 || prefix > 128) prefix = -1;
                            }
                        } catch (NumberFormatException e) {
                        }

                        if (prefix > 0) {
                            result.add(new AddressPortRangeRule(action,
                                        address, prefix, ports[0], ports[1]));
                        } else {
                            fail("Malformed prefix '%s'", s[1]);
                            continue;
                        }
                    }
                } catch (UnknownHostException uhe) {
                    fail("Unknown host or malformed IP address '%s'", s[1]);
                    continue;
                }
            }
            return result;
        } finally {
            scanner.close();
        }
    }

    // converts unbound TCP socket to a SDP socket if it matches the rules
    private void convertTcpToSdpIfMatch(FileDescriptor fdObj,
                                               Action action,
                                               InetAddress address,
                                               int port)
        throws IOException
    {
        boolean matched = false;
        for (Rule rule: rules) {
            if (rule.match(action, address, port)) {
                int fd = fdAccess.get(fdObj);
                convert(fd);
                matched = true;
                break;
            }
        }
        if (log != null) {
            String addr = (address instanceof Inet4Address) ?
                address.getHostAddress() : "[" + address.getHostAddress() + "]";
            if (matched) {
                log.format("%s to %s:%d (socket converted to SDP protocol)\n", action, addr, port);
            } else {
                log.format("%s to %s:%d (no match)\n", action, addr, port);
            }
        }
    }

    @Override
    public void implBeforeTcpBind(FileDescriptor fdObj,
                              InetAddress address,
                              int port)
        throws IOException
    {
        if (enabled)
            convertTcpToSdpIfMatch(fdObj, Action.BIND, address, port);
    }

    @Override
    public void implBeforeTcpConnect(FileDescriptor fdObj,
                                InetAddress address,
                                int port)
        throws IOException
    {
        if (enabled)
            convertTcpToSdpIfMatch(fdObj, Action.CONNECT, address, port);
    }

    // -- native methods --
    private static native void convert(int fd) throws IOException;
}