/** Die a horrible death. Cannot be restarted. */
 public synchronized void stopRunning() {
   if (_dead) return;
   if (_context.router().isAlive() && _log.shouldLog(Log.WARN))
     _log.warn(
         "Stop the I2CP connection!  current leaseSet: " + _currentLeaseSet,
         new Exception("Stop client connection"));
   _dead = true;
   // we need these keys to unpublish the leaseSet
   if (_reader != null) _reader.stopReading();
   if (_writer != null) _writer.stopWriting();
   if (_socket != null)
     try {
       _socket.close();
     } catch (IOException ioe) {
     }
   _messages.clear();
   _acceptedPending.clear();
   if (_sessionKeyManager != null) _sessionKeyManager.shutdown();
   _manager.unregisterConnection(this);
   if (_currentLeaseSet != null) _context.netDb().unpublish(_currentLeaseSet);
   _leaseRequest = null;
   synchronized (_alreadyProcessed) {
     _alreadyProcessed.clear();
   }
   // _config = null;
   // _manager = null;
 }
Beispiel #2
0
 public OutboundReceiver(RouterContext ctx, TunnelCreatorConfig cfg) {
   _context = ctx;
   _log = ctx.logManager().getLog(OutboundReceiver.class);
   _config = cfg;
   _nextHopCache = _context.netDb().lookupRouterInfoLocally(_config.getPeer(1));
   // all createRateStat() in TunnelDispatcher
 }
Beispiel #3
0
 /**
  * Note that we successfully stored to a floodfill peer and verified the result by asking another
  * floodfill peer
  */
 public void storeSuccessful() {
   // Fixme, redefined this to include both lookup and store fails,
   // need to fix the javadocs
   _failedLookupRate.addData(0, 0);
   _context.statManager().addRateData("peer.failedLookupRate", 0, 0);
   _lastStoreSuccessful = _context.clock().now();
 }
Beispiel #4
0
 /**
  * Deferred deletion of plugins that we failed to delete before.
  *
  * @since 0.9.13
  */
 private static void deferredDeletePlugins(RouterContext ctx) {
   Log log = ctx.logManager().getLog(PluginStarter.class);
   boolean changed = false;
   Properties props = pluginProperties();
   for (Iterator<Map.Entry<Object, Object>> iter = props.entrySet().iterator(); iter.hasNext(); ) {
     Map.Entry<Object, Object> e = iter.next();
     String name = (String) e.getKey();
     if (name.startsWith(PREFIX) && name.endsWith(ENABLED)) {
       // deferred deletion of a plugin
       if (e.getValue().equals(DELETED)) {
         String app = name.substring(PREFIX.length(), name.lastIndexOf(ENABLED));
         // shouldn't happen, this is run early
         if (isPluginRunning(app, ctx)) continue;
         File pluginDir = new File(ctx.getConfigDir(), PLUGIN_DIR + '/' + app);
         boolean deleted = FileUtil.rmdir(pluginDir, false);
         if (deleted) {
           log.logAlways(Log.WARN, "Deferred deletion of " + pluginDir + " successful");
           iter.remove();
           changed = true;
         } else {
           if (log.shouldLog(Log.WARN)) log.warn("Deferred deletion of " + pluginDir + " failed");
         }
       }
     }
   }
   if (changed) storePluginProperties(props);
 }
