Search in sources :

Example 61 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class FtpClient method openPassiveDataConnection.

/**
     * Opens a "PASSIVE" connection with the server and returns the connected
     * <code>Socket</code>.
     *
     * @return the connected <code>Socket</code>
     * @throws IOException if the connection was unsuccessful.
     */
private Socket openPassiveDataConnection(String cmd) throws sun.net.ftp.FtpProtocolException, IOException {
    String serverAnswer;
    int port;
    InetSocketAddress dest = null;
    /**
         * Here is the idea:
         *
         * - First we want to try the new (and IPv6 compatible) EPSV command
         *   But since we want to be nice with NAT software, we'll issue the
         *   EPSV ALL command first.
         *   EPSV is documented in RFC2428
         * - If EPSV fails, then we fall back to the older, yet ok, PASV
         * - If PASV fails as well, then we throw an exception and the calling
         *   method will have to try the EPRT or PORT command
         */
    if (issueCommand("EPSV ALL")) {
        // We can safely use EPSV commands
        issueCommandCheck("EPSV");
        serverAnswer = getResponseString();
        if (epsvPat == null) {
            epsvPat = Pattern.compile("^229 .* \\(\\|\\|\\|(\\d+)\\|\\)");
        }
        Matcher m = epsvPat.matcher(serverAnswer);
        if (!m.find()) {
            throw new sun.net.ftp.FtpProtocolException("EPSV failed : " + serverAnswer);
        }
        // Yay! Let's extract the port number
        String s = m.group(1);
        port = Integer.parseInt(s);
        InetAddress add = server.getInetAddress();
        if (add != null) {
            dest = new InetSocketAddress(add, port);
        } else {
            // This means we used an Unresolved address to connect in
            // the first place. Most likely because the proxy is doing
            // the name resolution for us, so let's keep using unresolved
            // address.
            dest = InetSocketAddress.createUnresolved(serverAddr.getHostName(), port);
        }
    } else {
        // EPSV ALL failed, so Let's try the regular PASV cmd
        issueCommandCheck("PASV");
        serverAnswer = getResponseString();
        if (pasvPat == null) {
            pasvPat = Pattern.compile("227 .* \\(?(\\d{1,3},\\d{1,3},\\d{1,3},\\d{1,3}),(\\d{1,3}),(\\d{1,3})\\)?");
        }
        Matcher m = pasvPat.matcher(serverAnswer);
        if (!m.find()) {
            throw new sun.net.ftp.FtpProtocolException("PASV failed : " + serverAnswer);
        }
        // Get port number out of group 2 & 3
        port = Integer.parseInt(m.group(3)) + (Integer.parseInt(m.group(2)) << 8);
        // IP address is simple
        String s = m.group(1).replace(',', '.');
        dest = new InetSocketAddress(s, port);
    }
    // Got everything, let's open the socket!
    Socket s;
    if (proxy != null) {
        if (proxy.type() == Proxy.Type.SOCKS) {
            s = AccessController.doPrivileged(new PrivilegedAction<Socket>() {

                public Socket run() {
                    return new Socket(proxy);
                }
            });
        } else {
            s = new Socket(Proxy.NO_PROXY);
        }
    } else {
        s = new Socket();
    }
    InetAddress serverAddress = AccessController.doPrivileged(new PrivilegedAction<InetAddress>() {

        @Override
        public InetAddress run() {
            return server.getLocalAddress();
        }
    });
    // Bind the socket to the same address as the control channel. This
    // is needed in case of multi-homed systems.
    s.bind(new InetSocketAddress(serverAddress, 0));
    if (connectTimeout >= 0) {
        s.connect(dest, connectTimeout);
    } else {
        if (defaultConnectTimeout > 0) {
            s.connect(dest, defaultConnectTimeout);
        } else {
            s.connect(dest);
        }
    }
    if (readTimeout >= 0) {
        s.setSoTimeout(readTimeout);
    } else if (defaultSoTimeout > 0) {
        s.setSoTimeout(defaultSoTimeout);
    }
    if (useCrypto) {
        try {
            s = sslFact.createSocket(s, dest.getHostName(), dest.getPort(), true);
        } catch (Exception e) {
            throw new sun.net.ftp.FtpProtocolException("Can't open secure data channel: " + e);
        }
    }
    if (!issueCommand(cmd)) {
        s.close();
        if (getLastReplyCode() == FtpReplyCode.FILE_UNAVAILABLE) {
            // Ensure backward compatibility
            throw new FileNotFoundException(cmd);
        }
        throw new sun.net.ftp.FtpProtocolException(cmd + ":" + getResponseString(), getLastReplyCode());
    }
    return s;
}
Also used : sun.net.ftp(sun.net.ftp) Matcher(java.util.regex.Matcher) ParseException(java.text.ParseException) PrivilegedAction(java.security.PrivilegedAction) java.net(java.net) SSLSocket(javax.net.ssl.SSLSocket)

