public Set<String> getAutoInstallPluginIDs() {
    Set<String> result = new HashSet<String>();

    Map m = getMostRecentVersionCheckData();

    if (m != null) {

      byte[] x = (byte[]) m.get("autoinstall_pids");

      if (x != null) {

        String str = new String(x);

        String latest = COConfigurationManager.getStringParameter("vc.autoinstall_pids.latest", "");

        if (!str.equals(latest)) {

          byte[] sig = (byte[]) m.get("autoinstall_pids_sig");

          if (sig == null) {

            Debug.out("autoinstall plugins sig missing");

            return (result);
          }

          try {
            AEVerifier.verifyData(str, sig);

            COConfigurationManager.setParameter("vc.autoinstall_pids.latest", str);

          } catch (Throwable e) {

            return (result);
          }
        }

        String[] bits = str.split(",");

        for (String b : bits) {

          b = b.trim();

          if (b.length() > 0) {

            result.add(b);
          }
        }
      }
    }

    return (result);
  }
  public void addVersionCheckClientListener(
      boolean triggerStartListener, VersionCheckClientListener l) {
    synchronized (listeners) {
      listeners.add(l);

      if (triggerStartListener && startCheckRan) {
        try {
          l.versionCheckStarted(REASON_UPDATE_CHECK_START);
        } catch (Exception e) {
          Debug.out(e);
        }
      }
    }
  }
  /** Stop the server. */
  public void stop() {
    try {
      this_mon.enter();

      if (server_channel != null) {
        try {
          server_channel.close();
          server_channel = null;
        } catch (Throwable t) {
          Debug.out(t);
        }
      }
    } finally {

      this_mon.exit();
    }
  }
 protected void accept_loop() {
   while (isRunning()) {
     try {
       SocketChannel client_channel = server_channel.accept();
       last_accept_time = SystemTime.getCurrentTime();
       client_channel.configureBlocking(false);
       listener.newConnectionAccepted(server_channel, client_channel);
     } catch (AsynchronousCloseException e) {
       /* is thrown when stop() is called */
     } catch (Throwable t) {
       Debug.out(t);
       try {
         Thread.sleep(500);
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
 }
  /** Start the server and begin accepting incoming connections. */
  public void start() {
    try {
      this_mon.enter();

      if (!isRunning()) {
        try {
          server_channel = ServerSocketChannel.open();

          server_channel.socket().setReuseAddress(true);
          if (receive_buffer_size > 0)
            server_channel.socket().setReceiveBufferSize(receive_buffer_size);

          server_channel.socket().bind(bind_address, 1024);

          if (Logger.isEnabled())
            Logger.log(new LogEvent(LOGID, "TCP incoming server socket " + bind_address));

          AEThread accept_thread =
              new AEThread("VServerSelector:port" + bind_address.getPort()) {
                public void runSupport() {
                  accept_loop();
                }
              };
          accept_thread.setDaemon(true);
          accept_thread.start();
        } catch (Throwable t) {
          Debug.out(t);
          Logger.log(
              new LogAlert(
                  LogAlert.UNREPEATABLE,
                  "ERROR, unable to bind TCP incoming server socket to " + bind_address.getPort(),
                  t));
        }

        last_accept_time = SystemTime.getCurrentTime(); // init to now
      }
    } finally {

      this_mon.exit();
    }
  }
    protected authDialog(
        AESemaphore _sem,
        Display display,
        String realm,
        boolean is_tracker,
        String target,
        String details) {
      sem = _sem;

      if (display.isDisposed()) {

        sem.releaseForever();

        return;
      }

      final String ignore_key = "IgnoreAuth:" + realm + ":" + target + ":" + details;

      if (RememberedDecisionsManager.getRememberedDecision(ignore_key) == 1) {

        Debug.out(
            "Authentication for "
                + realm
                + "/"
                + target
                + "/"
                + details
                + " ignored as told not to ask again");

        sem.releaseForever();

        return;
      }

      shell = ShellFactory.createMainShell(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);

      Utils.setShellIcon(shell);
      Messages.setLanguageText(shell, "authenticator.title");

      GridLayout layout = new GridLayout();
      layout.numColumns = 3;

      shell.setLayout(layout);

      GridData gridData;

      // realm

      Label realm_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(realm_label, "authenticator.realm");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      realm_label.setLayoutData(gridData);

      Label realm_value = new Label(shell, SWT.NULL);
      realm_value.setText(realm.replaceAll("&", "&&"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      realm_value.setLayoutData(gridData);

      // target

      Label target_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(
          target_label, is_tracker ? "authenticator.tracker" : "authenticator.location");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      target_label.setLayoutData(gridData);

      Label target_value = new Label(shell, SWT.NULL);
      target_value.setText(target.replaceAll("&", "&&"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      target_value.setLayoutData(gridData);

      if (details != null) {

        Label details_label = new Label(shell, SWT.NULL);
        Messages.setLanguageText(
            details_label, is_tracker ? "authenticator.torrent" : "authenticator.details");
        gridData = new GridData(GridData.FILL_BOTH);
        gridData.horizontalSpan = 1;
        details_label.setLayoutData(gridData);

        Label details_value = new Label(shell, SWT.NULL);
        details_value.setText(details.replaceAll("&", "&&"));
        gridData = new GridData(GridData.FILL_BOTH);
        gridData.horizontalSpan = 2;
        details_value.setLayoutData(gridData);
      }
      // user

      Label user_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(user_label, "authenticator.user");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      user_label.setLayoutData(gridData);

      final Text user_value = new Text(shell, SWT.BORDER);
      user_value.setText("");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      user_value.setLayoutData(gridData);

      user_value.addListener(
          SWT.Modify,
          new Listener() {
            public void handleEvent(Event event) {
              username = user_value.getText();
            }
          });

      // password

      Label password_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(password_label, "authenticator.password");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      password_label.setLayoutData(gridData);

      final Text password_value = new Text(shell, SWT.BORDER);
      password_value.setEchoChar('*');
      password_value.setText("");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      password_value.setLayoutData(gridData);

      password_value.addListener(
          SWT.Modify,
          new Listener() {
            public void handleEvent(Event event) {
              password = password_value.getText();
            }
          });

      // persist

      Label blank_label = new Label(shell, SWT.NULL);
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      blank_label.setLayoutData(gridData);

      final Button checkBox = new Button(shell, SWT.CHECK);
      checkBox.setText(MessageText.getString("authenticator.savepassword"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      checkBox.setLayoutData(gridData);
      checkBox.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              persist = checkBox.getSelection();
            }
          });

      final Button dontAsk = new Button(shell, SWT.CHECK);
      dontAsk.setText(MessageText.getString("general.dont.ask.again"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      dontAsk.setLayoutData(gridData);
      dontAsk.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              RememberedDecisionsManager.setRemembered(ignore_key, dontAsk.getSelection() ? 1 : 0);
            }
          });

      // line

      Label labelSeparator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
      gridData = new GridData(GridData.FILL_HORIZONTAL);
      gridData.horizontalSpan = 3;
      labelSeparator.setLayoutData(gridData);

      // buttons

      new Label(shell, SWT.NULL);

      Button bOk = new Button(shell, SWT.PUSH);
      Messages.setLanguageText(bOk, "Button.ok");
      gridData =
          new GridData(
              GridData.FILL_HORIZONTAL
                  | GridData.HORIZONTAL_ALIGN_END
                  | GridData.HORIZONTAL_ALIGN_FILL);
      gridData.grabExcessHorizontalSpace = true;
      gridData.widthHint = 70;
      bOk.setLayoutData(gridData);
      bOk.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              close(true);
            }
          });

      Button bCancel = new Button(shell, SWT.PUSH);
      Messages.setLanguageText(bCancel, "Button.cancel");
      gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
      gridData.grabExcessHorizontalSpace = false;
      gridData.widthHint = 70;
      bCancel.setLayoutData(gridData);
      bCancel.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              close(false);
            }
          });

      shell.setDefaultButton(bOk);

      shell.addListener(
          SWT.Traverse,
          new Listener() {
            public void handleEvent(Event e) {
              if (e.character == SWT.ESC) {
                close(false);
              }
            }
          });

      shell.pack();

      Utils.centreWindow(shell);

      shell.open();
    }
  protected Map getVersionCheckInfoSupport(
      String reason, boolean only_if_cached, boolean force, boolean v6) {
    try {
      synchronized (listeners) {
        if (REASON_UPDATE_CHECK_START.equals(reason)) {
          startCheckRan = true;
        }
        for (VersionCheckClientListener l : listeners) {
          l.versionCheckStarted(reason);
        }
      }
    } catch (Throwable t) {
      Debug.out(t);
    }
    if (v6) {

      if (enable_v6) {

        try {
          check_mon.enter();

          long time_diff = SystemTime.getCurrentTime() - last_check_time_v6;

          force = force || time_diff > CACHE_PERIOD || time_diff < 0;

          if (last_check_data_v6 == null || last_check_data_v6.size() == 0 || force) {
            // if we've never checked before then we go ahead even if the "only_if_cached"
            // flag is set as its had not chance of being cached yet!
            if (only_if_cached && last_check_data_v6 != null) {
              return (new HashMap());
            }
            try {
              last_check_data_v6 =
                  performVersionCheck(constructVersionCheckMessage(reason), true, true, true);

              if (last_check_data_v6 != null && last_check_data_v6.size() > 0) {

                COConfigurationManager.setParameter("versioncheck.cache.v6", last_check_data_v6);
              }
            } catch (SocketException t) {
              // internet is broken
              // Debug.out(t.getClass().getName() + ": " + t.getMessage());
            } catch (UnknownHostException t) {
              // dns is broken
              // Debug.out(t.getClass().getName() + ": " + t.getMessage());
            } catch (Throwable t) {
              Debug.out(t);
              last_check_data_v6 = new HashMap();
            }
          } else {
            Logger.log(
                new LogEvent(
                    LOGID,
                    "VersionCheckClient is using "
                        + "cached version check info. Using "
                        + last_check_data_v6.size()
                        + " reply keys."));
          }
        } finally {
          check_mon.exit();
        }
      }

      if (last_check_data_v6 == null) last_check_data_v6 = new HashMap();

      return last_check_data_v6;

    } else {

      try {
        check_mon.enter();

        long time_diff = SystemTime.getCurrentTime() - last_check_time_v4;

        force = force || time_diff > CACHE_PERIOD || time_diff < 0;

        if (last_check_data_v4 == null || last_check_data_v4.size() == 0 || force) {
          // if we've never checked before then we go ahead even if the "only_if_cached"
          // flag is set as its had not chance of being cached yet!
          if (only_if_cached && last_check_data_v4 != null) {
            return (new HashMap());
          }
          try {
            last_check_data_v4 =
                performVersionCheck(constructVersionCheckMessage(reason), true, true, false);

            if (last_check_data_v4 != null && last_check_data_v4.size() > 0) {

              COConfigurationManager.setParameter("versioncheck.cache.v4", last_check_data_v4);
            }

            // clear down any plugin-specific data that has successfully been sent to the version
            // server

            try {
              if (AzureusCoreFactory.isCoreAvailable()) {

                // installed plugin IDs
                PluginInterface[] plugins =
                    AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaces();

                for (int i = 0; i < plugins.length; i++) {

                  PluginInterface plugin = plugins[i];

                  Map data =
                      plugin
                          .getPluginconfig()
                          .getPluginMapParameter("plugin.versionserver.data", null);

                  if (data != null) {

                    plugin
                        .getPluginconfig()
                        .setPluginMapParameter("plugin.versionserver.data", new HashMap());
                  }
                }
              }
            } catch (Throwable e) {
            }
          } catch (UnknownHostException t) {
            // no internet
            Debug.outNoStack(
                "VersionCheckClient - " + t.getClass().getName() + ": " + t.getMessage());
          } catch (IOException t) {
            // General connection problem.
            Debug.outNoStack(
                "VersionCheckClient - " + t.getClass().getName() + ": " + t.getMessage());
          } catch (Throwable t) {
            Debug.out(t);
            last_check_data_v4 = new HashMap();
          }
        } else {
          if (Logger.isEnabled())
            Logger.log(
                new LogEvent(
                    LOGID,
                    "VersionCheckClient is using "
                        + "cached version check info. Using "
                        + last_check_data_v4.size()
                        + " reply keys."));
        }
      } finally {
        check_mon.exit();
      }

      if (last_check_data_v4 == null) last_check_data_v4 = new HashMap();

      last_feature_flag_cache_time = 0;

      return last_check_data_v4;
    }
  }
  /**
   * Construct the default version check message.
   *
   * @return message to send
   */
  public static Map constructVersionCheckMessage(String reason) {

    // only send if anonymous-check flag is not set

    boolean send_info = COConfigurationManager.getBooleanParameter("Send Version Info");

    Map message = new HashMap();

    // always send
    message.put("appid", SystemProperties.getApplicationIdentifier());
    message.put("appname", SystemProperties.getApplicationName());
    message.put("version", Constants.AZUREUS_VERSION);

    String sub_ver = Constants.AZUREUS_SUBVER;

    if (sub_ver.length() > 0) {
      message.put("subver", sub_ver);
    }

    if (COConfigurationManager.getBooleanParameter("Beta Programme Enabled")) {

      message.put("beta_prog", "true");
    }

    message.put("ui", COConfigurationManager.getStringParameter("ui", "unknown"));
    message.put("os", Constants.OSName);
    message.put("os_version", System.getProperty("os.version"));
    message.put(
        "os_arch", System.getProperty("os.arch")); // see http://lopica.sourceforge.net/os.html

    boolean using_phe =
        COConfigurationManager.getBooleanParameter("network.transport.encrypted.require");
    message.put("using_phe", using_phe ? new Long(1) : new Long(0));

    // swt stuff
    try {
      Class c = Class.forName("org.eclipse.swt.SWT");

      String swt_platform =
          (String) c.getMethod("getPlatform", new Class[] {}).invoke(null, new Object[] {});
      message.put("swt_platform", swt_platform);

      Integer swt_version =
          (Integer) c.getMethod("getVersion", new Class[] {}).invoke(null, new Object[] {});
      message.put("swt_version", new Long(swt_version.longValue()));

      if (send_info) {
        c = Class.forName("org.gudy.azureus2.ui.swt.mainwindow.MainWindow");
        if (c != null) {
          c.getMethod("addToVersionCheckMessage", new Class[] {Map.class})
              .invoke(null, new Object[] {message});
        }
      }
    } catch (ClassNotFoundException e) {
      /* ignore */
    } catch (NoClassDefFoundError er) {
      /* ignore */
    } catch (InvocationTargetException err) {
      /* ignore */
    } catch (Throwable t) {
      t.printStackTrace();
    }

    int last_send_time = COConfigurationManager.getIntParameter("Send Version Info Last Time", -1);
    int current_send_time = (int) (SystemTime.getCurrentTime() / 1000);
    COConfigurationManager.setParameter("Send Version Info Last Time", current_send_time);

    String id = COConfigurationManager.getStringParameter("ID", null);

    if (id != null && send_info) {
      message.put("id", id);

      try {
        byte[] id2 = CryptoManagerFactory.getSingleton().getSecureID();

        message.put("id2", id2);

      } catch (Throwable e) {
      }

      if (last_send_time != -1 && last_send_time < current_send_time) {
        // time since last
        message.put("tsl", new Long(current_send_time - last_send_time));
      }

      message.put("reason", reason);

      String java_version = System.getProperty("java.version");
      if (java_version == null) {
        java_version = "unknown";
      }
      message.put("java", java_version);

      String java_vendor = System.getProperty("java.vm.vendor");
      if (java_vendor == null) {
        java_vendor = "unknown";
      }
      message.put("javavendor", java_vendor);

      long max_mem = Runtime.getRuntime().maxMemory() / (1024 * 1024);
      message.put("javamx", new Long(max_mem));

      String java_rt_name = System.getProperty("java.runtime.name");
      if (java_rt_name != null) {
        message.put("java_rt_name", java_rt_name);
      }

      String java_rt_version = System.getProperty("java.runtime.version");
      if (java_rt_version != null) {
        message.put("java_rt_version", java_rt_version);
      }

      OverallStats stats = StatsFactory.getStats();

      if (stats != null) {

        // long total_bytes_downloaded 	= stats.getDownloadedBytes();
        // long total_bytes_uploaded		= stats.getUploadedBytes();
        long total_uptime = stats.getTotalUpTime();

        // removed due to complaints about anonymous stats collection
        // message.put( "total_bytes_downloaded", new Long( total_bytes_downloaded ) );
        // message.put( "total_bytes_uploaded", new Long( total_bytes_uploaded ) );
        message.put("total_uptime", new Long(total_uptime));
        // message.put( "dlstats", stats.getDownloadStats());
      }

      try {
        NetworkAdminASN current_asn = NetworkAdmin.getSingleton().getCurrentASN();

        String as = current_asn.getAS();

        message.put("ip_as", current_asn.getAS());

        String asn = current_asn.getASName();

        if (asn.length() > 64) {

          asn = asn.substring(0, 64);
        }

        message.put("ip_asn", asn);

      } catch (Throwable e) {

        Debug.out(e);
      }

      // send locale, so we can determine which languages need attention
      message.put("locale", Locale.getDefault().toString());
      String originalLocale =
          System.getProperty("user.language") + "_" + System.getProperty("user.country");
      String variant = System.getProperty("user.variant");
      if (variant != null && variant.length() > 0) {
        originalLocale += "_" + variant;
      }
      message.put("orig_locale", originalLocale);

      // We may want to reply differently if the user is in Beginner mode vs Advanced
      message.put("user_mode", COConfigurationManager.getIntParameter("User Mode", -1));

      Set<String> features = UtilitiesImpl.getFeaturesInstalled();

      if (features.size() > 0) {

        String str = "";

        for (String f : features) {
          str += (str.length() == 0 ? "" : ",") + f;
        }

        message.put("vzfeatures", str);
      }

      try {
        if (AzureusCoreFactory.isCoreAvailable()) {

          // installed plugin IDs
          PluginInterface[] plugins =
              AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaces();

          List pids = new ArrayList();

          List vs_data = new ArrayList();

          for (int i = 0; i < plugins.length; i++) {

            PluginInterface plugin = plugins[i];

            String pid = plugin.getPluginID();

            String info = plugin.getPluginconfig().getPluginStringParameter("plugin.info");

            // filter out built-in and core ones
            if ((info != null && info.length() > 0)
                || (!pid.startsWith("<")
                    && !pid.startsWith("azbp")
                    && !pid.startsWith("azupdater")
                    && !pid.startsWith("azplatform")
                    && !pids.contains(pid))) {

              if (info != null && info.length() > 0) {

                if (info.length() < 256) {

                  pid += ":" + info;

                } else {

                  Debug.out("Plugin '" + pid + "' reported excessive info string '" + info + "'");
                }
              }

              pids.add(pid);
            }

            Map data =
                plugin.getPluginconfig().getPluginMapParameter("plugin.versionserver.data", null);

            if (data != null) {

              Map payload = new HashMap();

              byte[] data_bytes = BEncoder.encode(data);

              if (data_bytes.length > 16 * 1024) {

                Debug.out(
                    "Plugin '"
                        + pid
                        + "' reported excessive version server data (length="
                        + data_bytes.length
                        + ")");

                payload.put("error", "data too long: " + data_bytes.length);

              } else {

                payload.put("data", data_bytes);
              }

              payload.put("id", pid);
              payload.put("version", plugin.getPluginVersion());

              vs_data.add(payload);
            }
          }
          message.put("plugins", pids);

          if (vs_data.size() > 0) {

            message.put("plugin_data", vs_data);
          }
        }
      } catch (Throwable e) {

        Debug.out(e);
      }
    }

    return message;
  }