Beispiel #5
0
 /**
  * Delete all files listed in the delete file. Format: One file name per line, comment lines start
  * with '#'. All file names must be relative to $I2P, absolute file names not allowed. We probably
  * can't remove old jars this way. Fails silently. Use no new I2P classes here so it may be called
  * after zip extraction.
  *
  * @since 0.8.12
  */
 private static void deleteListedFiles(RouterContext context) {
   File deleteFile = new File(context.getBaseDir(), DELETE_FILE);
   if (!deleteFile.exists()) return;
   // this is similar to FileUtil.readTextFile() but we can't use any I2P classes here
   FileInputStream fis = null;
   BufferedReader in = null;
   try {
     fis = new FileInputStream(deleteFile);
     in = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
     String line;
     while ((line = in.readLine()) != null) {
       String fl = line.trim();
       if (fl.contains("..") || fl.startsWith("#") || fl.length() == 0) continue;
       File df = new File(fl);
       if (df.isAbsolute()) continue;
       df = new File(context.getBaseDir(), fl);
       if (df.exists() && !df.isDirectory()) {
         if (df.delete()) System.out.println("INFO: File [" + fl + "] deleted");
       }
     }
   } catch (IOException ioe) {
   } finally {
     if (in != null)
       try {
         in.close();
       } catch (IOException ioe) {
       }
     if (deleteFile.delete()) System.out.println("INFO: File [" + DELETE_FILE + "] deleted");
   }
 }
  /** Set up basic security constraints for the webapp. Add all users and passwords. */
  static void initialize(RouterContext ctx, WebAppContext context) {
    SecurityHandler sec = new SecurityHandler();
    List<ConstraintMapping> constraints = new ArrayList(4);
    ConsolePasswordManager mgr = new ConsolePasswordManager(ctx);
    boolean enable = ctx.getBooleanProperty(PROP_PW_ENABLE);
    if (enable) {
      Map<String, String> userpw = mgr.getMD5(PROP_CONSOLE_PW);
      if (userpw.isEmpty()) {
        enable = false;
        ctx.router().saveConfig(PROP_CONSOLE_PW, "false");
      } else {
        HashUserRealm realm = new HashUserRealm(JETTY_REALM);
        sec.setUserRealm(realm);
        sec.setAuthenticator(authenticator);
        for (Map.Entry<String, String> e : userpw.entrySet()) {
          String user = e.getKey();
          String pw = e.getValue();
          realm.put(user, MD5.__TYPE + pw);
          realm.addUserToRole(user, JETTY_ROLE);
          Constraint constraint = new Constraint(user, JETTY_ROLE);
          constraint.setAuthenticate(true);
          ConstraintMapping cm = new ConstraintMapping();
          cm.setConstraint(constraint);
          cm.setPathSpec("/");
          constraints.add(cm);
        }
      }
    }

    // This forces a '403 Forbidden' response for TRACE and OPTIONS unless the
    // WAC handler handles it.
    // (LocaleWebAppHandler returns a '405 Method Not Allowed')
    // TRACE and OPTIONS aren't really security issues...
    // TRACE doesn't echo stuff unless you call setTrace(true)
    // But it might bug some people
    // The other strange methods - PUT, DELETE, MOVE - are disabled by default
    // See also:
    // http://old.nabble.com/Disable-HTTP-TRACE-in-Jetty-5.x-td12412607.html

    Constraint sc = new Constraint();
    sc.setName("No trace");
    ConstraintMapping cm = new ConstraintMapping();
    cm.setMethod("TRACE");
    cm.setConstraint(sc);
    cm.setPathSpec("/");
    constraints.add(cm);

    sc = new Constraint();
    sc.setName("No options");
    cm = new ConstraintMapping();
    cm.setMethod("OPTIONS");
    cm.setConstraint(sc);
    cm.setPathSpec("/");
    constraints.add(cm);

    ConstraintMapping cmarr[] = constraints.toArray(new ConstraintMapping[constraints.size()]);
    sec.setConstraintMappings(cmarr);

    context.setSecurityHandler(sec);
  }