Example 62 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class ProviderImpl method initMapIfNecessary.

private static synchronized void initMapIfNecessary() throws SyncFactoryException {
    // Local implementation class names and keys from Properties
    // file, translate names into Class objects using Class.forName
    // and store mappings
    final Properties properties = new Properties();
    if (implementations == null) {
        implementations = new Hashtable<>();
        try {
            // check if user is supplying his Synchronisation Provider
            // Implementation if not using Oracle's implementation.
            // properties.load(new FileInputStream(ROWSET_PROPERTIES));
            // The rowset.properties needs to be in jdk/jre/lib when
            // integrated with jdk.
            // else it should be picked from -D option from command line.
            // -Drowset.properties will add to standard properties. Similar
            // keys will over-write
            /*
                 * Dependent on application
                 */
            String strRowsetProperties;
            try {
                strRowsetProperties = AccessController.doPrivileged(new PrivilegedAction<String>() {

                    public String run() {
                        return System.getProperty("rowset.properties");
                    }
                }, null, new PropertyPermission("rowset.properties", "read"));
            } catch (Exception ex) {
                System.out.println("errorget rowset.properties: " + ex);
                strRowsetProperties = null;
            }
            ;
            if (strRowsetProperties != null) {
                // Load user's implementation of SyncProvider
                // here. -Drowset.properties=/abc/def/pqr.txt
                ROWSET_PROPERTIES = strRowsetProperties;
                try (FileInputStream fis = new FileInputStream(ROWSET_PROPERTIES)) {
                    properties.load(fis);
                }
                parseProperties(properties);
            }
            /*
                 * Always available
                 */
            ROWSET_PROPERTIES = "javax" + strFileSep + "sql" + strFileSep + "rowset" + strFileSep + "rowset.properties";
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            try {
                AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
                    try (InputStream stream = (cl == null) ? ClassLoader.getSystemResourceAsStream(ROWSET_PROPERTIES) : cl.getResourceAsStream(ROWSET_PROPERTIES)) {
                        if (stream == null) {
                            throw new SyncFactoryException("Resource " + ROWSET_PROPERTIES + " not found");
                        }
                        properties.load(stream);
                    }
                    return null;
                });
            } catch (PrivilegedActionException ex) {
                Throwable e = ex.getException();
                if (e instanceof SyncFactoryException) {
                    throw (SyncFactoryException) e;
                } else {
                    SyncFactoryException sfe = new SyncFactoryException();
                    sfe.initCause(ex.getException());
                    throw sfe;
                }
            }
            parseProperties(properties);
        // removed else, has properties should sum together
        } catch (FileNotFoundException e) {
            throw new SyncFactoryException("Cannot locate properties file: " + e);
        } catch (IOException e) {
            throw new SyncFactoryException("IOException: " + e);
        }
        /*
             * Now deal with -Drowset.provider.classname
             * load additional properties from -D command line
             */
        properties.clear();
        String providerImpls;
        try {
            providerImpls = AccessController.doPrivileged(new PrivilegedAction<String>() {

                public String run() {
                    return System.getProperty(ROWSET_SYNC_PROVIDER);
                }
            }, null, new PropertyPermission(ROWSET_SYNC_PROVIDER, "read"));
        } catch (Exception ex) {
            providerImpls = null;
        }
        if (providerImpls != null) {
            int i = 0;
            if (providerImpls.indexOf(colon) > 0) {
                StringTokenizer tokenizer = new StringTokenizer(providerImpls, colon);
                while (tokenizer.hasMoreElements()) {
                    properties.put(ROWSET_SYNC_PROVIDER + "." + i, tokenizer.nextToken());
                    i++;
                }
            } else {
                properties.put(ROWSET_SYNC_PROVIDER, providerImpls);
            }
            parseProperties(properties);
        }
    }
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) FileInputStream(java.io.FileInputStream) PrivilegedAction(java.security.PrivilegedAction)

