Search in sources :

Example 26 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class PluginInitializer method loadPluginFromDir.

private List loadPluginFromDir(File directory, boolean bSkipAlreadyLoaded, boolean loading_for_startup, // initialise setting is used if loading_for_startup isnt
boolean initialise) throws PluginException {
    List loaded_pis = new ArrayList();
    ClassLoader plugin_class_loader = root_class_loader;
    if (!directory.isDirectory()) {
        return (loaded_pis);
    }
    String pluginName = directory.getName();
    File[] pluginContents = directory.listFiles();
    if (pluginContents == null || pluginContents.length == 0) {
        return (loaded_pis);
    }
    // first sanity check - dir must include either a plugin.properties or
    // at least one .jar file
    boolean looks_like_plugin = false;
    for (int i = 0; i < pluginContents.length; i++) {
        String name = pluginContents[i].getName().toLowerCase();
        if (name.endsWith(".jar") || name.equals("plugin.properties")) {
            looks_like_plugin = true;
            break;
        }
    }
    if (!looks_like_plugin) {
        if (Logger.isEnabled())
            Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Plugin directory '" + directory + "' has no plugin.properties " + "or .jar files, skipping"));
        return (loaded_pis);
    }
    // take only the highest version numbers of jars that look versioned
    String[] plugin_version = { null };
    String[] plugin_id = { null };
    pluginContents = PluginLauncherImpl.getHighestJarVersions(pluginContents, plugin_version, plugin_id, true);
    for (int i = 0; i < pluginContents.length; i++) {
        File jar_file = pluginContents[i];
        if (pluginContents.length > 1) {
            String name = jar_file.getName();
            if (name.startsWith("i18nPlugin_")) {
                if (Logger.isEnabled())
                    Logger.log(new LogEvent(LOGID, "renaming '" + name + "' to conform with versioning system"));
                jar_file.renameTo(new File(jar_file.getParent(), "i18nAZ_0.1.jar  "));
                continue;
            }
        }
        plugin_class_loader = PluginLauncherImpl.addFileToClassPath(root_class_loader, plugin_class_loader, jar_file);
    }
    String plugin_class_string = null;
    try {
        Properties props = new Properties();
        File properties_file = new File(directory.toString() + File.separator + "plugin.properties");
        try {
            if (properties_file.exists()) {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(properties_file);
                    props.load(fis);
                } finally {
                    if (fis != null) {
                        fis.close();
                    }
                }
            } else {
                if (plugin_class_loader instanceof URLClassLoader) {
                    URLClassLoader current = (URLClassLoader) plugin_class_loader;
                    URL url = current.findResource("plugin.properties");
                    if (url != null) {
                        URLConnection connection = url.openConnection();
                        InputStream is = connection.getInputStream();
                        props.load(is);
                    } else {
                        throw (new Exception("failed to load plugin.properties from jars"));
                    }
                } else {
                    throw (new Exception("failed to load plugin.properties from dir or jars"));
                }
            }
        } catch (Throwable e) {
            Debug.printStackTrace(e);
            String msg = "Can't read 'plugin.properties' for plugin '" + pluginName + "': file may be missing";
            Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, msg));
            System.out.println(msg);
            throw (new PluginException(msg, e));
        }
        checkJDKVersion(pluginName, props, true);
        checkCoreAppVersion(pluginName, props, true);
        plugin_class_string = (String) props.get("plugin.class");
        if (plugin_class_string == null) {
            plugin_class_string = (String) props.get("plugin.classes");
            if (plugin_class_string == null) {
                // set so we don't bork later will npe
                plugin_class_string = "";
            }
        }
        String plugin_name_string = (String) props.get("plugin.name");
        if (plugin_name_string == null) {
            plugin_name_string = (String) props.get("plugin.names");
        }
        int pos1 = 0;
        int pos2 = 0;
        while (true) {
            int p1 = plugin_class_string.indexOf(";", pos1);
            String plugin_class;
            if (p1 == -1) {
                plugin_class = plugin_class_string.substring(pos1).trim();
            } else {
                plugin_class = plugin_class_string.substring(pos1, p1).trim();
                pos1 = p1 + 1;
            }
            PluginInterfaceImpl existing_pi = getPluginFromClass(plugin_class);
            if (existing_pi != null) {
                if (bSkipAlreadyLoaded) {
                    break;
                }
                // allow user dir entries to override app dir entries without warning
                File this_parent = directory.getParentFile();
                File existing_parent = null;
                if (existing_pi.getInitializerKey() instanceof File) {
                    existing_parent = ((File) existing_pi.getInitializerKey()).getParentFile();
                }
                if (this_parent.equals(FileUtil.getApplicationFile("plugins")) && existing_parent != null && existing_parent.equals(FileUtil.getUserFile("plugins"))) {
                    if (Logger.isEnabled())
                        Logger.log(new LogEvent(LOGID, "Plugin '" + plugin_name_string + "/" + plugin_class + ": shared version overridden by user-specific one"));
                    return (new ArrayList());
                } else {
                    Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_WARNING, "Error loading '" + plugin_name_string + "', plugin class '" + plugin_class + "' is already loaded"));
                }
            } else {
                String plugin_name = null;
                if (plugin_name_string != null) {
                    int p2 = plugin_name_string.indexOf(";", pos2);
                    if (p2 == -1) {
                        plugin_name = plugin_name_string.substring(pos2).trim();
                    } else {
                        plugin_name = plugin_name_string.substring(pos2, p2).trim();
                        pos2 = p2 + 1;
                    }
                }
                Properties new_props = (Properties) props.clone();
                new_props.put("plugin.class", plugin_class);
                if (plugin_name != null) {
                    new_props.put("plugin.name", plugin_name);
                }
                // System.out.println( "loading plugin '" + plugin_class + "' using cl " + classLoader);
                // if the plugin load fails we still need to generate a plugin entry
                // as this drives the upgrade process
                Throwable load_failure = null;
                String pid = plugin_id[0] == null ? directory.getName() : plugin_id[0];
                List<File> verified_files = null;
                Plugin plugin = null;
                if (vc_disabled_plugins.contains(pid)) {
                    log("Plugin '" + pid + "' has been administratively disabled");
                } else {
                    try {
                        String cl_key = "plugin.cl.ext." + pid;
                        String str = COConfigurationManager.getStringParameter(cl_key, null);
                        if (str != null && str.length() > 0) {
                            COConfigurationManager.removeParameter(cl_key);
                            plugin_class_loader = PluginLauncherImpl.extendClassLoader(root_class_loader, plugin_class_loader, new URL(str));
                        }
                    } catch (Throwable e) {
                    }
                    if (pid.endsWith("_v")) {
                        verified_files = new ArrayList<>();
                        // re-verify jar files
                        log("Re-verifying " + pid);
                        for (int i = 0; i < pluginContents.length; i++) {
                            File jar_file = pluginContents[i];
                            if (jar_file.getName().endsWith(".jar")) {
                                try {
                                    log("    verifying " + jar_file);
                                    AEVerifier.verifyData(jar_file);
                                    verified_files.add(jar_file);
                                    log("    OK");
                                } catch (Throwable e) {
                                    String msg = "Error loading plugin '" + pluginName + "' / '" + plugin_class_string + "'";
                                    Logger.log(new LogAlert(LogAlert.UNREPEATABLE, msg, e));
                                    plugin = new FailedPlugin(plugin_name, directory.getAbsolutePath());
                                }
                            }
                        }
                    }
                    if (plugin == null) {
                        plugin = PluginLauncherImpl.getPreloadedPlugin(plugin_class);
                        if (plugin == null) {
                            try {
                                try {
                                    Class<Plugin> c = (Class<Plugin>) PlatformManagerFactory.getPlatformManager().loadClass(plugin_class_loader, plugin_class);
                                    // Class c = plugin_class_loader.loadClass(plugin_class);
                                    plugin = c.newInstance();
                                    try {
                                        if (plugin_class_loader instanceof URLClassLoader) {
                                            URL[] urls = ((URLClassLoader) plugin_class_loader).getURLs();
                                            for (URL u : urls) {
                                                String path = u.getPath();
                                                if (path.endsWith(".jar")) {
                                                    int s1 = path.lastIndexOf('/');
                                                    int s2 = path.lastIndexOf('\\');
                                                    path = path.substring(Math.max(s1, s2) + 1);
                                                    s2 = path.indexOf('_');
                                                    if (s2 > 0) {
                                                        path = path.substring(0, s2);
                                                        path = path.replaceAll("-", "");
                                                        String cl = "plugin.preinit." + pid + ".PI" + path;
                                                        try {
                                                            Class pic = plugin_class_loader.loadClass(cl);
                                                            if (pic != null) {
                                                                pic.newInstance();
                                                            }
                                                        } catch (Throwable e) {
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } catch (Throwable e) {
                                    }
                                } catch (PlatformManagerException e) {
                                    throw (e.getCause());
                                }
                            } catch (java.lang.UnsupportedClassVersionError e) {
                                plugin = new FailedPlugin(plugin_name, directory.getAbsolutePath());
                                // shorten stack trace
                                load_failure = new UnsupportedClassVersionError(e.getMessage());
                            } catch (Throwable e) {
                                if (e instanceof ClassNotFoundException && props.getProperty("plugin.install_if_missing", "no").equalsIgnoreCase("yes")) {
                                // don't report the failure
                                } else {
                                    load_failure = e;
                                }
                                plugin = new FailedPlugin(plugin_name, directory.getAbsolutePath());
                            }
                        } else {
                            plugin_class_loader = plugin.getClass().getClassLoader();
                        }
                    }
                    MessageText.integratePluginMessages((String) props.get("plugin.langfile"), plugin_class_loader);
                    PluginInterfaceImpl plugin_interface = new PluginInterfaceImpl(plugin, this, directory, plugin_class_loader, verified_files, // key for config values
                    directory.getName(), new_props, directory.getAbsolutePath(), pid, plugin_version[0]);
                    boolean bEnabled = (loading_for_startup) ? plugin_interface.getPluginState().isLoadedAtStartup() : initialise;
                    plugin_interface.getPluginState().setDisabled(!bEnabled);
                    try {
                        Method load_method = plugin.getClass().getMethod("load", new Class[] { PluginInterface.class });
                        load_method.invoke(plugin, new Object[] { plugin_interface });
                    } catch (NoSuchMethodException e) {
                    } catch (Throwable e) {
                        load_failure = e;
                    }
                    loaded_pis.add(plugin_interface);
                    if (load_failure != null) {
                        plugin_interface.setAsFailed();
                        if (!pid.equals(UpdaterUpdateChecker.getPluginID())) {
                            String msg = MessageText.getString("plugin.init.load.failed", new String[] { plugin_name == null ? pluginName : plugin_name, directory.getAbsolutePath() });
                            LogAlert la;
                            if (load_failure instanceof UnsupportedClassVersionError) {
                                la = new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, msg + ".\n\n" + MessageText.getString("plugin.install.class_version_error"));
                            } else if (load_failure instanceof ClassNotFoundException) {
                                la = new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, msg + ".\n\n" + MessageText.getString("plugin.init.load.failed.classmissing") + "\n\n", load_failure);
                            } else {
                                la = new LogAlert(LogAlert.UNREPEATABLE, msg, load_failure);
                            }
                            Logger.log(la);
                            System.out.println(msg + ": " + load_failure);
                        }
                    }
                }
            }
            if (p1 == -1) {
                break;
            }
        }
        return (loaded_pis);
    } catch (Throwable e) {
        if (e instanceof PluginException) {
            throw ((PluginException) e);
        }
        Debug.printStackTrace(e);
        String msg = "Error loading plugin '" + pluginName + "' / '" + plugin_class_string + "'";
        Logger.log(new LogAlert(LogAlert.UNREPEATABLE, msg, e));
        System.out.println(msg + ": " + e);
        throw (new PluginException(msg, e));
    }
}
Also used : URL(java.net.URL) URLClassLoader(java.net.URLClassLoader) LogEvent(com.biglybt.core.logging.LogEvent) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Method(java.lang.reflect.Method) FileInputStream(java.io.FileInputStream) URLConnection(java.net.URLConnection) PlatformManagerException(com.biglybt.pif.platform.PlatformManagerException) CoreException(com.biglybt.core.CoreException) UtilitiesImpl.runnableWithException(com.biglybt.pifimpl.local.utils.UtilitiesImpl.runnableWithException) LogAlert(com.biglybt.core.logging.LogAlert) URLClassLoader(java.net.URLClassLoader) PlatformManagerException(com.biglybt.pif.platform.PlatformManagerException) File(java.io.File)