Beispiel #7
0
 public UDPReceiver(
     RouterContext ctx, UDPTransport transport, DatagramSocket socket, String name) {
   _context = ctx;
   _log = ctx.logManager().getLog(UDPReceiver.class);
   _name = name;
   _socket = socket;
   _transport = transport;
   _handler = transport.getPacketHandler();
   if (_handler == null) throw new IllegalStateException();
   _runner = new Runner();
   // _context.statManager().createRateStat("udp.receivePacketSize", "How large packets received
   // are", "udp", UDPTransport.RATES);
   // _context.statManager().createRateStat("udp.receiveRemaining", "How many packets are left
   // sitting on the receiver's queue", "udp", UDPTransport.RATES);
   // _context.statManager().createRateStat("udp.droppedInbound", "How many packet are queued up
   // but not yet received when we drop", "udp", UDPTransport.RATES);
   _context
       .statManager()
       .createRateStat(
           "udp.receiveHolePunch",
           "How often we receive a NAT hole punch",
           "udp",
           UDPTransport.RATES);
   _context
       .statManager()
       .createRateStat(
           "udp.ignorePacketFromDroplist",
           "Packet lifetime for those dropped on the drop list",
           "udp",
           UDPTransport.RATES);
 }
 /**
  * @param claimedAddress an IP/port based RemoteHostId, or null if unknown
  * @param remoteHostId non-null, == claimedAddress if direct, or a hash-based one if indirect
  * @param addr non-null
  */
 public OutboundEstablishState(
     RouterContext ctx,
     RemoteHostId claimedAddress,
     RemoteHostId remoteHostId,
     RouterIdentity remotePeer,
     SessionKey introKey,
     UDPAddress addr,
     DHSessionKeyBuilder.Factory dh) {
   _context = ctx;
   _log = ctx.logManager().getLog(OutboundEstablishState.class);
   if (claimedAddress != null) {
     _bobIP = claimedAddress.getIP();
     _bobPort = claimedAddress.getPort();
   } else {
     // _bobIP = null;
     _bobPort = -1;
   }
   _claimedAddress = claimedAddress;
   _remoteHostId = remoteHostId;
   _remotePeer = remotePeer;
   _introKey = introKey;
   _queuedMessages = new LinkedBlockingQueue<OutNetMessage>();
   _establishBegin = ctx.clock().now();
   _remoteAddress = addr;
   _introductionNonce = -1;
   _keyFactory = dh;
   if (addr.getIntroducerCount() > 0) {
     if (_log.shouldLog(Log.DEBUG))
       _log.debug(
           "new outbound establish to " + remotePeer.calculateHash() + ", with address: " + addr);
     _currentState = OutboundState.OB_STATE_PENDING_INTRO;
   } else {
     _currentState = OutboundState.OB_STATE_UNKNOWN;
   }
 }
Beispiel #9
0
  public long receiveEncrypted(byte encrypted[]) {
    TunnelDataMessage msg = new TunnelDataMessage(_context);
    msg.setData(encrypted);
    msg.setTunnelId(_config.getConfig(0).getSendTunnel());

    if (_log.shouldLog(Log.DEBUG))
      _log.debug("received encrypted, sending out " + _config + ": " + msg);
    RouterInfo ri = _nextHopCache;
    if (ri == null) ri = _context.netDb().lookupRouterInfoLocally(_config.getPeer(1));
    if (ri != null) {
      _nextHopCache = ri;
      send(msg, ri);
      return msg.getUniqueId();
    } else {
      // It should be rare to forget the router info for a peer in our own tunnel.
      if (_log.shouldLog(Log.WARN))
        _log.warn("lookup of " + _config.getPeer(1) + " required for " + msg);
      _context
          .netDb()
          .lookupRouterInfo(
              _config.getPeer(1),
              new SendJob(_context, msg),
              new FailedJob(_context),
              MAX_LOOKUP_TIME);
      return -1;
    }
  }
Beispiel #10
0
 public NewsFetcher(RouterContext ctx, ConsoleUpdateManager mgr, List<URI> uris) { 
     super(ctx, mgr, NEWS, uris);
     _newsFile = new File(ctx.getRouterDir(), NewsHelper.NEWS_FILE);
     _tempFile = new File(ctx.getTempDir(), "tmp-" + ctx.random().nextLong() + TEMP_NEWS_FILE);
     long lastMod = NewsHelper.lastChecked(ctx);
     if (lastMod > 0)
         _lastModified = RFC822Date.to822Date(lastMod);
 }
Beispiel #11
0
 private List<String> getUpdateURLs() {
     String URLs = _context.getProperty(ConfigUpdateHandler.PROP_UPDATE_URL, ConfigUpdateHandler.DEFAULT_UPDATE_URL);
     StringTokenizer tok = new StringTokenizer(URLs, " ,\r\n");
     List<String> URLList = new ArrayList();
     while (tok.hasMoreTokens())
         URLList.add(tok.nextToken().trim());
     Collections.shuffle(URLList, _context.random());
     return URLList;
 }
