public TRTrackerServerUDP(String _name, int _port, boolean _start_up_ready) {
    super(_name, _start_up_ready);

    port = _port;

    thread_pool = new ThreadPool("TrackerServer:UDP:" + port, THREAD_POOL_SIZE);

    try {
      InetAddress bind_ip = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress();

      InetSocketAddress address;

      DatagramSocket socket;

      if (bind_ip == null) {

        address = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port);

        socket = new DatagramSocket(port);

      } else {

        current_bind_ip = bind_ip;

        address = new InetSocketAddress(bind_ip, port);

        socket = new DatagramSocket(address);
      }

      socket.setReuseAddress(true);

      dg_socket = socket;

      final InetSocketAddress f_address = address;

      Thread recv_thread =
          new AEThread("TRTrackerServerUDP:recv.loop") {
            public void runSupport() {
              recvLoop(dg_socket, f_address);
            }
          };

      recv_thread.setDaemon(true);

      recv_thread.start();

      Logger.log(new LogEvent(LOGID, "TRTrackerServerUDP: recv established on port " + port));

    } catch (Throwable e) {

      Logger.log(
          new LogEvent(
              LOGID, "TRTrackerServerUDP: " + "DatagramSocket bind failed on port " + port, e));
    }
  }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
 public void removeThread(WorkerThread thread) {
   threads.remove(thread);
   Logger.log(Level.DEBUG, Messages.getString("connection_closed", Settings.getLocale()));
   if (FancyFileServer.getGUI() != null) {
     FancyFileServer.getGUI().updateConnectionsCounter();
   }
 }
  void _pickInitial() throws MongoException {
    if (_curAddress != null) return;

    // we need to just get a server to query for ismaster
    _pickCurrent();

    try {
      _logger.info("current address beginning of _pickInitial: " + _curAddress);

      DBObject im = isMasterCmd();
      if (_isMaster(im)) return;

      synchronized (_allHosts) {
        Collections.shuffle(_allHosts);
        for (ServerAddress a : _allHosts) {
          if (_curAddress == a) continue;

          _logger.info("remote [" + _curAddress + "] -> [" + a + "]");
          _set(a);

          im = isMasterCmd();
          if (_isMaster(im)) return;

          _logger.severe("switched to: " + a + " but isn't master");
        }

        throw new MongoException("can't find master");
      }
    } catch (Exception e) {
      _logger.log(Level.SEVERE, "can't pick initial master, using random one", e);
    }
  }
  /**
   * Copies the properties of a specific <tt>DatagramPacket</tt> to another <tt>DatagramPacket</tt>.
   * The property values are not cloned.
   *
   * @param src the <tt>DatagramPacket</tt> which is to have its properties copied to <tt>dest</tt>
   * @param dest the <tt>DatagramPacket</tt> which is to have its properties set to the value of the
   *     respective properties of <tt>src</tt>
   */
  public static void copy(DatagramPacket src, DatagramPacket dest) {
    synchronized (dest) {
      dest.setAddress(src.getAddress());
      dest.setPort(src.getPort());

      byte[] srcData = src.getData();

      if (srcData == null) dest.setLength(0);
      else {
        byte[] destData = dest.getData();

        if (destData == null) dest.setLength(0);
        else {
          int destOffset = dest.getOffset();
          int destLength = destData.length - destOffset;
          int srcLength = src.getLength();

          if (destLength >= srcLength) destLength = srcLength;
          else if (logger.isLoggable(Level.WARNING)) {
            logger.log(Level.WARNING, "Truncating received DatagramPacket data!");
          }
          System.arraycopy(srcData, src.getOffset(), destData, destOffset, destLength);
          dest.setLength(destLength);
        }
      }
    }
  }
  /**
   * Perform the actual version check by connecting to the version server.
   *
   * @param data_to_send version message
   * @return version reply
   * @throws Exception if the server check connection fails
   */
  private Map performVersionCheck(
      Map data_to_send, boolean use_az_message, boolean use_http, boolean v6) throws Exception {
    Exception error = null;
    Map reply = null;

    if (use_http) {

      try {
        reply = executeHTTP(data_to_send, v6);

        reply.put("protocol_used", "HTTP");

        error = null;
      } catch (IOException e) {
        error = e;
      } catch (Exception e) {
        Debug.printStackTrace(e);
        error = e;
      }
    }

    if (reply == null && use_az_message) {

      try {
        reply = executeAZMessage(data_to_send, v6);

        reply.put("protocol_used", "AZMSG");
      } catch (IOException e) {
        error = e;
      } catch (Exception e) {
        Debug.printStackTrace(e);
        error = e;
      }
    }
    if (error != null) {

      throw (error);
    }

    if (Logger.isEnabled())
      Logger.log(
          new LogEvent(
              LOGID,
              "VersionCheckClient server "
                  + "version check successful. Received "
                  + reply.size()
                  + " reply keys."));

    if (v6) {

      last_check_time_v6 = SystemTime.getCurrentTime();

    } else {

      last_check_time_v4 = SystemTime.getCurrentTime();
    }

    return reply;
  }
 @FXML
 private void Ok_click(ActionEvent event) {
   logger.entry();
   LogEntry log = new LogEntry("6.16", "Local Delete Object Instance service");
   try {
     ObjectInstanceHandle instanceHandle =
         rtiAmb
             .getObjectInstanceHandleFactory()
             .decode(
                 ByteBuffer.allocate(4)
                     .putInt(Integer.parseInt(ObjectInstanceDesignator.getText()))
                     .array(),
                 0);
     log.getSuppliedArguments()
         .add(
             new ClassValuePair(
                 "Object instance designator",
                 ObjectInstanceHandle.class,
                 instanceHandle.toString()));
     rtiAmb.localDeleteObjectInstance(instanceHandle);
     log.setDescription("Local Object instance deleted successfully");
     log.setLogType(LogEntryType.REQUEST);
   } catch (FederateNotExecutionMember
       | NotConnected
       | NumberFormatException
       | CouldNotDecode
       | RTIinternalError
       | OwnershipAcquisitionPending
       | FederateOwnsAttributes
       | ObjectInstanceNotKnown
       | SaveInProgress
       | RestoreInProgress ex) {
     log.setException(ex);
     log.setLogType(LogEntryType.ERROR);
     logger.log(Level.ERROR, ex.getMessage(), ex);
   } catch (Exception ex) {
     log.setException(ex);
     log.setLogType(LogEntryType.FATAL);
     logger.log(Level.FATAL, ex.getMessage(), ex);
   }
   logEntries.add(log);
   ((Stage) OkButton.getScene().getWindow()).close();
   logger.exit();
 }
  /** Start the server and begin accepting incoming connections. */
  public void start() {
    try {
      this_mon.enter();

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

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

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

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

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

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

      this_mon.exit();
    }
  }
