protected void setupActivationCheck(int delay) {
    if (announcers.size() > activated.size()) {

      event =
          SimpleTimer.addEvent(
              "TRMuxer:check",
              SystemTime.getOffsetTime(delay),
              new TimerEventPerformer() {
                public void perform(TimerEvent event) {
                  checkActivation(false);
                }
              });
    }
  }
Exemplo n.º 2
0
 public void refresh() {
   if (!everRefreshed) {
     everRefreshed = true;
     timerEvent =
         SimpleTimer.addPeriodicEvent(
             "TopBarSpeedGraphicView",
             1000,
             new TimerEventPerformer() {
               public void perform(TimerEvent event) {
                 if (downSpeedCanvas.isDisposed()) {
                   timerEvent.cancel();
                 } else {
                   periodicUpdate();
                 }
               }
             });
   }
   downSpeedGraphic.refresh();
 }
  protected synchronized void readConfigValues() {
    config_enabled = COConfigurationManager.getBooleanParameter("Stats Enable");

    config_period = COConfigurationManager.getIntParameter("Stats Period");

    config_dir = COConfigurationManager.getStringParameter("Stats Dir");

    config_file = COConfigurationManager.getStringParameter("Stats File");

    if (config_enabled) {
      long targetFrequency =
          1000 * (config_period < DEFAULT_SLEEP_PERIOD ? config_period : DEFAULT_SLEEP_PERIOD);
      if (event != null && event.getFrequency() != targetFrequency) {
        event.cancel();
        event = null;
      }

      if (event == null) event = SimpleTimer.addPeriodicEvent("StatsWriter", targetFrequency, this);

    } else if (event != null) {
      event.cancel();
      event = null;
    }
  }
    protected Searcher(boolean _persistent, boolean _async) throws DeviceManagerException {

      try {
        int last_port = COConfigurationManager.getIntParameter("devices.tivo.net.tcp.port", 0);

        if (last_port > 0) {

          try {
            ServerSocket ss = new ServerSocket(last_port);

            ss.setReuseAddress(true);

            ss.close();

          } catch (Throwable e) {

            last_port = 0;
          }
        }

        twc = plugin_interface.getTracker().createWebContext(last_port, Tracker.PR_HTTP);

        tcp_port = twc.getURLs()[0].getPort();

        COConfigurationManager.setParameter("devices.tivo.net.tcp.port", tcp_port);

        twc.addPageGenerator(
            new TrackerWebPageGenerator() {
              public boolean generate(
                  TrackerWebPageRequest request, TrackerWebPageResponse response)
                  throws IOException {
                String id = (String) request.getHeaders().get("tsn");

                if (id == null) {

                  id = (String) request.getHeaders().get("tivo_tcd_id");
                }

                if (id != null && is_enabled) {

                  persistent = true;

                  DeviceTivo tivo =
                      foundTiVo(request.getClientAddress2().getAddress(), id, null, null);

                  return (tivo.generate(request, response));
                }

                return (false);
              }
            });

        control_socket = new DatagramSocket(null);

        control_socket.setReuseAddress(true);

        try {
          control_socket.setSoTimeout(60 * 1000);

        } catch (Throwable e) {
        }

        InetAddress bind = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress();

        control_socket.bind(new InetSocketAddress(bind, CONTROL_PORT));

        timer_event =
            SimpleTimer.addPeriodicEvent(
                "Tivo:Beacon",
                60 * 1000,
                new TimerEventPerformer() {
                  public void perform(TimerEvent event) {
                    if (!(manager_destroyed || search_destroyed)) {

                      sendBeacon();
                    }

                    // see if time to auto-shutdown searching

                    if (!persistent) {

                      synchronized (DeviceTivoManager.this) {
                        if (SystemTime.getMonotonousTime() - start >= LIFE_MILLIS) {

                          log("Terminating search, no devices found");

                          current_search = null;

                          destroy();
                        }
                      }
                    }
                  }
                });

        final AESemaphore start_sem = new AESemaphore("TiVo:CtrlListener");

        new AEThread2("TiVo:CtrlListener", true) {
          public void run() {
            start_sem.release();

            long successful_accepts = 0;
            long failed_accepts = 0;

            while (!(manager_destroyed || search_destroyed)) {

              try {
                byte[] buf = new byte[8192];

                DatagramPacket packet = new DatagramPacket(buf, buf.length);

                control_socket.receive(packet);

                successful_accepts++;

                failed_accepts = 0;

                if (receiveBeacon(packet.getAddress(), packet.getData(), packet.getLength())) {

                  persistent = true;
                }

              } catch (SocketTimeoutException e) {

              } catch (Throwable e) {

                if (control_socket != null && !search_destroyed && !manager_destroyed) {

                  failed_accepts++;

                  log("UDP receive on port " + CONTROL_PORT + " failed", e);
                }

                if ((failed_accepts > 100 && successful_accepts == 0) || failed_accepts > 1000) {

                  log("    too many failures, abandoning");

                  break;
                }
              }
            }
          }
        }.start();

        if (_async) {

          new DelayedEvent(
              "search:delay",
              5000,
              new AERunnable() {
                public void runSupport() {
                  sendBeacon();
                }
              });
        } else {

          start_sem.reserve(5000);

          sendBeacon();
        }

        log("Initiated device search");

      } catch (Throwable e) {

        log("Failed to initialise search", e);

        destroy();

        throw (new DeviceManagerException("Creation failed", e));
      }
    }
  private void sessionStart() {
    OverallStatsImpl stats = (OverallStatsImpl) StatsFactory.getStats();

    synchronized (this) {
      if (closing) {

        return;
      }

      boolean enabled = COConfigurationManager.getBooleanParameter("long.term.stats.enable");

      if (active || !enabled) {

        return;
      }

      active = true;

      long[] snap = stats.getLastSnapshot();

      ss_d_received = gm_stats.getTotalDataBytesReceived();
      ss_p_received = gm_stats.getTotalProtocolBytesReceived();

      ss_d_sent = gm_stats.getTotalDataBytesSent();
      ss_p_sent = gm_stats.getTotalProtocolBytesSent();

      ss_dht_sent = 0;
      ss_dht_received = 0;

      if (core.isStarted()) {

        DHT[] dhts = getDHTs();

        if (dhts != null) {

          for (DHT dht : dhts) {

            DHTTransportStats dht_stats = dht.getTransport().getStats();

            ss_dht_sent += dht_stats.getBytesSent();
            ss_dht_received += dht_stats.getBytesReceived();
          }
        }
      }

      st_p_sent = snap[0] + (ss_p_sent - snap[6]);
      st_d_sent = snap[1] + (ss_d_sent - snap[7]);
      st_p_received = snap[2] + (ss_p_received - snap[8]);
      st_d_received = snap[3] + (ss_d_received - snap[9]);
      st_dht_sent = snap[4] + (ss_dht_sent - snap[10]);
      st_dht_received = snap[5] + (ss_dht_received - snap[11]);

      write(
          RT_SESSION_START,
          new long[] {
            st_p_sent, st_d_sent, st_p_received, st_d_received, st_dht_sent, st_dht_received
          });

      if (event == null) { // should always be null but hey ho

        event =
            SimpleTimer.addPeriodicEvent(
                "LongTermStats",
                MIN_IN_MILLIS,
                new TimerEventPerformer() {
                  public void perform(TimerEvent event) {
                    updateStats();
                  }
                });
      }
    }
  }