Beispiel #12
0
  /**
   * add but don't start This is used only by RouterConsoleRunner, which adds all the webapps first
   * and then starts all at once.
   */
  static WebAppContext addWebApp(
      RouterContext ctx,
      ContextHandlerCollection server,
      String appName,
      String warPath,
      File tmpdir)
      throws IOException {

    // Jetty will happily load one context on top of another without stopping
    // the first one, so we remove any previous one here
    try {
      stopWebApp(appName);
    } catch (Throwable t) {
    }

    // To avoid ZipErrors from JarURLConnetion caching,
    // (used by Jetty JarResource and JarFileResource)
    // copy the war to a new directory if it is newer than the one we loaded originally.
    // Yes, URLConnection has a setDefaultUseCaches() method, but it's hard to get to
    // because it's non-static and the class is abstract, and we don't really want to
    // set the default to false for everything.
    long newmod = (new File(warPath)).lastModified();
    if (newmod <= 0) throw new IOException("Web app " + warPath + " does not exist");
    Long oldmod = warModTimes.get(warPath);
    if (oldmod == null) {
      warModTimes.put(warPath, new Long(newmod));
    } else if (oldmod.longValue() < newmod) {
      // copy war to temporary directory
      File warTmpDir =
          new SecureDirectory(ctx.getTempDir(), "war-copy-" + appName + ctx.random().nextInt());
      warTmpDir.mkdir();
      String tmpPath = (new File(warTmpDir, appName + ".war")).getAbsolutePath();
      if (!FileUtil.copy(warPath, tmpPath, true))
        throw new IOException("Web app failed copy from " + warPath + " to " + tmpPath);
      warPath = tmpPath;
    }

    WebAppContext wac = new WebAppContext(warPath, "/" + appName);
    tmpdir.mkdir();
    wac.setTempDirectory(tmpdir);
    // all the JSPs are precompiled, no need to extract
    wac.setExtractWAR(false);

    // this does the passwords...
    RouterConsoleRunner.initialize(ctx, wac);

    // see WebAppConfiguration for info
    String[] classNames = wac.getConfigurationClasses();
    String[] newClassNames = new String[classNames.length + 1];
    for (int j = 0; j < classNames.length; j++) newClassNames[j] = classNames[j];
    newClassNames[classNames.length] = WebAppConfiguration.class.getName();
    wac.setConfigurationClasses(newClassNames);
    server.addHandler(wac);
    server.mapContexts();
    return wac;
  }
Beispiel #13
0
 /**
  * adds and starts
  *
  * @throws just about anything, caller would be wise to catch Throwable
  */
 static void startWebApp(
     RouterContext ctx, ContextHandlerCollection server, String appName, String warPath)
     throws Exception {
   File tmpdir =
       new SecureDirectory(ctx.getTempDir(), "jetty-work-" + appName + ctx.random().nextInt());
   WebAppContext wac = addWebApp(ctx, server, appName, warPath, tmpdir);
   // _log.debug("Loading war from: " + warPath);
   wac.setInitParams(INIT_PARAMS);
   wac.start();
 }