Beispiel #9
0
  /** Verify and invoke main if present in the specified class. */
  public static void invokeApplicationMain(Class mainClass, String[] args)
      throws InvocationTargetException, IllegalAccessException, ClassNotFoundException {
    String err = localStrings.getLocalString("utility.no.main", "", new Object[] {mainClass});

    // determine the main method using reflection
    // verify that it is public static void and takes
    // String[] as the only argument
    Method mainMethod = null;
    try {
      mainMethod = mainClass.getMethod("main", new Class[] {String[].class});
    } catch (NoSuchMethodException msme) {
      _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility", msme);
      throw new ClassNotFoundException(err);
    }

    // check modifiers: public static
    int modifiers = mainMethod.getModifiers();
    if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) {
      err =
          localStrings.getLocalString(
              "utility.main.notpublicorstatic",
              "The main method is either not public or not static");
      _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notpublicorstatic");
      throw new ClassNotFoundException(err);
    }

    // check return type and exceptions
    if (!mainMethod.getReturnType().equals(Void.TYPE)) {
      err =
          localStrings.getLocalString(
              "utility.main.notvoid", "The main method's return type is not void ");
      _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notvoid");
      throw new ClassNotFoundException(err);
    }

    // build args to the main and call it
    Object params[] = new Object[1];
    params[0] = args;
    mainMethod.invoke(null, params);
  }
  private String findDriverByUrlImpl(String url) {
    for (int i = 0; i < _driverList.size(); i++) {
      try {
        Driver driver = (Driver) _driverList.get(i);

        if (driver.acceptsURL(url)) return driver.getClass().getName();
      } catch (Exception e) {
        log.log(Level.FINE, e.toString(), e);
      }
    }

    return null;
  }
    @Override
    public void run() {
      byte[] buf = new byte[100];
      try {
        int len;
        while ((len = in.read(buf)) > 0) {
          String output = new String(buf, 0, len);
          Thread t = Thread.currentThread();
          System.out.println(
              "thread " + t.getName() + " " + t.getId() + ", read " + len + " bytes: " + output);
        }

      } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to read", e);

      } finally {
        try {
          in.close();
        } catch (IOException e) {
          logger.log(Level.SEVERE, "Failed to close", e);
        }
      }
    }
  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();
    }
  }
  public void start(int options) throws BundleException {
    if (getState() == UNINSTALLED) throw new IllegalStateException("Bundle.UNINSTALLED");

    BundleStartLevel bundleStartLevel = adapt(BundleStartLevel.class);
    FrameworkStartLevel frameworkStartLevel = getFramework().adapt(FrameworkStartLevel.class);

    if ((bundleStartLevel != null)
        && (bundleStartLevel.getStartLevel() > frameworkStartLevel.getStartLevel())) {
      if ((options & START_TRANSIENT) == START_TRANSIENT) throw new BundleException("startLevel");
      else return;
    }

    if (getState() == ACTIVE) return;

    if (getState() == INSTALLED) setState(RESOLVED);

    setState(STARTING);

    String location = getLocation();

    if (location != null) {
      BundleActivator bundleActivator = null;
      Throwable exception = null;

      try {
        bundleActivator = (BundleActivator) loadClass(location.replace('/', '.')).newInstance();

        bundleActivator.start(getBundleContext());
      } catch (Throwable t) {
        logger.log(Level.SEVERE, "Error starting bundle: " + bundleActivator, t);

        if (t instanceof ThreadDeath) throw (ThreadDeath) t;
        else exception = t;
      }

      if (exception == null) this.bundleActivator = bundleActivator;
      else {
        setState(STOPPING);
        setState(RESOLVED);
        getFramework().fireBundleEvent(BundleEvent.STOPPED, this);
        throw new BundleException("BundleActivator.start", exception);
      }
    }

    if (getState() == UNINSTALLED) throw new IllegalStateException("Bundle.UNINSTALLED");

    setState(ACTIVE);
  }