Exemplo n.º 6
0
  public void setSpeedTester(DHTSpeedTester _tester) {
    if (speed_tester != null) {

      if (!emulated_ping_source) {

        Debug.out("speed tester already set!");
      }

      return;
    }

    COConfigurationManager.setParameter(CONFIG_AVAIL, true);

    speed_tester = _tester;

    speed_tester.addListener(
        new DHTSpeedTesterListener() {
          private DHTSpeedTesterContact[] last_contact_group = new DHTSpeedTesterContact[0];

          public void contactAdded(DHTSpeedTesterContact contact) {
            if (core.getInstanceManager().isLANAddress(contact.getAddress().getAddress())) {

              contact.destroy();

            } else {
              log("activePing: " + contact.getString());

              contact.setPingPeriod(CONTACT_PING_SECS);

              synchronized (contacts) {
                pingContact source = new pingContact(contact);

                contacts.put(contact, source);

                contacts_array = new pingContact[contacts.size()];

                contacts.values().toArray(contacts_array);

                total_contacts++;

                provider.pingSourceFound(source, total_contacts > CONTACT_NUMBER);
              }

              contact.addListener(
                  new DHTSpeedTesterContactListener() {
                    public void ping(DHTSpeedTesterContact contact, int round_trip_time) {}

                    public void pingFailed(DHTSpeedTesterContact contact) {}

                    public void contactDied(DHTSpeedTesterContact contact) {
                      log("deadPing: " + contact.getString());

                      synchronized (contacts) {
                        pingContact source = (pingContact) contacts.remove(contact);

                        if (source != null) {

                          contacts_array = new pingContact[contacts.size()];

                          contacts.values().toArray(contacts_array);

                          provider.pingSourceFailed(source);
                        }
                      }
                    }
                  });
            }
          }

          public void resultGroup(DHTSpeedTesterContact[] st_contacts, int[] round_trip_times) {
            if (!enabled) {

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

                st_contacts[i].destroy();
              }

              return;
            }

            boolean sources_changed = false;

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

              boolean found = false;

              for (int j = 0; j < last_contact_group.length; j++) {

                if (st_contacts[i] == last_contact_group[j]) {

                  found = true;

                  break;
                }
              }

              if (!found) {

                sources_changed = true;

                break;
              }
            }

            last_contact_group = st_contacts;

            pingContact[] sources = new pingContact[st_contacts.length];

            boolean miss = false;

            int worst_value = -1;

            int num_values = 0;
            int total = 0;

            synchronized (contacts) {
              for (int i = 0; i < st_contacts.length; i++) {

                pingContact source = sources[i] = (pingContact) contacts.get(st_contacts[i]);

                if (source != null) {

                  int rtt = round_trip_times[i];

                  if (rtt > 0) {

                    if (rtt > worst_value) {

                      worst_value = rtt;
                    }

                    num_values++;

                    total += rtt;
                  }

                  source.setPingTime(rtt);

                } else {

                  miss = true;
                }
              }
            }

            if (miss) {

              Debug.out("Auto-speed: source missing");

            } else {

              provider.calculate(sources);

              // remove worst value if we have > 1

              if (num_values > 1) {

                total -= worst_value;
                num_values--;
              }

              if (num_values > 0) {

                addPingHistory(total / num_values, sources_changed);
              }
            }
          }
        });

    SimpleTimer.addPeriodicEvent(
        "SpeedManager:stats",
        SpeedManagerAlgorithmProvider.UPDATE_PERIOD_MILLIS,
        new TimerEventPerformer() {
          public void perform(TimerEvent event) {
            if (enabled) {

              provider.updateStats();
            }
          }
        });
  }