Beispiel #14
0
  /**
   * @return true on success
   * @throws just about anything, caller would be wise to catch Throwable
   */
  public static boolean stopPlugin(RouterContext ctx, String appName) throws Exception {
    Log log = ctx.logManager().getLog(PluginStarter.class);
    File pluginDir = new File(ctx.getConfigDir(), PLUGIN_DIR + '/' + appName);
    if ((!pluginDir.exists()) || (!pluginDir.isDirectory())) {
      log.error("Cannot stop nonexistent plugin: " + appName);
      return false;
    }

    // stop things in clients.config
    File clientConfig = new File(pluginDir, "clients.config");
    if (clientConfig.exists()) {
      Properties props = new Properties();
      DataHelper.loadProps(props, clientConfig);
      List<ClientAppConfig> clients = ClientAppConfig.getClientApps(clientConfig);
      runClientApps(ctx, pluginDir, clients, "stop");
    }

    // stop console webapps in console/webapps
    // ContextHandlerCollection server = WebAppStarter.getConsoleServer();
    // if (server != null) {
    /*
        File consoleDir = new File(pluginDir, "console");
        Properties props = RouterConsoleRunner.webAppProperties(consoleDir.getAbsolutePath());
        File webappDir = new File(consoleDir, "webapps");
        String fileNames[] = webappDir.list(RouterConsoleRunner.WarFilenameFilter.instance());
        if (fileNames != null) {
            for (int i = 0; i < fileNames.length; i++) {
                String warName = fileNames[i].substring(0, fileNames[i].lastIndexOf(".war"));
                if (Arrays.asList(STANDARD_WEBAPPS).contains(warName)) {
                    continue;
                }
                WebAppStarter.stopWebApp(server, warName);
            }
        }
    */
    if (pluginWars.containsKey(appName)) {
      Iterator<String> wars = pluginWars.get(appName).iterator();
      while (wars.hasNext()) {
        String warName = wars.next();
        WebAppStarter.stopWebApp(warName);
      }
      pluginWars.get(appName).clear();
    }
    // }

    // remove summary bar link
    Properties props = pluginProperties(ctx, appName);
    String name =
        ConfigClientsHelper.stripHTML(props, "consoleLinkName_" + Messages.getLanguage(ctx));
    if (name == null) name = ConfigClientsHelper.stripHTML(props, "consoleLinkName");
    if (name != null && name.length() > 0) NavHelper.unregisterApp(name);

    if (log.shouldLog(Log.WARN)) log.warn("Stopping plugin: " + appName);
    return true;
  }
 /** Create a new runner against the given socket */
 public ClientConnectionRunner(RouterContext context, ClientManager manager, Socket socket) {
   _context = context;
   _log = _context.logManager().getLog(ClientConnectionRunner.class);
   _manager = manager;
   _socket = socket;
   // unused for fastReceive
   _messages = new ConcurrentHashMap();
   _alreadyProcessed = new ArrayList();
   _acceptedPending = new ConcurrentHashSet();
   _messageId = new AtomicInteger(_context.random().nextInt());
 }
Beispiel #16
0
 public void run() {
   deferredDeletePlugins(_context);
   if (_context.getBooleanPropertyDefaultTrue("plugins.autoUpdate")
       && !NewsHelper.isUpdateInProgress()) {
     String prev = _context.getProperty("router.previousVersion");
     if (prev != null && VersionComparator.comp(RouterVersion.VERSION, prev) > 0) {
       updateAll(_context, true);
     }
   }
   startPlugins(_context);
 }
 public ProfilePersistenceHelper(RouterContext ctx) {
   _context = ctx;
   _log = ctx.logManager().getLog(ProfilePersistenceHelper.class);
   String dir = _context.getProperty(PROP_PEER_PROFILE_DIR, DEFAULT_PEER_PROFILE_DIR);
   _profileDir = new SecureDirectory(_context.getRouterDir(), dir);
   if (!_profileDir.exists()) _profileDir.mkdirs();
   for (int j = 0; j < B64.length(); j++) {
     File subdir = new SecureDirectory(_profileDir, DIR_PREFIX + B64.charAt(j));
     if (!subdir.exists()) subdir.mkdir();
   }
 }
 public Set<PeerProfile> readProfiles() {
   long start = _context.clock().now();
   List<File> files = selectFiles();
   Set<PeerProfile> profiles = new HashSet(files.size());
   for (File f : files) {
     PeerProfile profile = readProfile(f);
     if (profile != null) profiles.add(profile);
   }
   long duration = _context.clock().now() - start;
   if (_log.shouldLog(Log.DEBUG))
     _log.debug("Loading " + profiles.size() + " took " + duration + "ms");
   return profiles;
 }
Beispiel #19
0
 public OutNetMessage(RouterContext context) {
   _context = context;
   _log = context.logManager().getLog(OutNetMessage.class);
   _priority = -1;
   _expiration = -1;
   // _createdBy = new Exception("Created by");
   _created = context.clock().now();
   if (_log.shouldLog(Log.INFO)) timestamp("Created");
   // _context.messageStateMonitor().outboundMessageAdded();
   // _context.statManager().createRateStat("outNetMessage.timeToDiscard",
   //                                      "How long until we discard an outbound msg?",
   //                                      "OutNetMessage", new long[] { 5*60*1000, 30*60*1000,
   // 60*60*1000 });
 }