Beispiel #14
0
 public static void startTracker(Configuration conf) throws IOException {
   if (tracker != null) throw new IOException("JobTracker already running.");
   while (true) {
     try {
       tracker = new JobTracker(conf);
       break;
     } catch (IOException e) {
       LOG.log(Level.WARNING, "Starting tracker", e);
     }
     try {
       Thread.sleep(1000);
     } catch (InterruptedException e) {
     }
   }
   tracker.offerService();
 }
  protected void recvLoop(DatagramSocket socket, InetSocketAddress address) {
    long successful_accepts = 0;
    long failed_accepts = 0;

    while (!closed) {

      try {
        byte[] buf = new byte[PRUDPPacket.MAX_PACKET_SIZE];

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

        socket.receive(packet);

        successful_accepts++;

        failed_accepts = 0;

        String ip = packet.getAddress().getHostAddress();

        if (!ip_filter.isInRange(ip, "Tracker", null)) {

          thread_pool.run(new TRTrackerServerProcessorUDP(this, socket, packet));
        }

      } catch (Throwable e) {

        if (!closed) {

          failed_accepts++;

          Logger.log(new LogEvent(LOGID, "TRTrackerServer: receive failed on port " + port, e));

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

            // looks like its not going to work...
            // some kind of socket problem

            Logger.logTextResource(
                new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "Network.alert.acceptfail"),
                new String[] {"" + port, "UDP"});

            break;
          }
        }
      }
    }
  }