Exemplo n.º 7
0
  public SpeedManagerImpl(AzureusCore _core, SpeedManagerAdapter _adapter) {
    core = _core;
    adapter = _adapter;

    AEDiagnostics.addEvidenceGenerator(this);

    logger = AEDiagnostics.getLogger("SpeedMan");

    ping_mapper = new SpeedManagerPingMapperImpl(this, "Var", LONG_PERIOD_TICKS, true, false);

    if (Constants.isCVSVersion()) {

      SpeedManagerPingMapperImpl pm2 =
          new SpeedManagerPingMapperImpl(this, "Abs", LONG_PERIOD_TICKS, false, false);

      ping_mappers = new SpeedManagerPingMapperImpl[] {pm2, ping_mapper};

    } else {

      ping_mappers = new SpeedManagerPingMapperImpl[] {ping_mapper};
    }

    final File config_dir = new File(SystemProperties.getUserPath(), "net");

    if (!config_dir.exists()) {

      config_dir.mkdirs();
    }

    NetworkAdmin.getSingleton()
        .addAndFirePropertyChangeListener(
            new NetworkAdminPropertyChangeListener() {
              public void propertyChanged(String property) {
                if (property == NetworkAdmin.PR_AS) {

                  NetworkAdminASN net_asn = NetworkAdmin.getSingleton().getCurrentASN();

                  String as = net_asn.getAS();

                  if (as.length() == 0) {

                    as = "default";
                  }

                  File history =
                      new File(config_dir, "pm_" + FileUtil.convertOSSpecificChars(as) + ".dat");

                  ping_mapper.loadHistory(history);

                  asn = net_asn.getASName();

                  if (asn.length() == 0) {

                    asn = "Unknown";
                  }

                  informListeners(SpeedManagerListener.PR_ASN);
                }
              }
            });

    core.addLifecycleListener(
        new AzureusCoreLifecycleAdapter() {
          public void stopping(AzureusCore core) {
            ping_mapper.saveHistory();
          }
        });

    COConfigurationManager.addAndFireParameterListener(
        CONFIG_VERSION,
        new ParameterListener() {
          public void parameterChanged(final String name) {
            dispatcher.dispatch(
                new AERunnable() {
                  public void runSupport() {
                    boolean do_reset = provider_version == -1;

                    int version = COConfigurationManager.getIntParameter(name);

                    if (version != provider_version) {

                      provider_version = version;

                      if (isEnabled()) {

                        setEnabledSupport(false);

                        setEnabledSupport(true);
                      }
                    }

                    if (do_reset) {

                      enableOrAlgChanged();
                    }
                  }
                });
          }
        });

    COConfigurationManager.setParameter(CONFIG_AVAIL, false);

    SimpleTimer.addPeriodicEvent(
        "SpeedManager:timer",
        UPDATE_PERIOD_MILLIS,
        new TimerEventPerformer() {
          private int tick_count;

          public void perform(TimerEvent event) {
            // if enabled the ping stream drives the stats update for the ping mappers
            // When not enabled we do it here instead

            if (!enabled || contacts_array.length == 0) {

              int x =
                  (adapter.getCurrentDataUploadSpeed(SPEED_AVERAGE_PERIOD)
                      + adapter.getCurrentProtocolUploadSpeed(SPEED_AVERAGE_PERIOD));
              int y =
                  (adapter.getCurrentDataDownloadSpeed(SPEED_AVERAGE_PERIOD)
                      + adapter.getCurrentProtocolDownloadSpeed(SPEED_AVERAGE_PERIOD));

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

                ping_mappers[i].addSpeed(x, y);
              }
            }

            tick_count++;

            if (tick_count % SAVE_PERIOD_TICKS == 0) {

              ping_mapper.saveHistory();
            }
          }
        });

    emulated_ping_source = false;

    if (emulated_ping_source) {

      Debug.out("Emulated ping source!!!!");

      setSpeedTester(new TestPingSourceRandom(this));
    }
  }
  private PeerNATTraverser(AzureusCore core) {
    nat_traverser = core.getNATTraverser();

    nat_traverser.registerHandler(this);

    SimpleTimer.addPeriodicEvent(
        "PeerNAT:stats",
        TIMER_PERIOD,
        new TimerEventPerformer() {
          private int ticks;

          public void perform(TimerEvent event) {
            ticks++;

            List to_run = null;

            synchronized (initiators) {
              if (ticks % BLOOM_REBUILD_TICKS == 0) {

                int size = negative_result_bloom.getEntryCount();

                if (Logger.isEnabled()) {

                  if (size > 0) {

                    Logger.log(
                        new LogEvent(LOGID, "PeerNATTraverser: negative bloom size = " + size));
                  }
                }

                negative_result_bloom = BloomFilterFactory.createAddOnly(BLOOM_SIZE);
              }

              if (ticks % STATS_TICK_COUNT == 0) {

                String msg =
                    "NAT traversal stats: active="
                        + active_requests.size()
                        + ",pending="
                        + pending_requests.size()
                        + ",attempted="
                        + attempted_count
                        + ",no rendezvous="
                        + failed_no_rendezvous
                        + ",negative bloom="
                        + failed_negative_bloom
                        + ",successful="
                        + success_count;

                // System.out.println( msg );

                if (Logger.isEnabled()) {
                  Logger.log(new LogEvent(LOGID, msg));
                }
              }

              int used = 0;

              for (int i = 0; i < active_requests.size(); i++) {

                used += ((PeerNATTraversal) active_requests.get(i)).getTimeUsed();
              }

              usage_average.addValue(used);

              int usage = (int) usage_average.getAverage();

              if (usage > MAX_USAGE_PER_MIN) {

                return;
              }

              // System.out.println( "usage = " + usage );

              while (true) {

                if (pending_requests.size() == 0 || active_requests.size() >= MAX_ACTIVE_REQUESTS) {

                  break;
                }

                // TODO: prioritisation based on initiator connections etc?

                PeerNATTraversal traversal = (PeerNATTraversal) pending_requests.removeFirst();

                active_requests.add(traversal);

                if (to_run == null) {

                  to_run = new ArrayList();
                }

                to_run.add(traversal);

                attempted_count++;
              }
            }

            if (to_run != null) {

              for (int i = 0; i < to_run.size(); i++) {

                PeerNATTraversal traversal = (PeerNATTraversal) to_run.get(i);

                boolean bad = false;

                synchronized (initiators) {
                  if (negative_result_bloom.contains(traversal.getTarget().toString().getBytes())) {

                    bad = true;

                    failed_negative_bloom++;
                  }
                }

                if (bad) {

                  removeRequest(traversal, OUTCOME_FAILED_OTHER);

                  traversal.getAdapter().failed();
                } else {

                  traversal.run();
                }
              }
            }
          }
        });
  }