Beispiel #20
0
    public void renderStatusHTML(Writer out) throws IOException {
        StringBuilder buf = new StringBuilder(1024);
        // move to the jsp
        //buf.append("<h2>Banned Peers</h2>");
        Map<Hash, Banlist.Entry> entries = new TreeMap<Hash, Banlist.Entry>(new HashComparator());
        
        entries.putAll(_context.banlist().getEntries());
        if (entries.isEmpty()) {
            buf.append("<i>").append(_("none")).append("</i>");
            out.write(buf.toString());
            return;
        }

        buf.append("<ul>");
        
        for (Map.Entry<Hash, Banlist.Entry> e : entries.entrySet()) {
            Hash key = e.getKey();
            Banlist.Entry entry = e.getValue();
            long expires = entry.expireOn-_context.clock().now();
            if (expires <= 0)
                continue;
            buf.append("<li>").append(_context.commSystem().renderPeerHTML(key));
            buf.append(' ');
            String expireString = DataHelper.formatDuration2(expires);
            if (key.equals(Hash.FAKE_HASH))
                buf.append(_("Permanently banned"));
            else if (expires < 5l*24*60*60*1000)
                buf.append(_("Temporary ban expiring in {0}", expireString));
            else
                buf.append(_("Banned until restart or in {0}", expireString));
            Set<String> transports = entry.transports;
            if ( (transports != null) && (!transports.isEmpty()) )
                buf.append(" on the following transport: ").append(transports);
            if (entry.cause != null) {
                buf.append("<br>\n");
                if (entry.causeCode != null)
                    buf.append(_(entry.cause, entry.causeCode));
                else
                    buf.append(_(entry.cause));
            }
            if (!key.equals(Hash.FAKE_HASH)) {
                buf.append(" (<a href=\"configpeer?peer=").append(key.toBase64())
                   .append("#unsh\">").append(_("unban now")).append("</a>)");
            }
            buf.append("</li>\n");
        }
        buf.append("</ul>\n");
        out.write(buf.toString());
        out.flush();
    }
Beispiel #21
0
  /** Enqueue the specified job */
  public void addJob(Job job) {
    if (job == null || !_alive) return;

    // This does nothing
    // if (job instanceof JobImpl)
    //    ((JobImpl)job).addedToQueue();

    long numReady = 0;
    boolean alreadyExists = false;
    boolean dropped = false;
    // getNext() is now outside the jobLock, is that ok?
    synchronized (_jobLock) {
      if (_readyJobs.contains(job)) alreadyExists = true;
      numReady = _readyJobs.size();
      if (!alreadyExists) {
        // if (_timedJobs.contains(job))
        //    alreadyExists = true;
        // Always remove and re-add, since it needs to be
        // re-sorted in the TreeSet.
        boolean removed = _timedJobs.remove(job);
        if (removed && _log.shouldLog(Log.WARN)) _log.warn("Rescheduling job: " + job);
      }

      if ((!alreadyExists) && shouldDrop(job, numReady)) {
        job.dropped();
        dropped = true;
      } else {
        if (!alreadyExists) {
          if (job.getTiming().getStartAfter() <= _context.clock().now()) {
            // don't skew us - its 'start after' its been queued, or later
            job.getTiming().setStartAfter(_context.clock().now());
            if (job instanceof JobImpl) ((JobImpl) job).madeReady();
            _readyJobs.offer(job);
          } else {
            _timedJobs.add(job);
            // only notify for _timedJobs, as _readyJobs does not use that lock
            // only notify if sooner, to reduce contention
            if (job.getTiming().getStartAfter() < _nextPumperRun) _jobLock.notifyAll();
          }
        }
      }
    }

    _context.statManager().addRateData("jobQueue.readyJobs", numReady, 0);
    if (dropped) {
      _context.statManager().addRateData("jobQueue.droppedJobs", 1, 0);
      _log.logAlways(
          Log.WARN, "Dropping job due to overload!  # ready jobs: " + numReady + ": job = " + job);
    }
  }