Beispiel #16
0
  public HostInfo(InetAddress address, String name) {
    super();

    String SLevel = System.getProperty("jmdns.debug");
    if (SLevel == null) SLevel = "INFO";
    logger.setLevel(Level.parse(SLevel));

    this.address = address;
    this.name = name;
    if (address != null) {
      try {
        interfaze = NetworkInterface.getByInetAddress(address);
      } catch (Exception exception) {
        // FIXME Shouldn't we take an action here?
        logger.log(Level.WARNING, "LocalHostInfo() exception ", exception);
      }
    }
  }
  private Map executeAZMessage(Map data_to_send, boolean v6) throws Exception {

    if (v6 && !enable_v6) {

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

    String host = getHost(v6, AZ_MSG_SERVER_ADDRESS_V6, AZ_MSG_SERVER_ADDRESS_V4);

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

    ClientMessageService msg_service = null;
    Map reply = null;

    try {
      msg_service =
          ClientMessageServiceClient.getServerService(host, AZ_MSG_SERVER_PORT, MESSAGE_TYPE_ID);

      msg_service.sendMessage(data_to_send); // send our version message

      reply = msg_service.receiveMessage(); // get the server reply

      preProcessReply(reply, v6);

    } finally {

      if (msg_service != null) {

        msg_service.close();
      }
    }

    return (reply);
  }
Beispiel #18
0
 // /home/jean/Área de Trabalho/Link para Dropbox/workspace/GSPAnalyzer/grails app
 // examples/rgms-master/grails-app/views/bookChapter/show.gsp
 private void process(String uri) {
   try {
     URL url;
     try {
       url = new URL(uri);
     } catch (java.net.MalformedURLException mfu) {
       int idx = uri.indexOf(':');
       if (idx == -1 || idx == 1) {
         // try file
         url = new URL("file:" + uri);
       } else {
         throw mfu;
       }
     }
     // Call SimpleHtmlRendererContext.navigate()
     // which implements incremental rendering.
     this.rcontext.navigate(url, null);
   } catch (Exception err) {
     logger.log(Level.SEVERE, "Error trying to load URI=[" + uri + "].", err);
   }
 }
Beispiel #19
0
  /** Create the working folder (later deleted) */
  private void createWorkingFolder() throws RuntimeException {
    if (this.workingFolder == null
        && (this.workingFolderPath == null || this.workingFolderPath.equals("")))
      throw new RuntimeException("Class needs a valid working folder!");

    if (this.workingFolder == null) {
      this.workingFolder = new File(this.workingFolderPath);
    } else {
      // sanitize working folder. If it exists and is a directory, delete
      // it. If it is a file, refuse to continue.
      if (this.workingFolder.exists()) {
        if (this.workingFolder.isFile()) {
          throw new RuntimeException("Working folder exists, and is a file!");
        }
        if (this.workingFolder.isDirectory()) {
          Logger.log("Deleting existing working directory.");
          FileUtils.deleteFolder(this.workingFolder);
        }
      }
    }

    // create temporary directory for the local repository...
    this.workingFolder = FileUtils.createFolder(this.workingFolder);
  }
  protected Map getVersionCheckInfoSupport(
      String reason, boolean only_if_cached, boolean force, boolean v6) {
    try {
      synchronized (listeners) {
        if (REASON_UPDATE_CHECK_START.equals(reason)) {
          startCheckRan = true;
        }
        for (VersionCheckClientListener l : listeners) {
          l.versionCheckStarted(reason);
        }
      }
    } catch (Throwable t) {
      Debug.out(t);
    }
    if (v6) {

      if (enable_v6) {

        try {
          check_mon.enter();

          long time_diff = SystemTime.getCurrentTime() - last_check_time_v6;

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

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

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

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

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

      return last_check_data_v6;

    } else {

      try {
        check_mon.enter();

        long time_diff = SystemTime.getCurrentTime() - last_check_time_v4;

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

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

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

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

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

            try {
              if (AzureusCoreFactory.isCoreAvailable()) {

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

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

                  PluginInterface plugin = plugins[i];

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

                  if (data != null) {

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

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

      last_feature_flag_cache_time = 0;

      return last_check_data_v4;
    }
  }
  private Map executeTCP(Map data_to_send, InetAddress bind_ip, int bind_port, boolean v6)
      throws Exception {
    if (v6 && !enable_v6) {

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

    String host = getHost(v6, TCP_SERVER_ADDRESS_V6, TCP_SERVER_ADDRESS_V4);

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

    String get_str = getHTTPGetString(data_to_send, false, v6);

    Socket socket = null;

    try {
      socket = new Socket();

      if (bind_ip != null) {

        socket.bind(new InetSocketAddress(bind_ip, bind_port));

      } else if (bind_port != 0) {

        socket.bind(new InetSocketAddress(bind_port));
      }

      socket.setSoTimeout(10000);

      socket.connect(new InetSocketAddress(host, TCP_SERVER_PORT), 10000);

      OutputStream os = socket.getOutputStream();

      os.write(get_str.getBytes("ISO-8859-1"));

      os.flush();

      InputStream is = socket.getInputStream();

      byte[] buffer = new byte[1];

      String header = "";

      int content_length = -1;

      while (true) {

        int len = is.read(buffer);

        if (len <= 0) {

          break;
        }

        header += (char) buffer[0];

        if (header.endsWith("\r\n\r\n")) {

          header = header.toLowerCase(MessageText.LOCALE_ENGLISH);

          int pos = header.indexOf("content-length:");

          if (pos == -1) {

            throw (new IOException("content length missing"));
          }

          header = header.substring(pos + 15);

          pos = header.indexOf('\r');

          header = header.substring(0, pos).trim();

          content_length = Integer.parseInt(header);

          if (content_length > 10000) {

            throw (new IOException("content length too large"));
          }

          break;
        }

        if (header.length() > 2048) {

          throw (new IOException("header too large"));
        }
      }

      ByteArrayOutputStream baos = new ByteArrayOutputStream(content_length);

      buffer = new byte[content_length];

      while (content_length > 0) {

        int len = is.read(buffer);

        if (len <= 0) {

          break;
        }

        baos.write(buffer, 0, len);

        content_length -= len;
      }

      if (content_length != 0) {

        throw (new IOException("error reading reply"));
      }

      byte[] reply_bytes = baos.toByteArray();

      Map reply = BDecoder.decode(new BufferedInputStream(new ByteArrayInputStream(reply_bytes)));

      preProcessReply(reply, v6);

      return (reply);

    } finally {

      if (socket != null) {

        try {
          socket.close();

        } catch (Throwable e) {

        }
      }
    }
  }
  public void runSupport() {
    byte[] input_buffer = new byte[request_dg.getLength()];

    System.arraycopy(request_dg.getData(), 0, input_buffer, 0, input_buffer.length);

    int packet_data_length = input_buffer.length;

    String auth_user = null;
    byte[] auth_user_bytes = null;
    byte[] auth_hash = null;

    if (server.isTrackerPasswordEnabled()) {

      // auth detail should be attached to the packet. Auth details are 16
      // bytes

      if (input_buffer.length < 17) {

        Logger.log(
            new LogEvent(
                LOGID,
                LogEvent.LT_WARNING,
                "TRTrackerServerProcessorUDP: " + "packet received but authorisation missing"));

        return;
      }

      packet_data_length -= 16;

      auth_user_bytes = new byte[8];

      auth_hash = new byte[8];

      System.arraycopy(input_buffer, packet_data_length, auth_user_bytes, 0, 8);

      int user_len = 0;

      while (user_len < 8 && auth_user_bytes[user_len] != 0) {

        user_len++;
      }

      auth_user = new String(auth_user_bytes, 0, user_len);

      System.arraycopy(input_buffer, packet_data_length + 8, auth_hash, 0, 8);
    }

    DataInputStream is =
        new DataInputStream(new ByteArrayInputStream(input_buffer, 0, packet_data_length));

    try {
      String client_ip_address = request_dg.getAddress().getHostAddress();

      PRUDPPacketRequest request = PRUDPPacketRequest.deserialiseRequest(null, is);

      Logger.log(
          new LogEvent(
              LOGID, "TRTrackerServerProcessorUDP: packet received: " + request.getString()));

      PRUDPPacket reply = null;
      TRTrackerServerTorrentImpl torrent = null;

      if (auth_user_bytes != null) {

        // user name is irrelevant as we only have one at the moment

        // <parg_home> so <new_packet> = <old_packet> + <user_padded_to_8_bytes> + <hash>
        // <parg_home> where <hash> = first 8 bytes of sha1(<old_packet> + <user_padded_to_8> +
        // sha1(pass))
        // <XTF> Yes

        byte[] sha1_pw = null;

        if (server.hasExternalAuthorisation()) {

          try {
            URL resource = new URL("udp://" + server.getHost() + ":" + server.getPort() + "/");

            sha1_pw = server.performExternalAuthorisation(resource, auth_user);

          } catch (MalformedURLException e) {

            Debug.printStackTrace(e);
          }

          if (sha1_pw == null) {

            Logger.log(
                new LogEvent(
                    LOGID,
                    LogEvent.LT_ERROR,
                    "TRTrackerServerProcessorUDP: auth fails for user '" + auth_user + "'"));

            reply = new PRUDPPacketReplyError(request.getTransactionId(), "Access Denied");
          }
        } else {

          sha1_pw = server.getPassword();
        }

        // if we haven't already failed then check the PW

        if (reply == null) {

          SHA1Hasher hasher = new SHA1Hasher();

          hasher.update(input_buffer, 0, packet_data_length);
          hasher.update(auth_user_bytes);
          hasher.update(sha1_pw);

          byte[] digest = hasher.getDigest();

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

            if (auth_hash[i] != digest[i]) {

              Logger.log(
                  new LogEvent(
                      LOGID,
                      LogEvent.LT_ERROR,
                      "TRTrackerServerProcessorUDP: auth fails for user '" + auth_user + "'"));

              reply = new PRUDPPacketReplyError(request.getTransactionId(), "Access Denied");

              break;
            }
          }
        }
      }

      int request_type = TRTrackerServerRequest.RT_UNKNOWN;

      if (reply == null) {

        if (server.isEnabled()) {

          try {
            int type = request.getAction();

            if (type == PRUDPPacketTracker.ACT_REQUEST_CONNECT) {

              reply = handleConnect(client_ip_address, request);

            } else if (type == PRUDPPacketTracker.ACT_REQUEST_ANNOUNCE) {

              Object[] x =
                  handleAnnounceAndScrape(
                      client_ip_address, request, TRTrackerServerRequest.RT_ANNOUNCE);

              if (x == null) {

                throw (new Exception("Connection ID mismatch"));
              }

              reply = (PRUDPPacket) x[0];
              torrent = (TRTrackerServerTorrentImpl) x[1];

              request_type = TRTrackerServerRequest.RT_ANNOUNCE;

            } else if (type == PRUDPPacketTracker.ACT_REQUEST_SCRAPE) {

              Object[] x =
                  handleAnnounceAndScrape(
                      client_ip_address, request, TRTrackerServerRequest.RT_SCRAPE);

              if (x == null) {

                throw (new Exception("Connection ID mismatch"));
              }

              reply = (PRUDPPacket) x[0];
              torrent = (TRTrackerServerTorrentImpl) x[1];

              request_type = TRTrackerServerRequest.RT_SCRAPE;

            } else {

              reply = new PRUDPPacketReplyError(request.getTransactionId(), "unsupported action");
            }
          } catch (Throwable e) {

            // e.printStackTrace();

            String error = e.getMessage();

            if (error == null) {

              error = e.toString();
            }

            reply = new PRUDPPacketReplyError(request.getTransactionId(), error);
          }
        } else {

          System.out.println("UDP Tracker: replying 'disabled' to " + client_ip_address);

          reply = new PRUDPPacketReplyError(request.getTransactionId(), "UDP Tracker disabled");
        }
      }

      if (reply != null) {

        InetAddress address = request_dg.getAddress();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DataOutputStream os = new DataOutputStream(baos);

        reply.serialise(os);

        byte[] output_buffer = baos.toByteArray();

        DatagramPacket reply_packet =
            new DatagramPacket(output_buffer, output_buffer.length, address, request_dg.getPort());

        socket.send(reply_packet);

        server.updateStats(request_type, torrent, input_buffer.length, output_buffer.length);
      }

    } catch (Throwable e) {

      Logger.log(new LogEvent(LOGID, "TRTrackerServerProcessorUDP: processing fails", e));
    } finally {

      try {
        is.close();

      } catch (Throwable e) {

      }
    }
  }
Beispiel #23
0
  /** The listening thread's run method. */
  @Override
  public void run() {
    DatagramPacket packet = null;

    while (this.running) {
      try {
        IceSocketWrapper localSock;

        synchronized (sockLock) {
          if (!running) return;

          localSock = this.sock;
        }

        /*
         * Make sure localSock's receiveBufferSize is taken into
         * account including after it gets changed.
         */
        int receiveBufferSize = 1500;
        /*
        if(localSock.getTCPSocket() != null)
        {
            receiveBufferSize = localSock.getTCPSocket().
                getReceiveBufferSize();
        }
        else if(localSock.getUDPSocket() != null)
        {
            receiveBufferSize = localSock.getUDPSocket().
                getReceiveBufferSize();
        }
        */

        if (packet == null) {
          packet = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize);
        } else {
          byte[] packetData = packet.getData();

          if ((packetData == null) || (packetData.length < receiveBufferSize)) {
            packet.setData(new byte[receiveBufferSize], 0, receiveBufferSize);
          } else {
            /*
             * XXX Tell the packet it is large enough because the
             * socket will not look at the length of the data array
             * property and will just respect the length property.
             */
            packet.setLength(receiveBufferSize);
          }
        }

        localSock.receive(packet);

        // get lost if we are no longer running.
        if (!running) return;

        logger.finest("received datagram");

        RawMessage rawMessage =
            new RawMessage(
                packet.getData(),
                packet.getLength(),
                new TransportAddress(
                    packet.getAddress(), packet.getPort(), listenAddress.getTransport()),
                listenAddress);

        messageQueue.add(rawMessage);
      } catch (SocketException ex) {
        if (running) {
          logger.log(
              Level.WARNING, "Connector died: " + listenAddress + " -> " + remoteAddress, ex);

          stop();
          // Something wrong has happened
          errorHandler.handleFatalError(
              this, "A socket exception was thrown" + " while trying to receive a message.", ex);
        } else {
          // The exception was most probably caused by calling
          // this.stop().
        }
      } catch (ClosedChannelException cce) {
        logger.log(Level.WARNING, "A net access point has gone useless:", cce);

        stop();
        errorHandler.handleFatalError(
            this, "ClosedChannelException occurred while listening" + " for messages!", cce);
      } catch (IOException ex) {
        logger.log(Level.WARNING, "A net access point has gone useless:", ex);

        errorHandler.handleError(ex.getMessage(), ex);
        // do not stop the thread;
      } catch (Throwable ex) {
        logger.log(Level.WARNING, "A net access point has gone useless:", ex);

        stop();
        errorHandler.handleFatalError(
            this, "Unknown error occurred while listening for messages!", ex);
      }
    }
  }
  @FXML
  private void OK_click(ActionEvent event) {
    logger.entry();
    FederateHandle federateHandle;
    LogEntry log = new LogEntry("4.9", "Join Federation Execution service");
    try {
      if (!FederateName.getText().isEmpty()) {
        log.getSuppliedArguments()
            .add(new ClassValuePair("Federate Name", String.class, FederateName.getText()));
      }
      log.getSuppliedArguments()
          .add(new ClassValuePair("Federate Type", String.class, FederateType.getText()));
      log.getSuppliedArguments()
          .add(
              new ClassValuePair(
                  "Federation Execution Name", String.class, FederationExecutionName.getText()));
      List<URL> foms = new ArrayList<>();
      int i = 1;
      for (File file : FomModuleDesignators.getFiles()) {
        foms.add(file.toURI().toURL());
        log.getSuppliedArguments()
            .add(
                new ClassValuePair(
                    "FOM Module Deisgnator " + i++, URL.class, file.toURI().toURL().toString()));
      }
      if (FederateName.getText().isEmpty() && FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(), FederationExecutionName.getText());
      } else if (FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(), FederateType.getText(), FederationExecutionName.getText());
      } else if (FederateName.getText().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      } else {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(),
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      }
      log.getReturnedArguments()
          .add(
              new ClassValuePair(
                  "Federate Handle", FederateHandle.class, federateHandle.toString()));
      log.setDescription("Federate joined federation execution successfully");
      log.setLogType(LogEntryType.REQUEST);
      logicalTimeFactory = rtiAmb.getTimeFactory();
      currentLogicalTime = logicalTimeFactory.makeInitial();

      // subscribe to HLAcurrentFDD to retrieve FDD
      ObjectClassHandle FederationHandle =
          rtiAmb.getObjectClassHandle("HLAobjectRoot.HLAmanager.HLAfederation");
      currentFDDHandle = rtiAmb.getAttributeHandle(FederationHandle, "HLAcurrentFDD");
      AttributeHandleSet set = rtiAmb.getAttributeHandleSetFactory().create();
      set.add(currentFDDHandle);
      rtiAmb.subscribeObjectClassAttributes(FederationHandle, set);
      rtiAmb.requestAttributeValueUpdate(FederationHandle, set, null);
      // In case of HLA_EVOKED we require this line to receive the FDD
      rtiAmb.evokeMultipleCallbacks(
          .05,
          1); // evoke one callback will not be enough because the reflect attribute is the second
              // one
    } catch (CouldNotCreateLogicalTimeFactory
        | CallNotAllowedFromWithinCallback
        | CouldNotOpenFDD
        | ErrorReadingFDD
        | InconsistentFDD
        | FederateNameAlreadyInUse
        | FederateAlreadyExecutionMember
        | FederationExecutionDoesNotExist
        | SaveInProgress
        | RestoreInProgress
        | NotConnected
        | RTIinternalError ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.ERROR);
      logger.log(Level.ERROR, ex.getMessage(), ex);
    } catch (Exception ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.FATAL);
      logger.log(Level.FATAL, ex.getMessage(), ex);
    }
    logEntries.add(log);
    ((Stage) FederationExecutionName.getScene().getWindow()).close();
    logger.exit();
  }
  public void run() {
    try {
      this.serverSocket = new ServerSocket(Settings.getPropertyInteger("server_port"));
    } catch (Exception e) {
      Logger.log(
          Level.WARNING,
          Messages.getString("can_not_open_port_", Settings.getLocale())
              + Settings.getPropertyInteger("server_port"));
      if (FancyFileServer.getGUI() != null) {
        FancyFileServer.getGUI().updateServerStatus();
      }
      return;
    }

    running = true;

    this.parameters = new BasicHttpParams();
    this.parameters.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000);
    this.parameters.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    this.parameters.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    this.parameters.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true);
    this.parameters.setParameter(
        HttpProtocolParams.ORIGIN_SERVER,
        FancyFileServer.NAME.replaceAll("\\s", "-") + "/" + FancyFileServer.VERSION);

    Logger.log(Level.INFO, Messages.getString("server_started", Settings.getLocale()));

    try {
      Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) interfaces.nextElement();
        if (i.isLoopback() || i.isVirtual()) {
          continue;
        }
        Enumeration<InetAddress> addresses = i.getInetAddresses();
        while (addresses.hasMoreElements()) {
          InetAddress a = (InetAddress) addresses.nextElement();
          if (a instanceof Inet4Address) {
            Logger.log(
                Level.INFO,
                Messages.getString("server_address_", Settings.getLocale())
                    + "http://"
                    + a.getHostAddress()
                    + ":"
                    + serverSocket.getLocalPort()
                    + "/");
          }
        }
      }
    } catch (Exception e) {
      Logger.log(
          Level.WARNING,
          Messages.getString("can_not_get_server_address_", Settings.getLocale()) + e.getMessage());
    }

    if (FancyFileServer.getGUI() != null) {
      FancyFileServer.getGUI().updateServerStatus();
    }

    while (running) {
      try {
        /** Set up HTTP connection */
        Socket socket = this.serverSocket.accept();
        DefaultHttpServerConnection connection = new DefaultHttpServerConnection();
        Logger.log(
            Level.DEBUG,
            Messages.getString("incoming_connection_from_", Settings.getLocale())
                + socket.getInetAddress().getHostAddress());
        connection.bind(socket, this.parameters);

        /** Set up HTTP protocol processor */
        BasicHttpProcessor processor = new BasicHttpProcessor();
        processor.addInterceptor(new ResponseDate());
        processor.addInterceptor(new ResponseServer());
        processor.addInterceptor(new ResponseContent());
        processor.addInterceptor(new ResponseConnControl());

        /** Set up HTTP request handlers */
        HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
        registry.register("*", new FileHandler());

        /** Set up HTTP service */
        HttpService service =
            new HttpService(
                processor,
                new DefaultConnectionReuseStrategy(),
                new DefaultHttpResponseFactory(),
                registry,
                this.parameters);

        /** Start worker thread */
        WorkerThread t = new WorkerThread(this, service, connection);
        t.setDaemon(true);
        t.start();
      } catch (IOException e) {
        if (running) {
          running = false;
          Logger.log(
              Level.SEVERE,
              Messages.getString("i_o_error_", Settings.getLocale()) + e.getMessage());
          break;
        }
      }
    }

    if (FancyFileServer.getGUI() != null) {
      FancyFileServer.getGUI().updateServerStatus();
    }
    Logger.log(Level.INFO, Messages.getString("server_stopped", Settings.getLocale()));
  }
  protected void preProcessReply(Map reply, final boolean v6) {
    NetworkAdmin admin = NetworkAdmin.getSingleton();

    try {
      byte[] address = (byte[]) reply.get("source_ip_address");

      InetAddress my_ip = InetAddress.getByName(new String(address));

      NetworkAdminASN old_asn = admin.getCurrentASN();

      NetworkAdminASN new_asn = admin.lookupCurrentASN(my_ip);

      if (!new_asn.sameAs(old_asn)) {

        // kick off a secondary version check to communicate the new information

        if (!secondary_check_done) {

          secondary_check_done = true;

          new AEThread("Secondary version check", true) {
            public void runSupport() {
              getVersionCheckInfoSupport(REASON_SECONDARY_CHECK, false, true, v6);
            }
          }.start();
        }
      }
    } catch (Throwable e) {

      Debug.printStackTrace(e);
    }

    Long as_advice = (Long) reply.get("as_advice");

    if (as_advice != null) {

      NetworkAdminASN current_asn = admin.getCurrentASN();

      String asn = current_asn.getASName();

      if (asn != null) {

        long advice = as_advice.longValue();

        if (advice != 0) {

          // require crypto

          String done_asn = COConfigurationManager.getStringParameter("ASN Advice Followed", "");

          if (!done_asn.equals(asn)) {

            COConfigurationManager.setParameter("ASN Advice Followed", asn);

            boolean change = advice == 1 || advice == 2;
            boolean alert = advice == 1 || advice == 3;

            if (!COConfigurationManager.getBooleanParameter(
                "network.transport.encrypted.require")) {

              if (change) {

                COConfigurationManager.setParameter("network.transport.encrypted.require", true);
              }

              if (alert) {

                String msg = MessageText.getString("crypto.alert.as.warning", new String[] {asn});

                Logger.log(new LogAlert(false, LogAlert.AT_WARNING, msg));
              }
            }
          }
        }
      }
    }

    // set ui.toolbar.uiswitcher based on instructions from tracker
    // Really shouldn't be in VersionCheck client, but instead have some
    // listener and have the code elsewhere.  Simply calling
    // getVersionCheckInfo from "code elsewhere" (to get the cached result)
    // caused a deadlock at startup.
    Long lEnabledUISwitcher = (Long) reply.get("ui.toolbar.uiswitcher");
    if (lEnabledUISwitcher != null) {
      COConfigurationManager.setBooleanDefault(
          "ui.toolbar.uiswitcher", lEnabledUISwitcher.longValue() == 1);
    }
  }