Exemplo n.º 9
0
  private static void updateMetaData_handleReply(
      TOTorrent torrent, String hash, String replyType, Map mapHashes) {
    if (hash == null && torrent != null) {
      try {
        hash = torrent.getHashWrapper().toBase32String();
      } catch (Exception e) {
      }
    }

    GlobalManager gm = AzureusCoreFactory.getSingleton().getGlobalManager();
    DownloadManager dm = gm.getDownloadManager(new HashWrapper(Base32.decode(hash)));

    if (torrent == null && dm != null) {
      torrent = dm.getTorrent();
    }
    Map contentMap = PlatformTorrentUtils.getContentMap(torrent);

    final TOTorrent torrentFinal = torrent;

    if (replyType.equals(PlatformMessenger.REPLY_EXCEPTION)) {
      if (torrent != null) {
        // try again in a bit
        log(torrent, "Exception, retrying later");
        SimpleTimer.addEvent(
            "Update MD Retry",
            SystemTime.getCurrentTime() + RETRY_METADATA,
            new TimerEventPerformer() {
              public void perform(TimerEvent event) {
                log(torrentFinal, "retry time");
                PlatformTorrentUtils.updateMetaData(torrentFinal, 15000);
              }
            });
      }
    } else {
      Map jsonMapMetaData = hash == null ? null : (Map) mapHashes.get(hash);
      if (jsonMapMetaData != null) {
        long oldLastUpdated = getContentLastUpdated(torrent);
        long expireyMins = 0;

        for (Iterator iter = jsonMapMetaData.keySet().iterator(); iter.hasNext(); ) {
          String key = (String) iter.next();
          Object value = jsonMapMetaData.get(key);

          if (value == null || value.equals(null)) {
            contentMap.remove(key);
          } else if ((key.equals("Thumbnail") || key.endsWith(".B64")) && value instanceof String) {
            contentMap.put(key, Base64.decode((String) value));
          } else if (key.equals("expires-in-mins") && value instanceof Long) {
            expireyMins = ((Long) value).longValue();
          } else {
            contentMap.put(key, value);
          }
          writeTorrentIfExists(torrent);
        }

        // crappy way of updating the display name
        if (dm != null) {
          String title = PlatformTorrentUtils.getContentTitle(torrent);
          if (title != null
              && title.length() > 0
              && dm.getDownloadState().getDisplayName() == null) {
            dm.getDownloadState().setDisplayName(title);
          }
        }
        triggerMetaDataUpdateListeners(torrent);

        if (torrent != null) {
          // setup next refresh

          long refreshOn;
          if (expireyMins > 0) {
            refreshOn = SystemTime.getCurrentTime() + (expireyMins * 60 * 1000L);
          } else {
            long newLastUpdated = getContentLastUpdated(torrent);

            long diff = newLastUpdated - oldLastUpdated;
            log(
                torrent,
                "Last Updated: new "
                    + new Date(newLastUpdated)
                    + ";old "
                    + new Date(oldLastUpdated)
                    + ";diff="
                    + diff);
            if (diff > 0 && oldLastUpdated != 0) {
              diff *= 2;
              if (diff < MIN_MD_REFRESH_MS) {
                diff = MIN_MD_REFRESH_MS;
              } else if (diff > MAX_MD_REFRESH_MS) {
                diff = MAX_MD_REFRESH_MS;
              }
              refreshOn = SystemTime.getOffsetTime(diff);
            } else {
              refreshOn = SystemTime.getCurrentTime() + (7 * 24 * 60 * 60 * 1000L);
            }
          }

          log(torrent, "got MD. Next refresh in " + (refreshOn - SystemTime.getCurrentTime()));
          setMetaDataRefreshOn(torrent, refreshOn);
          SimpleTimer.addEvent(
              "Update MD",
              refreshOn,
              new TimerEventPerformer() {
                public void perform(TimerEvent event) {
                  PlatformTorrentUtils.updateMetaData(torrentFinal, 15000);
                }
              });
        }
      } else if (torrent != null) {
        long refreshOn = SystemTime.getCurrentTime() + (30 * 24 * 60 * 60 * 1000L);
        setMetaDataRefreshOn(torrent, refreshOn);
        log(torrent, "no hash in reply. Next refresh on " + new Date(refreshOn));
      }
    }
  }