Example 27 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class PluginInitializer method initializePluginFromClass.

protected void initializePluginFromClass(final Class plugin_class, final String plugin_id, String plugin_config_key, boolean force_enabled, boolean loading_for_startup, boolean initialise) throws PluginException {
    if (plugin_class != FailedPlugin.class && getPluginFromClass(plugin_class) != null) {
        Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_WARNING, "Error loading '" + plugin_id + "', plugin class '" + plugin_class.getName() + "' is already loaded"));
        return;
    }
    try {
        final Plugin plugin = (Plugin) plugin_class.newInstance();
        String plugin_name;
        if (plugin_config_key.length() == 0) {
            plugin_name = plugin_class.getName();
            int pos = plugin_name.lastIndexOf(".");
            if (pos != -1) {
                plugin_name = plugin_name.substring(pos + 1);
            }
        } else {
            plugin_name = plugin_config_key;
        }
        Properties properties = new Properties();
        // default plugin name
        properties.put("plugin.name", plugin_name);
        final PluginInterfaceImpl plugin_interface = new PluginInterfaceImpl(plugin, this, plugin_class, plugin_class.getClassLoader(), null, plugin_config_key, properties, "", plugin_id, null);
        boolean bEnabled = (loading_for_startup) ? plugin_interface.getPluginState().isLoadedAtStartup() : initialise;
        /**
         * For some plugins, override any config setting which disables the plugin.
         */
        if (force_enabled && !bEnabled) {
            plugin_interface.getPluginState().setLoadedAtStartup(true);
            bEnabled = true;
            Logger.log(new LogAlert(false, LogAlert.AT_WARNING, MessageText.getString("plugins.init.force_enabled", new String[] { plugin_id })));
        }
        plugin_interface.getPluginState().setDisabled(!bEnabled);
        final boolean f_enabled = bEnabled;
        UtilitiesImpl.callWithPluginThreadContext(plugin_interface, new runnableWithException<PluginException>() {

            @Override
            public void run() throws PluginException {
                try {
                    Method load_method = plugin_class.getMethod("load", new Class[] { PluginInterface.class });
                    load_method.invoke(plugin, new Object[] { plugin_interface });
                } catch (NoSuchMethodException e) {
                } catch (Throwable e) {
                    Debug.printStackTrace(e);
                    Logger.log(new LogAlert(LogAlert.UNREPEATABLE, "Load of built in plugin '" + plugin_id + "' fails", e));
                }
                if (f_enabled) {
                    fireCreated(plugin_interface);
                    plugin.initialize(plugin_interface);
                    if (!(plugin instanceof FailedPlugin)) {
                        plugin_interface.getPluginStateImpl().setOperational(true, false);
                    }
                }
            }
        });
        synchronized (s_plugin_interfaces) {
            s_plugins.add(plugin);
            s_plugin_interfaces.add(plugin_interface);
        }
    } catch (Throwable e) {
        Debug.printStackTrace(e);
        String msg = "Error loading internal plugin '" + plugin_class.getName() + "'";
        Logger.log(new LogAlert(LogAlert.UNREPEATABLE, msg, e));
        System.out.println(msg + " : " + e);
        throw (new PluginException(msg, e));
    }
}
Also used : Method(java.lang.reflect.Method) LogAlert(com.biglybt.core.logging.LogAlert)