Example 63 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class AppletPropsErrorDialog method apply.

void apply() {
    String proxyHostValue = proxyHost.getText().trim();
    String proxyPortValue = proxyPort.getText().trim();
    // Get properties
    final Properties props = (Properties) AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            return System.getProperties();
        }
    });
    if (proxyHostValue.length() != 0) {
        /* 4066402 */
        /* Check for parsable value in proxy port number field before */
        /* applying. Display warning to user until parsable value is  */
        /* entered. */
        int proxyPortNumber = 0;
        try {
            proxyPortNumber = Integer.parseInt(proxyPortValue);
        } catch (NumberFormatException e) {
        }
        if (proxyPortNumber <= 0) {
            proxyPort.selectAll();
            proxyPort.requestFocus();
            (new AppletPropsErrorDialog(this, amh.getMessage("title.invalidproxy"), amh.getMessage("label.invalidproxy"), amh.getMessage("button.ok"))).show();
            return;
        }
        /* end 4066402 */
        props.put("http.proxyHost", proxyHostValue);
        props.put("http.proxyPort", proxyPortValue);
    } else {
        props.put("http.proxyHost", "");
    }
    if (amh.getMessage("choice.class.item.restricted").equals(accessMode.getSelectedItem())) {
        props.put("package.restrict.access.sun", "true");
    } else {
        props.put("package.restrict.access.sun", "false");
    }
    // Save properties
    try {
        reset();
        AccessController.doPrivileged(new PrivilegedExceptionAction() {

            public Object run() throws IOException {
                File dotAV = Main.theUserPropertiesFile;
                FileOutputStream out = new FileOutputStream(dotAV);
                Properties avProps = new Properties();
                for (int i = 0; i < Main.avDefaultUserProps.length; i++) {
                    String avKey = Main.avDefaultUserProps[i][0];
                    avProps.setProperty(avKey, props.getProperty(avKey));
                }
                avProps.store(out, amh.getMessage("prop.store"));
                out.close();
                return null;
            }
        });
        hide();
    } catch (java.security.PrivilegedActionException e) {
        System.out.println(amh.getMessage("apply.exception", e.getException()));
        // XXX what's the general feeling on stack traces to System.out?
        e.printStackTrace();
        reset();
    }
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Properties(java.util.Properties) PrivilegedAction(java.security.PrivilegedAction)

Example 64 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class SunFontManager method getFontFilesFromPath.

private String[] getFontFilesFromPath(boolean noType1) {
    final FilenameFilter filter;
    if (noType1) {
        filter = ttFilter;
    } else {
        filter = new TTorT1Filter();
    }
    return (String[]) AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            if (pathDirs.length == 1) {
                File dir = new File(pathDirs[0]);
                String[] files = dir.list(filter);
                if (files == null) {
                    return new String[0];
                }
                for (int f = 0; f < files.length; f++) {
                    files[f] = files[f].toLowerCase();
                }
                return files;
            } else {
                ArrayList<String> fileList = new ArrayList<String>();
                for (int i = 0; i < pathDirs.length; i++) {
                    File dir = new File(pathDirs[i]);
                    String[] files = dir.list(filter);
                    if (files == null) {
                        continue;
                    }
                    for (int f = 0; f < files.length; f++) {
                        fileList.add(files[f].toLowerCase());
                    }
                }
                return fileList.toArray(STR_ARRAY);
            }
        }
    });
}
Also used : FilenameFilter(java.io.FilenameFilter) PrivilegedAction(java.security.PrivilegedAction) ArrayList(java.util.ArrayList) File(java.io.File)