Exemplo n.º 10
0
  private void start() {
    synchronized (this) {
      if (started) {

        return;
      }

      started = true;
    }

    N_3072 =
        fromHex(
            "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1 29024E08"
                + "8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD EF9519B3 CD3A431B"
                + "302B0A6D F25F1437 4FE1356D 6D51C245 E485B576 625E7EC6 F44C42E9"
                + "A637ED6B 0BFF5CB6 F406B7ED EE386BFB 5A899FA5 AE9F2411 7C4B1FE6"
                + "49286651 ECE45B3D C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8"
                + "FD24CF5F 83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D"
                + "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B E39E772C"
                + "180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9 DE2BCBF6 95581718"
                + "3995497C EA956AE5 15D22618 98FA0510 15728E5A 8AAAC42D AD33170D"
                + "04507A33 A85521AB DF1CBA64 ECFB8504 58DBEF0A 8AEA7157 5D060C7D"
                + "B3970F85 A6E1E4C7 ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226"
                + "1AD2EE6B F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C"
                + "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31 43DB5BFC"
                + "E0FD108E 4B82D120 A93AD2CA FFFFFFFF FFFFFFFF");

    G_3072 = BigInteger.valueOf(5);

    try {
      PluginInterface dht_pi = core.getPluginManager().getPluginInterfaceByClass(DHTPlugin.class);

      if (dht_pi == null) {

        throw (new Exception("DHT Plugin not found"));
      }

      DHTPlugin dht_plugin = (DHTPlugin) dht_pi.getPlugin();

      if (!dht_plugin.isEnabled()) {

        throw (new Exception("DHT Plugin is disabled"));
      }

      DHT[] dhts = dht_plugin.getDHTs();

      List<DHTNATPuncher> punchers = new ArrayList<DHTNATPuncher>();

      for (DHT dht : dhts) {

        int net = dht.getTransport().getNetwork();

        if (net == DHT.NW_MAIN) {

          DHTNATPuncher primary_puncher = dht.getNATPuncher();

          if (primary_puncher != null) {

            punchers.add(primary_puncher);

            nat_punchers_ipv4.add(primary_puncher);

            for (int i = 1; i <= 2; i++) {

              DHTNATPuncher puncher = primary_puncher.getSecondaryPuncher();

              punchers.add(puncher);

              nat_punchers_ipv4.add(puncher);
            }
          }
        } else if (net == DHT.NW_MAIN_V6) {

          /*
           * no point in this atm as we don't support v6 tunnels

          DHTNATPuncher puncher = dht.getNATPuncher();

          if ( puncher != null ){

          	punchers.add( puncher );

          	nat_punchers_ipv6.add( puncher );

          	puncher = puncher.getSecondaryPuncher();

          	punchers.add( puncher );

          	nat_punchers_ipv6.add( puncher );
          }
          */
        }
      }

      if (punchers.size() == 0) {

        throw (new Exception("No suitable DHT instances available"));
      }

      for (DHTNATPuncher p : punchers) {

        p.forceActive(true);

        p.addListener(
            new DHTNATPuncherListener() {
              public void rendezvousChanged(DHTTransportContact rendezvous) {
                System.out.println("active: " + rendezvous.getString());

                synchronized (PairingManagerTunnelHandler.this) {
                  if (update_event == null) {

                    update_event =
                        SimpleTimer.addEvent(
                            "PMT:defer",
                            SystemTime.getOffsetTime(15 * 1000),
                            new TimerEventPerformer() {
                              public void perform(TimerEvent event) {
                                synchronized (PairingManagerTunnelHandler.this) {
                                  update_event = null;
                                }

                                System.out.println("    updating");

                                manager.updateNeeded();
                              };
                            });
                  }
                }
              }
            });
      }

      core.getNATTraverser()
          .registerHandler(
              new NATTraversalHandler() {
                private Map<Long, Object[]> server_map =
                    new LinkedHashMap<Long, Object[]>(10, 0.75f, true) {
                      protected boolean removeEldestEntry(Map.Entry<Long, Object[]> eldest) {
                        return size() > 10;
                      }
                    };

                public int getType() {
                  return (NATTraverser.TRAVERSE_REASON_PAIR_TUNNEL);
                }

                public String getName() {
                  return ("Pairing Tunnel");
                }

                public Map process(InetSocketAddress originator, Map data) {
                  if (SRP_VERIFIER == null || !active) {

                    return (null);
                  }

                  boolean good_request = false;

                  try {

                    Map result = new HashMap();

                    Long session = (Long) data.get("sid");

                    if (session == null) {

                      return (null);
                    }

                    InetAddress tunnel_originator;

                    try {
                      tunnel_originator = InetAddress.getByAddress((byte[]) data.get("origin"));

                    } catch (Throwable e) {

                      Debug.out("originator decode failed: " + data);

                      return (null);
                    }

                    System.out.println(
                        "PairManagerTunnelHander: incoming message - session="
                            + session
                            + ", payload="
                            + data
                            + " from "
                            + tunnel_originator
                            + " via "
                            + originator);

                    SRP6Server server;
                    BigInteger B;

                    synchronized (server_map) {
                      Object[] entry = server_map.get(session);

                      if (entry == null) {

                        long diff = SystemTime.getMonotonousTime() - last_server_create_time;

                        if (diff < 5000) {

                          try {
                            long sleep = 5000 - diff;

                            System.out.println("Sleeping for " + sleep + " before starting srp");

                            Thread.sleep(sleep);

                          } catch (Throwable e) {
                          }
                        }

                        server = new SRP6Server();

                        server.init(
                            N_3072,
                            G_3072,
                            SRP_VERIFIER,
                            new SHA256Digest(),
                            RandomUtils.SECURE_RANDOM);

                        B = server.generateServerCredentials();

                        server_map.put(session, new Object[] {server, B});

                        last_server_create_time = SystemTime.getMonotonousTime();

                        total_servers++;

                      } else {

                        server = (SRP6Server) entry[0];
                        B = (BigInteger) entry[1];
                      }
                    }

                    Long op = (Long) data.get("op");

                    if (op == 1) {

                      result.put("op", 2);

                      result.put("s", SRP_SALT);

                      result.put("b", B.toByteArray());

                      good_request = true;

                      if (data.containsKey("test")) {

                        manager.recordRequest(
                            "SRP Test", originator.getAddress().getHostAddress(), true);
                      }
                    } else if (op == 3) {

                      boolean log_error = true;

                      try {
                        long diff = SystemTime.getMonotonousTime() - last_server_agree_time;

                        if (diff < 5000) {

                          try {
                            long sleep = 5000 - diff;

                            System.out.println("Sleeping for " + sleep + " before completing srp");

                            Thread.sleep(sleep);

                          } catch (Throwable e) {
                          }
                        }

                        BigInteger A = new BigInteger((byte[]) data.get("a"));

                        BigInteger serverS = server.calculateSecret(A);

                        byte[] shared_secret = serverS.toByteArray();

                        Cipher decipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

                        byte[] key = new byte[16];

                        System.arraycopy(shared_secret, 0, key, 0, 16);

                        SecretKeySpec secret = new SecretKeySpec(key, "AES");

                        decipher.init(
                            Cipher.DECRYPT_MODE,
                            secret,
                            new IvParameterSpec((byte[]) data.get("enc_iv")));

                        byte[] dec = decipher.doFinal((byte[]) data.get("enc_data"));

                        String json_str = new String(dec, "UTF-8");

                        if (!json_str.startsWith("{")) {

                          log_error = false;

                          throw (new Exception("decode failed"));
                        }

                        JSONObject dec_json = (JSONObject) JSONUtils.decodeJSON(json_str);

                        String tunnel_url = (String) dec_json.get("url");

                        String service_id = new String((byte[]) data.get("service"), "UTF-8");

                        String endpoint_url = (String) dec_json.get("endpoint");

                        boolean ok =
                            createTunnel(
                                tunnel_originator,
                                session,
                                service_id,
                                secret,
                                tunnel_url,
                                endpoint_url);

                        result.put("op", 4);
                        result.put("status", ok ? "ok" : "failed");

                        good_request = true;

                      } catch (Throwable e) {

                        result.put("op", 4);
                        result.put("status", "failed");

                        // filter usual errors on bad agreement

                        if (e instanceof BadPaddingException
                            || e instanceof IllegalBlockSizeException) {

                          log_error = false;
                        }

                        if (log_error) {

                          e.printStackTrace();
                        }
                      } finally {

                        last_server_agree_time = SystemTime.getMonotonousTime();
                      }
                    }

                    return (result);

                  } finally {

                    if (!good_request) {

                      manager.recordRequest("SRP", originator.getAddress().getHostAddress(), false);
                    }
                  }
                }
              });

      SimpleTimer.addPeriodicEvent(
          "pm:tunnel:stats",
          30 * 1000,
          new TimerEventPerformer() {
            public void perform(TimerEvent event) {
              synchronized (tunnels) {
                if (tunnels.size() > 0) {

                  System.out.println("PairTunnels: " + tunnels.size());

                  for (PairManagerTunnel t : tunnels.values()) {

                    System.out.println("\t" + t.getString());
                  }
                }
              }
            }
          });

    } catch (Throwable e) {

      Debug.out(e);

      init_fail = Debug.getNestedExceptionMessage(e);

      manager.updateSRPState();
    }
  }
