示例#1
0
  public static byte[] encode(Map object, boolean url_encode) throws IOException {

    BEncoder encoder = new BEncoder(url_encode);

    encoder.encodeObject(object);

    return (encoder.toByteArray());
  }
示例#2
0
  public <T> void setPersistentMapProperty(String prop, Map<String, T> value) {
    boolean dirty = false;

    synchronized (persistent_properties) {
      Map<String, T> existing = getPersistentMapProperty(prop, null);

      if (!BEncoder.mapsAreIdentical(value, existing)) {

        try {
          if (value == null) {

            persistent_properties.remove(prop);

          } else {

            persistent_properties.put(prop, value);
          }

          dirty = true;

        } catch (Throwable e) {

          Debug.printStackTrace(e);
        }
      }
    }

    if (dirty) {

      setDirty();
    }
  }
  @Override
  public DirectByteBuffer[] getData() {
    try {
      if (buffer == null) {
        if (msg_type == REQUEST_MESSAGE_TYPE_ID) {
          Map<Object, Object> map = new HashMap<Object, Object>();
          map.put("msg_type", msg_type);
          map.put("piece", piece);
          buffer =
              MessagingUtil.convertPayloadToBencodedByteStream(
                  map, DirectByteBuffer.AL_MSG_UT_METADATA);
        } else if (msg_type == DATA_MESSAGE_TYPE_ID) {
          Map<Object, Object> map = new HashMap<Object, Object>();
          map.put("msg_type", msg_type);
          map.put("piece", piece);
          map.put("total_size", total_size);
          byte[] mapPayload = BEncoder.encode(map);
          buffer =
              DirectByteBufferPool.getBuffer(
                  DirectByteBuffer.AL_MSG_UT_METADATA, mapPayload.length + metadata.length);
          buffer.put(DirectByteBuffer.SS_MSG, mapPayload);
          buffer.put(DirectByteBuffer.SS_MSG, metadata);
          buffer.flip(DirectByteBuffer.SS_MSG);
        } else if (msg_type == REJECT_MESSAGE_TYPE_ID) {
          Map<Object, Object> map = new HashMap<Object, Object>();
          map.put("msg_type", msg_type);
          map.put("piece", piece);
          buffer =
              MessagingUtil.convertPayloadToBencodedByteStream(
                  map, DirectByteBuffer.AL_MSG_UT_METADATA);
        } else {
          if (Logger.isEnabled()) {
            Logger.log(
                new LogEvent(
                    LOGID, LogEvent.LT_ERROR, "METADATA (UT): No valid msg_type=" + msg_type));
          }
          return null;
        }
      }

      return new DirectByteBuffer[] {buffer};
    } catch (Throwable e) {
      // what is the best way to handle this error?
      if (Logger.isEnabled()) {
        Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "METADATA (UT)", e));
      }
      return new DirectByteBuffer[0];
    }
  }
  private Map executeHTTP(Map data_to_send, boolean v6) throws Exception {

    if (v6 && !enable_v6) {

      throw (new Exception("IPv6 is disabled"));
    }

    String host = getHost(v6, HTTP_SERVER_ADDRESS_V6, HTTP_SERVER_ADDRESS_V4);

    if (Logger.isEnabled())
      Logger.log(
          new LogEvent(
              LOGID,
              "VersionCheckClient retrieving "
                  + "version information from "
                  + host
                  + ":"
                  + HTTP_SERVER_PORT
                  + " via HTTP"));

    String url_str =
        "http://"
            + (v6 ? UrlUtils.convertIPV6Host(host) : host)
            + (HTTP_SERVER_PORT == 80 ? "" : (":" + HTTP_SERVER_PORT))
            + "/version?";

    url_str +=
        URLEncoder.encode(new String(BEncoder.encode(data_to_send), "ISO-8859-1"), "ISO-8859-1");

    URL url = new URL(url_str);

    HttpURLConnection url_connection = (HttpURLConnection) url.openConnection();

    url_connection.connect();

    try {
      InputStream is = url_connection.getInputStream();

      Map reply = BDecoder.decode(new BufferedInputStream(is));

      preProcessReply(reply, v6);

      return (reply);

    } finally {

      url_connection.disconnect();
    }
  }
  @Override
  public Message deserialize(DirectByteBuffer data, byte version) throws MessageException {
    try {
      int pos = data.position(DirectByteBuffer.SS_MSG);
      byte[] raw = new byte[data.remaining(DirectByteBuffer.SS_MSG)];
      data.get(DirectByteBuffer.SS_MSG, raw);
      data.position(DirectByteBuffer.SS_MSG, pos);
      Map<?, ?> map = MessagingUtil.convertBencodedByteStreamToPayload(data, 2, getID());

      int msg_type = ((Long) map.get("msg_type")).intValue();
      int piece = ((Long) map.get("piece")).intValue();
      if (msg_type == REQUEST_MESSAGE_TYPE_ID) {
        return new UTMetadata(msg_type, piece, 0, null, (byte) 1);
      } else if (msg_type == DATA_MESSAGE_TYPE_ID) {
        int total_size = ((Long) map.get("total_size")).intValue();
        int offset = BEncoder.encode(map).length;
        byte[] metadata = new byte[raw.length - offset];
        System.arraycopy(raw, offset, metadata, 0, metadata.length);
        return new UTMetadata(msg_type, piece, total_size, metadata, (byte) 1);
      } else if (msg_type == REJECT_MESSAGE_TYPE_ID) {
        return new UTMetadata(msg_type, piece, 0, null, (byte) 1);
      }

      // what is the best way to handle this error?
      if (Logger.isEnabled()) {
        Logger.log(
            new LogEvent(LOGID, LogEvent.LT_ERROR, "METADATA (UT): No valid msg_type=" + msg_type));
      }

      return null;
    } catch (Throwable e) {
      // what is the best way to handle this error?
      if (Logger.isEnabled()) {
        Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "METADATA (UT)", e));
      }
      return null;
    }
  }
  private String getHTTPGetString(Map content, boolean for_proxy, boolean v6) {
    String host = getHost(v6, HTTP_SERVER_ADDRESS_V6, HTTP_SERVER_ADDRESS_V4);

    String get_str =
        "GET "
            + (for_proxy
                ? ("http://"
                    + (v6 ? UrlUtils.convertIPV6Host(host) : host)
                    + ":"
                    + HTTP_SERVER_PORT)
                : "")
            + "/version?";

    try {
      get_str +=
          URLEncoder.encode(new String(BEncoder.encode(content), "ISO-8859-1"), "ISO-8859-1");

    } catch (Throwable e) {
    }

    get_str += " HTTP/1.1" + "\015\012" + "\015\012";

    return (get_str);
  }
  public byte[] exportToBytes() throws IOException {

    return (BEncoder.encode(exportToMap()));
  }
  public void dumpConfigChanges(IndentWriter writer) {
    ConfigurationDefaults defaults = ConfigurationDefaults.getInstance();

    Set<String> keys =
        new TreeSet<String>(
            new Comparator<String>() {
              public int compare(String o1, String o2) {
                return (o1.compareToIgnoreCase(o2));
              }
            });

    keys.addAll(propertiesMap.keySet());

    Iterator<String> it = keys.iterator();

    while (it.hasNext()) {

      String key = it.next();

      // don't dump crypto stuff

      if (ignoreKeyForDump(key)) {

        continue;
      }

      Object value = propertiesMap.get(key);

      boolean bParamExists = defaults.doesParameterDefaultExist(key.toString());

      if (bParamExists) {

        Object def = defaults.getParameter(key);

        if (def != null && value != null) {

          if (!BEncoder.objectsAreIdentical(def, value)) {

            if (value instanceof Long) {

              writer.println(key + "=" + value);

            } else if (value instanceof List) {

              writer.println(
                  key + "=" + BDecoder.decodeStrings((List) BEncoder.clone(value)) + "[list]");

            } else if (value instanceof Map) {

              writer.println(
                  key + "=" + BDecoder.decodeStrings((Map) BEncoder.clone(value)) + "[map]");

            } else if (value instanceof byte[]) {

              byte[] b = (byte[]) value;

              boolean hex = false;

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

                char c = (char) b[i];

                if (!(Character.isLetterOrDigit(c)
                    || "\\ `¬\"£$%^&*()-_=+[{]};:'@#~,<.>/?'".indexOf(c) != -1)) {

                  hex = true;

                  break;
                }
              }
              writer.println(
                  key + "=" + (hex ? ByteFormatter.nicePrint(b) : bytesToString((byte[]) value)));

            } else {

              writer.println(key + "=" + value + "[unknown]");
            }
          }
        }
      }
    }
  }
  public void generate(IndentWriter writer) {
    writer.println("Configuration Details");

    try {
      writer.indent();

      writer.println(
          "version=" + Constants.AZUREUS_VERSION + ", subver=" + Constants.AZUREUS_SUBVER);

      writer.println("System Properties");

      try {
        writer.indent();

        Properties props = System.getProperties();

        Iterator it = new TreeSet(props.keySet()).iterator();

        while (it.hasNext()) {

          String key = (String) it.next();

          writer.println(key + "=" + props.get(key));
        }
      } finally {

        writer.exdent();
      }

      writer.println("Environment");

      try {
        writer.indent();

        Map<String, String> env = System.getenv();

        if (env == null) {

          writer.println("Not supported");

        } else {

          Iterator it = new TreeSet(env.keySet()).iterator();

          while (it.hasNext()) {

            String key = (String) it.next();

            writer.println(key + "=" + env.get(key));
          }
        }
      } finally {

        writer.exdent();
      }

      writer.println("Azureus Config");

      ConfigurationDefaults defaults = ConfigurationDefaults.getInstance();

      try {
        writer.indent();

        Set<String> keys =
            new TreeSet<String>(
                new Comparator<String>() {
                  public int compare(String o1, String o2) {
                    return (o1.compareToIgnoreCase(o2));
                  }
                });

        keys.addAll(propertiesMap.keySet());

        Iterator<String> it = keys.iterator();

        while (it.hasNext()) {

          String key = it.next();

          // don't dump crypto stuff

          if (ignoreKeyForDump(key)) {

            continue;
          }

          Object value = propertiesMap.get(key);

          boolean bParamExists = defaults.doesParameterDefaultExist(key.toString());

          if (!bParamExists) {

            key = "[NoDef] " + key;
          } else {

            Object def = defaults.getParameter(key);

            if (def != null && value != null) {

              if (!BEncoder.objectsAreIdentical(def, value)) {

                key = "-> " + key;
              }
            }
          }

          if (value instanceof Long) {

            writer.println(key + "=" + value);

          } else if (value instanceof List) {

            writer.println(
                key + "=" + BDecoder.decodeStrings((List) BEncoder.clone(value)) + "[list]");

          } else if (value instanceof Map) {

            writer.println(
                key + "=" + BDecoder.decodeStrings((Map) BEncoder.clone(value)) + "[map]");

          } else if (value instanceof byte[]) {

            byte[] b = (byte[]) value;

            boolean hex = false;

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

              char c = (char) b[i];

              if (!(Character.isLetterOrDigit(c)
                  || "\\ `¬\"£$%^&*()-_=+[{]};:'@#~,<.>/?'".indexOf(c) != -1)) {

                hex = true;

                break;
              }
            }
            writer.println(
                key + "=" + (hex ? ByteFormatter.nicePrint(b) : bytesToString((byte[]) value)));

          } else {

            writer.println(key + "=" + value + "[unknown]");
          }
        }
      } finally {

        writer.exdent();
      }
    } finally {

      writer.exdent();
    }
  }
  /**
   * 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;
  }