Example 28 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class PluginInitializer method checkCoreAppVersion.

public static void checkCoreAppVersion(String name, Properties props, boolean alert_on_fail) throws PluginException {
    String required_version = (String) props.get("plugin.coreapp.min_version");
    if (required_version == null) {
        return;
    }
    if (Constants.compareVersions(Constants.AZUREUS_VERSION, required_version) < 0) {
        String plugin_name_bit = name.length() > 0 ? (name + " ") : "";
        String msg = "Plugin " + plugin_name_bit + "requires " + Constants.APP_NAME + " version " + required_version + " or higher";
        if (alert_on_fail) {
            Logger.log(new LogAlert(LogAlert.REPEATABLE, LogAlert.AT_ERROR, msg));
        }
        throw new PluginException(msg);
    }
}
Also used : LogAlert(com.biglybt.core.logging.LogAlert)

Example 29 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class LoggerImpl method addAlertListener.

@Override
public void addAlertListener(final LogAlertListener listener) {
    ILogAlertListener lg_listener = new ILogAlertListener() {

        private HashSet set = new HashSet();

        @Override
        public void alertRaised(LogAlert alert) {
            if (!alert.repeatable) {
                if (set.contains(alert.text)) {
                    return;
                }
                set.add(alert.text);
            }
            listener.alertRaised(alert);
        }
    };
    alert_listeners_map2.put(listener, lg_listener);
    com.biglybt.core.logging.Logger.addListener(lg_listener);
}
Also used : ILogAlertListener(com.biglybt.core.logging.ILogAlertListener) LogAlert(com.biglybt.core.logging.LogAlert)