Exemplo n.º 11
0
  public static <T> long LazyMovingImmediateAverage(
      final int periods,
      final int interval_secs,
      final LazyMovingImmediateAverageAdapter<T> adapter,
      final T instance) {
    LazyMovingImmediateAverageState current = adapter.getCurrent(instance);

    if (current == null) {

      final LazyMovingImmediateAverageState state = current = new LazyMovingImmediateAverageState();

      SimpleTimer.addTickReceiver(
          new TimerTickReceiver() {

            public void tick(long mono_now, int tick_count) {
              long now = SystemTime.getMonotonousTime();

              if (now - state.last_read > 60 * 1000) {

                SimpleTimer.removeTickReceiver(this);

                adapter.setCurrent(instance, null);

              } else if (tick_count % interval_secs == 0) {

                long value = adapter.getValue(instance);

                long last = state.last_value;
                long diff = value - last;

                if (last >= 0 && diff >= 0) {

                  MovingImmediateAverage average = state.average;

                  if (diff == 0) {

                    state.consec_zeros++;

                  } else {

                    state.consec_zeros = 0;
                  }

                  if (average == null) {

                    if (diff > 0) {

                      state.average = average = MovingImmediateAverage(periods);

                      int zeros_to_do = Math.min(state.consec_zeros, periods);

                      for (int i = 0; i < zeros_to_do; i++) {

                        average.update(0);
                      }
                    }
                  }

                  if (average != null) {

                    long ave = (long) average.update(diff);

                    if (ave == 0 && average.getSampleCount() >= periods) {

                      // looks pretty dead

                      state.average = null;
                    }
                  }
                }

                state.last_value = value;
              }
            }
          });

      adapter.setCurrent(instance, current);

    } else {

      current.last_read = SystemTime.getMonotonousTime();
    }

    MovingImmediateAverage average = current.average;

    if (average == null) {

      return (0);

    } else {

      return ((long) average.getAverage() / interval_secs);
    }
  }