Example 65 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class CFontManager method createFont2D.

@Override
public Font2D createFont2D(File fontFile, int fontFormat, boolean isCopy, CreatedFontTracker tracker) throws FontFormatException {
    String fontFilePath = fontFile.getPath();
    Font2D font2D = null;
    final File fFile = fontFile;
    final CreatedFontTracker _tracker = tracker;
    try {
        switch(fontFormat) {
            case Font.TRUETYPE_FONT:
                font2D = new TrueTypeFont(fontFilePath, null, 0, true);
                break;
            case Font.TYPE1_FONT:
                font2D = new Type1Font(fontFilePath, null, isCopy);
                break;
            default:
                throw new FontFormatException("Unrecognised Font Format");
        }
    } catch (FontFormatException e) {
        if (isCopy) {
            java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<Object>() {

                public Object run() {
                    if (_tracker != null) {
                        _tracker.subBytes((int) fFile.length());
                    }
                    fFile.delete();
                    return null;
                }
            });
        }
        throw (e);
    }
    if (isCopy) {
        FileFont.setFileToRemove(font2D, fontFile, tracker);
        synchronized (FontManager.class) {
            if (tmpFontFiles == null) {
                tmpFontFiles = new Vector<File>();
            }
            tmpFontFiles.add(fontFile);
            if (fileCloser == null) {
                final Runnable fileCloserRunnable = new Runnable() {

                    public void run() {
                        java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<Object>() {

                            public Object run() {
                                for (int i = 0; i < CHANNELPOOLSIZE; i++) {
                                    if (fontFileCache[i] != null) {
                                        try {
                                            fontFileCache[i].close();
                                        } catch (Exception e) {
                                        }
                                    }
                                }
                                if (tmpFontFiles != null) {
                                    File[] files = new File[tmpFontFiles.size()];
                                    files = tmpFontFiles.toArray(files);
                                    for (int f = 0; f < files.length; f++) {
                                        try {
                                            files[f].delete();
                                        } catch (Exception e) {
                                        }
                                    }
                                }
                                return null;
                            }
                        });
                    }
                };
                AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
                    ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
                    fileCloser = new Thread(rootTG, fileCloserRunnable);
                    fileCloser.setContextClassLoader(null);
                    Runtime.getRuntime().addShutdownHook(fileCloser);
                    return null;
                });
            }
        }
    }
    return font2D;
}
Also used : PrivilegedAction(java.security.PrivilegedAction) File(java.io.File)

Aggregations

PrivilegedAction (java.security.PrivilegedAction)190 IOException (java.io.IOException)44 Subject (javax.security.auth.Subject)28 File (java.io.File)19 AccessControlContext (java.security.AccessControlContext)18 Method (java.lang.reflect.Method)13 InputStream (java.io.InputStream)12 URL (java.net.URL)11 LoginException (com.sun.enterprise.security.auth.login.common.LoginException)10 Field (java.lang.reflect.Field)10 URLClassLoader (java.net.URLClassLoader)10 Principal (java.security.Principal)10 Set (java.util.Set)9 PrivilegedActionException (java.security.PrivilegedActionException)8 Iterator (java.util.Iterator)8 PasswordCredential (com.sun.enterprise.security.auth.login.common.PasswordCredential)7 InvalidOperationException (com.sun.enterprise.security.auth.realm.InvalidOperationException)7 NoSuchRealmException (com.sun.enterprise.security.auth.realm.NoSuchRealmException)7 NoSuchUserException (com.sun.enterprise.security.auth.realm.NoSuchUserException)7 URISyntaxException (java.net.URISyntaxException)7