Example 30 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class ClientIDManagerImpl method setupFilter.

private void setupFilter(boolean force) {
    synchronized (filter_lock) {
        if (!use_filter) {
            if (force) {
                use_filter = true;
            } else {
                return;
            }
        }
        if (filter_port != 0) {
            return;
        }
        try {
            thread_pool = new ThreadPool("ClientIDManager", 32);
            int timeout = connect_timeout + read_timeout;
            thread_pool.setExecutionLimit(timeout);
            final ServerSocket ss = new ServerSocket(0, 1024, InetAddress.getByName("127.0.0.1"));
            filter_port = ss.getLocalPort();
            ss.setReuseAddress(true);
            new AEThread2("ClientIDManager::filterloop") {

                @Override
                public void run() {
                    long failed_accepts = 0;
                    while (true) {
                        try {
                            Socket socket = ss.accept();
                            failed_accepts = 0;
                            thread_pool.run(new httpFilter(socket));
                        } catch (Throwable e) {
                            failed_accepts++;
                            if (Logger.isEnabled())
                                Logger.log(new LogEvent(LOGID, "ClientIDManager: listener failed on port " + filter_port, e));
                            if (failed_accepts > 10) {
                                // looks like its not going to work...
                                // some kind of socket problem
                                Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "Network.alert.acceptfail"), new String[] { "" + filter_port, "TCP" });
                                use_filter = false;
                                break;
                            }
                        }
                    }
                }
            }.start();
            if (Logger.isEnabled())
                Logger.log(new LogEvent(LOGID, "ClientIDManager: listener established on port " + filter_port));
        } catch (Throwable e) {
            Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "Tracker.alert.listenfail"), new String[] { "" + filter_port });
            if (Logger.isEnabled())
                Logger.log(new LogEvent(LOGID, "ClientIDManager: listener failed on port " + filter_port, e));
            use_filter = false;
        }
    }
}
Also used : LogEvent(com.biglybt.core.logging.LogEvent) LogAlert(com.biglybt.core.logging.LogAlert)

Aggregations

LogAlert (com.biglybt.core.logging.LogAlert)72 File (java.io.File)21 LogEvent (com.biglybt.core.logging.LogEvent)20 URL (java.net.URL)7 Core (com.biglybt.core.Core)5 ParameterListener (com.biglybt.core.config.ParameterListener)5 DownloadManager (com.biglybt.core.download.DownloadManager)5 TOTorrent (com.biglybt.core.torrent.TOTorrent)5 UIFunctions (com.biglybt.ui.UIFunctions)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 VuzeFile (com.biglybt.core.vuzefile.VuzeFile)4 PlatformManagerException (com.biglybt.pif.platform.PlatformManagerException)4 Method (java.lang.reflect.Method)4 CoreRunningListener (com.biglybt.core.CoreRunningListener)3 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)3 URLClassLoader (java.net.URLClassLoader)3 CoreException (com.biglybt.core.CoreException)2 CacheFile (com.biglybt.core.diskmanager.cache.CacheFile)2 DownloadManagerInitialisationAdapter (com.biglybt.core.download.DownloadManagerInitialisationAdapter)2