Exemplo n.º 12
0
  protected void calculateSchedule() {
    Subscription[] subs = manager.getSubscriptions();

    synchronized (this) {
      if (!schedulng_permitted) {

        return;
      }

      if (schedule_in_progress) {

        return;
      }

      long next_ready_time = Long.MAX_VALUE;

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

        Subscription sub = subs[i];

        if (!sub.isSubscribed()) {

          continue;
        }

        SubscriptionHistory history = sub.getHistory();

        if (!history.isEnabled()) {

          continue;
        }

        long next_scan = getNextScan(sub);

        sub.setUserData(SCHEDULER_NEXT_SCAN_KEY, new Long(next_scan));

        if (next_scan < next_ready_time) {

          next_ready_time = next_scan;
        }
      }

      long old_when = 0;

      if (schedule_event != null) {

        old_when = schedule_event.getWhen();

        schedule_event.cancel();

        schedule_event = null;
      }

      if (next_ready_time < Long.MAX_VALUE) {

        long now = SystemTime.getCurrentTime();

        if (now < last_schedule || now - last_schedule < 30 * 1000) {

          if (next_ready_time - now < 30 * 1000) {

            next_ready_time = now + 30 * 1000;
          }
        }

        log(
            "Calculate : "
                + "old_time="
                + new SimpleDateFormat().format(new Date(old_when))
                + ", new_time="
                + new SimpleDateFormat().format(new Date(next_ready_time)));

        schedule_event =
            SimpleTimer.addEvent(
                "SS:Scheduler",
                next_ready_time,
                new TimerEventPerformer() {
                  public void perform(TimerEvent event) {
                    synchronized (SubscriptionSchedulerImpl.this) {
                      if (schedule_in_progress) {

                        return;
                      }

                      schedule_in_progress = true;

                      last_schedule = SystemTime.getCurrentTime();

                      schedule_event = null;
                    }

                    new AEThread2("SS:Sched", true) {
                      public void run() {
                        try {
                          schedule();

                        } finally {

                          synchronized (SubscriptionSchedulerImpl.this) {
                            schedule_in_progress = false;
                          }

                          calculateSchedule();
                        }
                      }
                    }.start();
                  }
                });
      }
    }
  }
  protected ContentNetworkManagerImpl() {
    loadConfig();

    addNetwork(new ContentNetworkVuze(this));

    AEDiagnostics.addEvidenceGenerator(this);

    CustomizationManager cust_man = CustomizationManagerFactory.getSingleton();

    Customization cust = cust_man.getActiveCustomization();

    if (cust != null) {

      String cust_name = COConfigurationManager.getStringParameter("cnetworks.custom.name", "");
      String cust_version =
          COConfigurationManager.getStringParameter("cnetworks.custom.version", "0");

      boolean new_name = !cust_name.equals(cust.getName());
      boolean new_version = Constants.compareVersions(cust_version, cust.getVersion()) < 0;

      if (new_name || new_version) {

        try {
          InputStream[] streams = cust.getResources(Customization.RT_CNETWORKS);

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

            InputStream is = streams[i];

            try {
              VuzeFile vf = VuzeFileHandler.getSingleton().loadVuzeFile(is);

              if (vf != null) {

                VuzeFileComponent[] comps = vf.getComponents();

                for (int j = 0; j < comps.length; j++) {

                  VuzeFileComponent comp = comps[j];

                  int type = comp.getType();

                  if (type == VuzeFileComponent.COMP_TYPE_CONTENT_NETWORK) {

                    try {
                      // change here as we always add all networks upfront so
                      // we always set the customisation flag regardless of
                      // whether existing or not

                      ContentNetwork imported = importNetwork(comp.getContent());

                      imported.setPersistentProperty(ContentNetwork.PP_IS_CUSTOMIZATION, true);

                      comp.setProcessed();

                    } catch (Throwable e) {

                      log("Failed to import customisation network", e);
                    }
                  }
                }
              }
            } finally {

              try {
                is.close();

              } catch (Throwable e) {
              }
            }
          }
        } finally {

          COConfigurationManager.setParameter("cnetworks.custom.name", cust.getName());
          COConfigurationManager.setParameter("cnetworks.custom.version", cust.getVersion());
        }
      }
    }

    SimpleTimer.addPeriodicEvent(
        "MetaSearchRefresh",
        23 * 60 * 60 * 1000,
        new TimerEventPerformer() {
          public void perform(TimerEvent event) {
            checkForUpdates();
          }
        });

    if (networks.size() > 1 || LOAD_ALL_NETWORKS) {

      new AEThread2("CNetwork:init", true) {
        public void run() {
          checkForUpdates();
        }
      }.start();
    }
  }