Beispiel #22
0
 public UPnPManager(RouterContext context, TransportManager manager) {
     _context = context;
     _manager = manager;
     _log = _context.logManager().getLog(UPnPManager.class);
     // UPnP wants to bind to IPv6 link local interfaces by default, but what UPnP router
     // is going to want to talk IPv6 anyway? Just make it easy and force IPv4 only
     org.cybergarage.upnp.UPnP.setEnable(org.cybergarage.upnp.UPnP.USE_ONLY_IPV4_ADDR);
     // set up logging in the UPnP package
     Debug.initialize(context);
     _upnp = new UPnP(context);
     _upnp.setHTTPPort(_context.getProperty(PROP_HTTP_PORT, DEFAULT_HTTP_PORT));
     _upnp.setSSDPPort(_context.getProperty(PROP_SSDP_PORT, DEFAULT_SSDP_PORT));
     _upnpCallback = new UPnPCallback();
     _rescanner = new Rescanner();
 }
Beispiel #23
0
  private static void buildZeroHop(
      RouterContext ctx, TunnelPool pool, PooledTunnelCreatorConfig cfg, BuildExecutor exec) {
    Log log = ctx.logManager().getLog(BuildRequestor.class);
    if (log.shouldLog(Log.DEBUG)) log.debug("Build zero hop tunnel " + cfg);

    exec.buildComplete(cfg, pool);
    if (cfg.isInbound()) ctx.tunnelDispatcher().joinInbound(cfg);
    else ctx.tunnelDispatcher().joinOutbound(cfg);
    pool.addTunnel(cfg);
    exec.buildSuccessful(cfg);
    ExpireJob expireJob = new ExpireJob(ctx, cfg, pool);
    cfg.setExpireJob(expireJob);
    ctx.jobQueue().addJob(expireJob);
    // can it get much easier?
  }
Beispiel #24
0
  /** @return true on success - caller should call stopPlugin() first */
  static boolean deletePlugin(RouterContext ctx, String appName) throws Exception {
    Log log = ctx.logManager().getLog(PluginStarter.class);
    File pluginDir = new File(ctx.getConfigDir(), PLUGIN_DIR + '/' + appName);
    if ((!pluginDir.exists()) || (!pluginDir.isDirectory())) {
      log.error("Cannot delete nonexistent plugin: " + appName);
      return false;
    }
    // uninstall things in clients.config
    File clientConfig = new File(pluginDir, "clients.config");
    if (clientConfig.exists()) {
      Properties props = new Properties();
      DataHelper.loadProps(props, clientConfig);
      List<ClientAppConfig> clients = ClientAppConfig.getClientApps(clientConfig);
      runClientApps(ctx, pluginDir, clients, "uninstall");
    }

    // unregister themes, and switch to default if we are unregistering the current theme
    File dir = new File(pluginDir, "console/themes");
    File[] tfiles = dir.listFiles();
    if (tfiles != null) {
      String current = ctx.getProperty(CSSHelper.PROP_THEME_NAME);
      Map<String, String> changes = new HashMap<String, String>();
      List<String> removes = new ArrayList<String>();
      for (int i = 0; i < tfiles.length; i++) {
        String name = tfiles[i].getName();
        if (tfiles[i].isDirectory() && (!Arrays.asList(STANDARD_THEMES).contains(tfiles[i]))) {
          removes.add(ConfigUIHelper.PROP_THEME_PFX + name);
          if (name.equals(current)) changes.put(CSSHelper.PROP_THEME_NAME, CSSHelper.DEFAULT_THEME);
        }
      }
      ctx.router().saveConfig(changes, removes);
    }

    boolean deleted = FileUtil.rmdir(pluginDir, false);
    Properties props = pluginProperties();
    for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
      String name = (String) iter.next();
      if (name.startsWith(PREFIX + appName + '.')) iter.remove();
    }
    if (!deleted) {
      // This happens on Windows when there are plugin jars in classpath
      // Mark it as deleted, we will try again after restart
      log.logAlways(Log.WARN, "Deletion of " + pluginDir + " failed, will try again at restart");
      props.setProperty(PREFIX + appName + ENABLED, DELETED);
    }
    storePluginProperties(props);
    return true;
  }