Exemplo n.º 14
0
  protected void runRendezvousSupport() {

    SimpleTimer.addPeriodicEvent(
        "DHTNAT:cp",
        RENDEZVOUS_CLIENT_PING_PERIOD,
        new TimerEventPerformer() {
          public void perform(TimerEvent ev) {

            try {
              DHTTransportContact latest_local;
              DHTTransportContact latest_target;

              try {
                pub_mon.enter();

                latest_local = rendezvous_local_contact;
                latest_target = rendezvous_target;
              } finally {

                pub_mon.exit();
              }

              if (current_local != null || latest_local != null) {

                // one's not null, worthwhile further investigation

                if (current_local != latest_local) {

                  // local has changed, remove existing publish

                  if (current_local != null) {

                    log(
                        "Removing publish for "
                            + current_local.getString()
                            + " -> "
                            + current_target.getString());

                    dht.remove(
                        getPublishKey(current_local),
                        "DHTNatPuncher: removal of publish",
                        new DHTOperationListener() {
                          public void searching(
                              DHTTransportContact contact, int level, int active_searches) {}

                          public void found(DHTTransportContact contact) {}

                          public void diversified(String desc) {}

                          public void read(DHTTransportContact contact, DHTTransportValue value) {}

                          public void wrote(DHTTransportContact contact, DHTTransportValue value) {}

                          public void complete(boolean timeout) {}
                        });
                  }

                  if (latest_local != null) {

                    log(
                        "Adding publish for "
                            + latest_local.getString()
                            + " -> "
                            + latest_target.getString());

                    rendevzous_fail_count =
                        RENDEZVOUS_PING_FAIL_LIMIT - 2; // only 2 attempts to start with

                    dht.put(
                        getPublishKey(latest_local),
                        "NAT Traversal: rendezvous publish",
                        encodePublishValue(latest_target),
                        DHT.FLAG_SINGLE_VALUE,
                        new DHTOperationListener() {
                          public void searching(
                              DHTTransportContact contact, int level, int active_searches) {}

                          public void found(DHTTransportContact contact) {}

                          public void diversified(String desc) {}

                          public void read(DHTTransportContact contact, DHTTransportValue value) {}

                          public void wrote(DHTTransportContact contact, DHTTransportValue value) {}

                          public void complete(boolean timeout) {}
                        });
                  }
                } else if (current_target != latest_target) {

                  // here current_local == latest_local and neither is null!

                  // target changed, update publish

                  log(
                      "Updating publish for "
                          + latest_local.getString()
                          + " -> "
                          + latest_target.getString());

                  rendevzous_fail_count =
                      RENDEZVOUS_PING_FAIL_LIMIT - 2; // only 2 attempts to start with

                  dht.put(
                      getPublishKey(latest_local),
                      "DHTNatPuncher: update publish",
                      encodePublishValue(latest_target),
                      DHT.FLAG_SINGLE_VALUE,
                      new DHTOperationListener() {
                        public void searching(
                            DHTTransportContact contact, int level, int active_searches) {}

                        public void found(DHTTransportContact contact) {}

                        public void diversified(String desc) {}

                        public void read(DHTTransportContact contact, DHTTransportValue value) {}

                        public void wrote(DHTTransportContact contact, DHTTransportValue value) {}

                        public void complete(boolean timeout) {}
                      });
                }
              }

              current_local = latest_local;
              current_target = latest_target;

              if (current_target != null) {

                int bind_result = sendBind(current_target);

                if (bind_result == RESP_OK) {

                  trace("Rendezvous:" + current_target.getString() + " OK");

                  rendevzous_fail_count = 0;

                  if (last_ok_rendezvous != current_target) {

                    last_ok_rendezvous = current_target;

                    log("Rendezvous " + latest_target.getString() + " operational");
                  }
                } else {

                  if (bind_result == RESP_NOT_OK) {

                    // denied access

                    rendevzous_fail_count = RENDEZVOUS_PING_FAIL_LIMIT;

                  } else {

                    rendevzous_fail_count++;
                  }

                  if (rendevzous_fail_count == RENDEZVOUS_PING_FAIL_LIMIT) {

                    rendezvousFailed(current_target, false);
                  }
                }
              }

            } catch (Throwable e) {

              log(e);
            }
          }
        });
  }