Beispiel #25
0
  /**
   * Returns <code>true</code> if one or more client threads are running in a given plugin.
   *
   * @param pluginName
   * @return true if running
   */
  private static boolean isClientThreadRunning(String pluginName, RouterContext ctx) {
    ThreadGroup group = pluginThreadGroups.get(pluginName);
    if (group == null) return false;
    boolean rv = group.activeCount() > 0;

    // Plugins start before the eepsite, and will create the static Timer thread
    // in RolloverFileOutputStream, which never stops. Don't count it.
    if (rv) {
      Log log = ctx.logManager().getLog(PluginStarter.class);
      Thread[] activeThreads = new Thread[128];
      int count = group.enumerate(activeThreads);
      boolean notRollover = false;
      for (int i = 0; i < count; i++) {
        if (activeThreads[i] != null) {
          String name = activeThreads[i].getName();
          if (!"org.eclipse.jetty.util.RolloverFileOutputStream".equals(name)) notRollover = true;
          if (log.shouldLog(Log.DEBUG))
            log.debug(
                "Found " + activeThreads[i].getState() + " thread for " + pluginName + ": " + name);
        }
      }
      rv = notRollover;
    }

    return rv;
  }
Beispiel #26
0
 public static void main(String args[]) {
   List<RouterContext> contexts = RouterContext.listContexts();
   if (contexts == null || contexts.isEmpty())
     throw new IllegalStateException("no router context");
   RouterConsoleRunner runner = new RouterConsoleRunner(contexts.get(0), null, args);
   runner.startup();
 }
Beispiel #27
0
 /**
  * Allow the choice as to whether failed searches should count against the peer (such as if we
  * search for a random key)
  */
 public FailedJob(RouterContext enclosingContext, RouterInfo peer, boolean penalizePeer) {
   super(enclosingContext);
   _penalizePeer = penalizePeer;
   _peer = peer.getIdentity().getHash();
   _sentOn = enclosingContext.clock().now();
   _isFloodfill = FloodfillNetworkDatabaseFacade.isFloodfill(peer);
 }
Beispiel #28
0
 public DBHistory(RouterContext context, String statGroup) {
   _context = context;
   _log = context.logManager().getLog(DBHistory.class);
   _statGroup = statGroup;
   _lastLookupReceived = -1;
   createRates(statGroup);
 }
Beispiel #29
0
 /**
  * Configure this bean to query a particular router context
  *
  * @param contextId beginning few characters of the routerHash, or null to pick
  *                  the first one we come across.
  */
 public void setContextId(String contextId) {
     try {
         _context = ContextHelper.getContext(contextId);
         _log = _context.logManager().getLog(UpdateHandler.class);
     } catch (Throwable t) {
         t.printStackTrace();
     }
 }
Beispiel #30
0
  /**
   * Initialize the message history according to the router's configuration. Call this whenever the
   * router identity changes.
   */
  public synchronized void initialize(boolean forceReinitialize) {
    if (!forceReinitialize) return;

    if (_context.router().getRouterInfo() == null) {
      _reinitializeJob.getTiming().setStartAfter(_context.clock().now() + 15 * 1000);
      _context.jobQueue().addJob(_reinitializeJob);
    } else {
      _localIdent = getName(_context.routerHash());
      // _unwrittenEntries = new ArrayList(64);
      updateSettings();
      // clear the history file on startup
      if (_firstPass) {
        File f = new File(_historyFile);
        if (!f.isAbsolute()) f = new File(_context.getLogDir(), _historyFile);
        f.delete();
        _writeJob.getTiming().setStartAfter(_context.clock().now() + WRITE_DELAY);
        _context.jobQueue().addJob(_writeJob);
        _firstPass = false;
      }
      if (_doLog)
        addEntry(getPrefix() + "** Router initialized (started up or changed identities)");
      // _submitMessageHistoryJob.getTiming().setStartAfter(_context.clock().now() + 2*60*1000);
      // _context.jobQueue().addJob(_submitMessageHistoryJob);
    }
  }