Ejemplo n.º 1
0
 /** List file names */
 public Enumeration nlst(String s) throws IOException {
   InetAddress inetAddress = InetAddress.getLocalHost();
   byte ab[] = inetAddress.getAddress();
   serverSocket_ = new ServerSocket(0, 1);
   StringBuffer sb = new StringBuffer(32);
   sb.append("PORT ");
   for (int i = 0; i < ab.length; i++) {
     sb.append(String.valueOf(ab[i] & 255));
     sb.append(",");
   }
   sb.append(String.valueOf(serverSocket_.getLocalPort() >>> 8 & 255));
   sb.append(",");
   sb.append(String.valueOf(serverSocket_.getLocalPort() & 255));
   if (issueCommand(sb.toString()) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   } else if (issueCommand("NLST " + ((s == null) ? "" : s)) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   }
   dataSocket_ = serverSocket_.accept();
   serverSocket_.close();
   serverSocket_ = null;
   Vector v = readServerResponse_(dataSocket_.getInputStream());
   dataSocket_.close();
   dataSocket_ = null;
   return (v == null) ? null : v.elements();
 }
Ejemplo n.º 2
0
  public TCPConnectionMap(
      String service_name,
      ThreadFactory f,
      SocketFactory socket_factory,
      Receiver r,
      InetAddress bind_addr,
      InetAddress external_addr,
      int srv_port,
      int max_port,
      long reaper_interval,
      long conn_expire_time)
      throws Exception {
    this.mapper = new Mapper(f, reaper_interval);
    this.receiver = r;
    this.bind_addr = bind_addr;
    this.conn_expire_time = conn_expire_time;
    if (socket_factory != null) this.socket_factory = socket_factory;
    this.srv_sock =
        Util.createServerSocket(this.socket_factory, service_name, bind_addr, srv_port, max_port);

    if (external_addr != null) local_addr = new IpAddress(external_addr, srv_sock.getLocalPort());
    else if (bind_addr != null) local_addr = new IpAddress(bind_addr, srv_sock.getLocalPort());
    else local_addr = new IpAddress(srv_sock.getLocalPort());

    acceptor = f.newThread(thread_group, new ConnectionAcceptor(), "ConnectionMap.Acceptor");
  }
Ejemplo n.º 3
0
  public void run() {
    while (true) {
      try {
        System.out.println("Server name: " + serverSocket.getInetAddress().getHostName());
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to " + server.getRemoteSocketAddress());

        ObjectInputStream objectIn = new ObjectInputStream(server.getInputStream());

        try {
          Recipe rec = (Recipe) objectIn.readObject();
          startHMI(rec, rec.getProductName());

          //				System.out.println("Object Received: width: "+rec.getWidth()+" height:
          // "+rec.getHeight());
        } catch (ClassNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out.writeUTF(
            "Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
        server.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
Ejemplo n.º 4
0
 private void writeHostAndPortToFile(File portFile) {
   String host = socket.getInetAddress().getHostName();
   int port = socket.getLocalPort();
   // The motivation for the Log.warn would be better satisfied by Bug 38.
   Log.warn("echo " + host + ":" + port + " > " + portFile);
   StringUtilities.writeFile(portFile, host + ":" + port + "\n");
 }
Ejemplo n.º 5
0
  public SetIfModifiedSince() throws Exception {

    serverSock = new ServerSocket(0);
    int port = serverSock.getLocalPort();

    Thread thr = new Thread(this);
    thr.start();

    Date date = new Date(new Date().getTime() - 1440000); // this time yesterday
    URL url;
    HttpURLConnection con;

    // url = new URL(args[0]);
    url = new URL("http://localhost:" + String.valueOf(port) + "/anything");
    con = (HttpURLConnection) url.openConnection();

    con.setIfModifiedSince(date.getTime());
    con.connect();
    int ret = con.getResponseCode();

    if (ret == 304) {
      System.out.println("Success!");
    } else {
      throw new RuntimeException(
          "Test failed! Http return code using setIfModified method is:"
              + ret
              + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method");
    }
  }
Ejemplo n.º 6
0
  /**
   * serviceClient accepts a client connection and reads lines from the socket. Each line is handed
   * to executeCommand for parsing and execution.
   */
  public void serviceClient() throws java.io.IOException {
    System.out.println("Accepting clients now");
    Socket clientConnection = serverSocket.accept();

    // Arrange to read input from the Socket
    InputStream inputStream = clientConnection.getInputStream();
    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    // Arrange to write result across Socket back to client
    OutputStream outputStream = clientConnection.getOutputStream();
    PrintStream printStream = new PrintStream(outputStream);

    System.out.println(
        "Client acquired on port #" + serverSocket.getLocalPort() + ", reading from socket");

    try {
      String commandLine;
      while ((commandLine = bufferedReader.readLine()) != null) {
        try {
          Float result = executeCommand(commandLine);
          // Only BALANCE command returns non-null
          if (result != null) {
            printStream.println(result); // Write it back to the client
          }
        } catch (ATMException atmex) {
          System.out.println("ERROR: " + atmex);
        }
      }
    } catch (SocketException sException) {
      // client has stopped sending commands.  Exit gracefully.
      System.out.println("done");
    }
  }
Ejemplo n.º 7
0
  /** Test the http protocol handler with one WWW-Authenticate header with the value "NTLM". */
  static void testNTLM() throws Exception {
    // server reply
    String reply = authReplyFor("NTLM");

    System.out.println("====================================");
    System.out.println("Expect client to fail with 401 Unauthorized");
    System.out.println(reply);

    try (ServerSocket ss = new ServerSocket(0)) {
      Client client = new Client(ss.getLocalPort());
      Thread thr = new Thread(client);
      thr.start();

      // client ---- GET ---> server
      // client <--- 401 ---- client
      try (Socket s = ss.accept()) {
        new MessageHeader().parseHeader(s.getInputStream());
        s.getOutputStream().write(reply.getBytes("US-ASCII"));
      }

      // the client should fail with 401
      System.out.println("Waiting for client to terminate");
      thr.join();
      IOException ioe = client.ioException();
      if (ioe != null) System.out.println("Client failed: " + ioe);
      int respCode = client.respCode();
      if (respCode != 0 && respCode != -1)
        System.out.println("Client received HTTP response code: " + respCode);
      if (respCode != HttpURLConnection.HTTP_UNAUTHORIZED)
        throw new RuntimeException("Unexpected response code");
    }
  }
Ejemplo n.º 8
0
  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Need port");
      return;
    }
    int port = Integer.parseInt(args[0]);
    try {
      ServerSocket server = new ServerSocket(port);
      System.out.println(
          "Login on "
              + server.getInetAddress().toString()
              + ":"
              + server.getLocalPort()
              + ".\nExit with a single x");
      Socket client = server.accept();
      LineNumberReader in = new LineNumberReader(new InputStreamReader(client.getInputStream()));
      PrintWriter out = new PrintWriter(client.getOutputStream());
      while (true) {
        String str = in.readLine();
        System.out.println(str);
        if (str.equals("x") == true) {
          client.close();
          server.close();

          break;
        }
        out.println(str);
        out.flush();
      }
    } catch (IOException ex) {
    }
  }
 public Download(String saveTo, ChatFrame ui) {
   try {
     server = new ServerSocket(0);
     port = server.getLocalPort();
     this.saveTo = saveTo;
     this.ui = ui;
   } catch (IOException ex) {
     System.out.println("Exception [Download : Download(...)]");
   }
 }
Ejemplo n.º 10
0
 public SocksServer(int port) throws IOException {
   this.port = port;
   server = new ServerSocket();
   if (port == 0) {
     server.bind(null);
     this.port = server.getLocalPort();
   } else {
     server.bind(new InetSocketAddress(port));
   }
 }
Ejemplo n.º 11
0
  public static void main(String[] args) {
    String ipv4;
    try {
      System.out.println("Stablishing the server socket...");
      ServerSocket srvSock = new ServerSocket(4201);
      System.out.println(
          "Server socket stablished to "
              + srvSock.getInetAddress().getHostName()
              + " at port number "
              + srvSock.getLocalPort()
              + ".\n");

      try {
        Socket comSock = srvSock.accept();
        System.out.println(
            "New connection stablished with "
                + comSock.getInetAddress().getHostName()
                + " (port "
                + comSock.getPort()
                + "), trying to communicate...");
        // DO STUFF
        try {
          BufferedReader br = new BufferedReader(new InputStreamReader(comSock.getInputStream()));
          ipv4 = br.readLine();
          br.close();
          comSock.close();
          srvSock.close();
          Socket sock = new Socket(ipv4, 4202);
          BufferedReader br2 = new BufferedReader(new InputStreamReader(sock.getInputStream()));
          System.out.println(br2.readLine());
          br2.close();
          sock.close();
          // System.out.println(ipv4);
        } catch (Exception e) {
          e.printStackTrace();
          System.out.println("Connection failed. Try again later.");
        }

      } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Problem with client.\n");
      }

    } catch (Exception e) {
      System.out.println("Failed to create server socket:");
      e.printStackTrace();
    }
  }
  public static void main(String[] args) throws Exception {
    int counter = 0;
    while (true) {
      Thread outThread = null;
      Thread errThread = null;
      try {
        // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange

        // *** start slave

        ServerSocket commSocket = new ServerSocket(0);
        int commPort = commSocket.getLocalPort();
        System.out.println("commPort = " + commPort);

        // org.pitest.mutationtest.execute.MutationTestProcess#start
        //   - org.pitest.util.CommunicationThread#start
        FutureTask<Integer> commFuture = createFuture(commSocket);
        //   - org.pitest.util.WrappingProcess#start
        //       - org.pitest.util.JavaProcess#launch
        Process slaveProcess = startSlaveProcess(commPort);
        outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout");
        errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr");
        outThread.start();
        errThread.start();

        // *** wait for slave to die

        // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie
        //    - org.pitest.util.CommunicationThread#waitToFinish
        System.out.println("waitToFinish");
        Integer controlReturned = commFuture.get();
        System.out.println("controlReturned = " + controlReturned);
        // NOTE: the following won't get called if commFuture.get() fails!
        //    - org.pitest.util.JavaProcess#destroy
        outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        slaveProcess.destroy();
      } catch (Exception e) {
        e.printStackTrace(System.out);
      }

      // test: the threads should exit eventually
      outThread.join();
      errThread.join();
      counter++;
      System.out.println("try " + counter + ": stdout and stderr threads exited normally");
    }
  }
Ejemplo n.º 13
0
    /*
     * Returns the string representation of the address that this
     * listen key represents.
     */
    public String address() {
      InetAddress address = ss.getInetAddress();

      /*
       * If bound to the wildcard address then use current local
       * hostname. In the event that we don't know our own hostname
       * then assume that host supports IPv4 and return something to
       * represent the loopback address.
       */
      if (address.isAnyLocalAddress()) {
        try {
          address = InetAddress.getLocalHost();
        } catch (UnknownHostException uhe) {
          byte[] loopback = {0x7f, 0x00, 0x00, 0x01};
          try {
            address = InetAddress.getByAddress("127.0.0.1", loopback);
          } catch (UnknownHostException x) {
            throw new InternalError("unable to get local hostname");
          }
        }
      }

      /*
       * Now decide if we return a hostname or IP address. Where possible
       * return a hostname but in the case that we are bound to an
       * address that isn't registered in the name service then we
       * return an address.
       */
      String result;
      String hostname = address.getHostName();
      String hostaddr = address.getHostAddress();
      if (hostname.equals(hostaddr)) {
        if (address instanceof Inet6Address) {
          result = "[" + hostaddr + "]";
        } else {
          result = hostaddr;
        }
      } else {
        result = hostname;
      }

      /*
       * Finally return "hostname:port", "ipv4-address:port" or
       * "[ipv6-address]:port".
       */
      return result + ":" + ss.getLocalPort();
    }
Ejemplo n.º 14
0
  /**
   * Test the http protocol handler with the given authentication schemes in the WWW-Authenticate
   * header.
   */
  static void test(String... schemes) throws IOException {

    // the authentication scheme that the client is expected to choose
    String expected = null;
    for (String s : schemes) {
      if (expected == null) {
        expected = s;
      } else if (s.equals("Digest")) {
        expected = s;
      }
    }

    // server reply
    String reply = authReplyFor(schemes);

    System.out.println("====================================");
    System.out.println("Expect client to choose: " + expected);
    System.out.println(reply);

    try (ServerSocket ss = new ServerSocket(0)) {
      Client.start(ss.getLocalPort());

      // client ---- GET ---> server
      // client <--- 401 ---- server
      try (Socket s = ss.accept()) {
        new MessageHeader().parseHeader(s.getInputStream());
        s.getOutputStream().write(reply.getBytes("US-ASCII"));
      }

      // client ---- GET ---> server
      // client <--- 200 ---- server
      String auth;
      try (Socket s = ss.accept()) {
        MessageHeader mh = new MessageHeader();
        mh.parseHeader(s.getInputStream());
        s.getOutputStream().write(OKAY.getBytes("US-ASCII"));
        auth = mh.findValue("Authorization");
      }

      // check Authorization header
      if (auth == null) throw new RuntimeException("Authorization header not found");
      System.out.println("Server received Authorization header: " + auth);
      String[] values = auth.split(" ");
      if (!values[0].equals(expected)) throw new RuntimeException("Unexpected value");
    }
  }
Ejemplo n.º 15
0
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  static void doServerSide() throws Exception {
    ServerSocket serverSocket = new ServerSocket(serverPort);
    serverPort = serverSocket.getLocalPort();

    /*
     * Signal Client, we're ready for a connect.
     */
    serverReady = true;

    Socket socket = serverSocket.accept();

    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();

    os.write(85);
    os.flush();
    socket.close();
  }
Ejemplo n.º 16
0
  public void run() {

    while (true) {
      try {
        System.out.println(
            "TCP Server waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just received request from " + server.getRemoteSocketAddress());

        /* parsing a request from socket */
        DataInputStream in = new DataInputStream(server.getInputStream());
        String request = in.readUTF();
        System.out.println("Request: " + request);

        /* handle the request */
        String output = null;
        output = requestHandler(request);
        System.out.print(output);

        /* display dataTable */
        System.out.print("-dataTable--------\n");
        Enumeration<String> key = dataTable.keys();
        while (key.hasMoreElements()) {
          String str = key.nextElement();
          System.out.println(str + ": " + dataTable.get(str));
        }
        System.out.print("------------------\n");

        /* send the result back to the client */
        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out.writeUTF(output);
        server.close();

      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
Ejemplo n.º 17
0
  public static void main(String[] args) throws Exception {
    int nLoops = 1;
    int nSize = 10;
    int port, n = 0;
    byte b[] = new byte[nSize];
    RedirServer server;
    ServerSocket sock;

    try {
      sock = new ServerSocket(0);
      port = sock.getLocalPort();
    } catch (Exception e) {
      System.out.println("Exception: " + e);
      return;
    }

    server = new RedirServer(sock);
    server.start();

    try {

      String s = "http://localhost:" + port;
      URL url = new URL(s);
      URLConnection conURL = url.openConnection();

      conURL.setDoInput(true);
      conURL.setAllowUserInteraction(false);
      conURL.setUseCaches(false);

      InputStream in = conURL.getInputStream();
      if ((in.read() != (int) 'W') || (in.read() != (int) 'o')) {
        throw new RuntimeException("Unexpected string read");
      }
    } catch (IOException e) {
      throw new RuntimeException("Exception caught");
    }
  }
Ejemplo n.º 18
0
  public static void main(String args[]) {

    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    int bytesRead;
    int current = 0;
    int varInc = 0; // A decrementer pour simuler la perte de la meme trame pour son deuxiem envoi

    int port = 1500;
    ServerSocket socket_serveur;
    BufferedReader input;
    PrintWriter out; // Ajouté

    System.out.println("\n\n*********************************");
    System.out.println("***********Serveur***************");
    System.out.println("*********************************\n\n");
    // si le port est donne en argument!!
    if (args.length == 1) {
      try {
        port = Integer.parseInt(args[0]);
      } catch (Exception e) {
        System.out.println("port d'ecoute= 1500 (par defaut)");
        port = 1500;
      }
    }

    // Ouverture du socket en attente de connexions
    try {
      socket_serveur = new ServerSocket(port);
      System.out.println(
          "Serveur en attente de clients sur le port " + socket_serveur.getLocalPort());

      // boucle infinie: traitement d'une connexion client
      while (true) {
        Socket socket = socket_serveur.accept();
        System.out.println(
            "nouvelle connexion acceptee " + socket.getInetAddress() + ":" + socket.getPort());
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        /*
         *
         * Reception des Trames envoyées par le client 1 Rassembler le
         * tout dans un tableau
         */

        ArrayList<Tram> listTrames = new ArrayList<Tram>();
        try {
          ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
          ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
          Tram trame;
          Tram ack;

          while ((trame = (Tram) ois.readObject()) != null) {
            System.out.print(
                "trame n° "
                    + trame.id
                    + " du fichier : "
                    + FILE_TO_RECEIVED
                    + " telechargée  ("
                    + trame.tabOct.length
                    + "bytes read)");

            if (!listTrames.isEmpty()) { // si ce n'est pas la premiere trame
              if (listTrames.get(listTrames.size() - 1).id
                  == trame.id - 1) { // si c'est la trame qui suit celle recue prealabment
                System.out.println(" <= Données acceptées ");
                listTrames.add(trame);

              } else {
                System.out.println(" <= Données refusées ");
              }

            } else {
              if (trame.id == 0) {
                System.out.println(" <= Données acceptées ");
                listTrames.add(trame);
              } else {
                System.out.println(" <= Données refusées ");
              }
            }

            // Données acceptées ou refusées il faut envoyer un ACK !!!

            // envoie ACK //
            ack = new Tram(null, trame.id); // Envoi une trame vide
            // de 0 octets mais avec
            // l'id de la trame
            // d'avant
            Timer timer = new Timer();
            if (ack.id == 2 && varInc == 0) {
              varInc++;

            } else {
              oos.writeObject(ack);
              System.out.println("Envoi de l'ack pour la trame " + trame.id);
            }

            if (trame.id == 8) break; // le break est a refaire dynamiquement

            oos.flush();
          }

        } catch (ClassNotFoundException e1) {
          // TODO Auto-generated catch block
          e1.printStackTrace();
        }

        /*
         * ETAPE 2 : parcourir le tableau contenant les trames pour les
         * rasesmbler
         */

        System.out.println("Etap 2 ");

        fos = new FileOutputStream(FILE_TO_RECEIVED);
        bos = new BufferedOutputStream(fos);

        for (Tram trame : listTrames) {

          bos.write(trame.tabOct, 0, trame.tabOct.length); // ecrire
          // les 5
          // bytes
          // de la
          // trame
          // i (
          // ou
          // moins
          // pour
          // la
          // derniere)
          // dans
          // bos
          bos.flush();
        }

        // connexion fermee par client
        try {
          socket.close();
          System.out.println("connexion fermee par le client");
        } catch (IOException e) {
          System.out.println(e);
        }
      }

    } catch (IOException e) {
      System.out.println(e);
    }
  }
Ejemplo n.º 19
0
  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()));
  }
Ejemplo n.º 20
0
 RedirServer(ServerSocket y) {
   s = y;
   port = s.getLocalPort();
 }
Ejemplo n.º 21
0
  // initiate either a server or a user session
  public void run() {
    if (isDaemon) {
      daemon();
      return;
    }
    ;

    boolean loggedIn = false;
    int i, h1;
    String di, str1, user = "******", user_id = "0";
    InetAddress localNode;
    byte dataBuffer[] = new byte[1024];
    String command = null;
    StringBuffer statusMessage = new StringBuffer(40);
    File targetFile = null;

    try {
      // start mysql
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      this.db_conn = DriverManager.getConnection(db_url);
      this.db_stmt = this.db_conn.createStatement();

      this.db_stmt.executeUpdate("INSERT INTO test_table (name) VALUES ('hello world')");

      incoming.setSoTimeout(inactivityTimer); // enforce I/O timeout
      remoteNode = incoming.getInetAddress();
      localNode = InetAddress.getLocalHost();

      BufferedReader in =
          new BufferedReader(new InputStreamReader(incoming.getInputStream(), TELNET));
      PrintWriter out =
          new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(), TELNET), true);
      str1 = "220 Flickr FTP Server Ready";
      out.println(str1);
      if (log) System.out.println(remoteNode.getHostName() + " " + str1);

      boolean done = false;
      char dataType = 0;

      while (!done) {
        statusMessage.setLength(0);

        // obtain and tokenize command
        String str = in.readLine();
        if (str == null) break; // EOS reached
        i = str.indexOf(' ');
        if (i == -1) i = str.length();
        command = str.substring(0, i).toUpperCase().intern();
        if (log)
          System.out.print(
              user
                  + "@"
                  + remoteNode.getHostName()
                  + " "
                  + (String) ((command != "PASS") ? str : "PASS ***"));
        str = str.substring(i).trim();

        try {
          if (command == "USER") {

            user = str;
            statusMessage.append("331 Password");

          } else if (command == "PASS") {

            String pass = str;
            String pass_md5 = md5(pass);

            this.db_rs =
                this.db_stmt.executeQuery(
                    "SELECT * FROM users WHERE email='"
                        + user
                        + "' AND password='******'");
            if (this.db_rs.first()) {
              loggedIn = true;
              user_id = this.db_rs.getString("id");
              System.out.println("Account id is " + user_id);
            }

            statusMessage.append(loggedIn ? "230 logged in User" : "530 Login Incorrect");

          } else if (!loggedIn) {

            statusMessage.append("530 Not logged in");

          } else if (command == "RETR") {

            statusMessage.append("999 Not likely");

          } else if (command == "STOR") {

            out.println(BINARY_XFER);

            // trim a leading slash off the filename if there is one
            if (str.substring(0, 1).equals("/")) str = str.substring(1);
            String filename = user_id + "_" + str;
            // TODO: sanitise filename
            targetFile = new File(upload_root + "/" + filename);

            RandomAccessFile dataFile = null;
            InputStream inStream = null;
            OutputStream outStream = null;
            BufferedReader br = null;
            PrintWriter pw = null;

            try {
              int amount;
              dataSocket = setupDataLink();

              // ensure timeout on reads.
              dataSocket.setSoTimeout(inactivityTimer);

              dataFile = new RandomAccessFile(targetFile, "rw");

              inStream = dataSocket.getInputStream();
              while ((amount = inStream.read(dataBuffer)) != -1)
                dataFile.write(dataBuffer, 0, amount);

              statusMessage.append(XFER_COMPLETE);

              shell_exec(ingest_path + " " + user_id + " " + filename);
            } finally {
              try {
                if (inStream != null) inStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (outStream != null) outStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataFile != null) dataFile.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e1) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "REST") {

            statusMessage.append("502 Sorry, no resuming");

          } else if (command == "TYPE") {

            if (Character.toUpperCase(str.charAt(0)) == 'I') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504 Only binary baybee");
            }

          } else if (command == "DELE"
              || command == "RMD"
              || command == "XRMD"
              || command == "MKD"
              || command == "XMKD"
              || command == "RNFR"
              || command == "RNTO"
              || command == "CDUP"
              || command == "XCDUP"
              || command == "CWD"
              || command == "SIZE"
              || command == "MDTM") {

            statusMessage.append("502 None of that malarky!");

          } else if (command == "QUIT") {

            statusMessage.append(COMMAND_OK).append("GOOD BYE");
            done = true;

          } else if (command == "PWD" | command == "XPWD") {

            statusMessage.append("257 \"/\" is current directory");

          } else if (command == "PORT") {

            int lng, lng1, lng2, ip2;
            String a1 = "", a2 = "";
            lng = str.length() - 1;
            lng2 = str.lastIndexOf(",");
            lng1 = str.lastIndexOf(",", lng2 - 1);

            for (i = lng1 + 1; i < lng2; i++) {
              a1 = a1 + str.charAt(i);
            }

            for (i = lng2 + 1; i <= lng; i++) {
              a2 = a2 + str.charAt(i);
            }

            remotePort = Integer.parseInt(a1);
            ip2 = Integer.parseInt(a2);
            remotePort = (remotePort << 8) + ip2;
            statusMessage.append(COMMAND_OK).append(remotePort);

          } else if (command == "LIST" | command == "NLST") {

            try {

              out.println("150 ASCII data");
              dataSocket = setupDataLink();

              PrintWriter out2 = new PrintWriter(dataSocket.getOutputStream(), true);

              if ((command == "NLST")) {
                out2.println(".");
                out2.println("..");
              } else {
                out2.println("total 8.0k");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 .");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 ..");
              }

              // socket MUST be closed before signalling EOD
              dataSocket.close();
              dataSocket = null;
              statusMessage.setLength(0);
              statusMessage.append(XFER_COMPLETE);
            } finally {
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "NOOP") {

            statusMessage.append(COMMAND_OK);

          } else if (command == "SYST") {

            statusMessage.append("215 UNIX"); // allows NS to do long dir

          } else if (command == "MODE") {

            if (Character.toUpperCase(str.charAt(0)) == 'S') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "STRU") {

            if (str.equals("F")) {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "PASV") {

            try {

              int num = 0, j = 0;
              if (passiveSocket != null)
                try {
                  passiveSocket.close();
                } catch (Exception e) {
                }
              ;
              passiveSocket = new ServerSocket(0); // any port

              // ensure timeout on reads.
              passiveSocket.setSoTimeout(inactivityTimer);

              statusMessage.append("227 Entering Passive Mode (");
              String s = localNode.getHostAddress().replace('.', ','); // get host #
              statusMessage.append(s).append(',');
              num = passiveSocket.getLocalPort(); // get port #
              j = (num >> 8) & 0xff;
              statusMessage.append(j);
              statusMessage.append(',');
              j = num & 0xff;
              statusMessage.append(j);
              statusMessage.append(')');
            } catch (Exception e) {
              try {
                if (passiveSocket != null) passiveSocket.close();
              } catch (Exception e1) {
              }
              ;
              passiveSocket = null;
              throw e;
            }

          } else {
            statusMessage.append("502 unimplemented ").append(command);
          }
        }

        // shutdown causes an interruption to be thrown
        catch (InterruptedException e) {
          throw (e);
        } catch (Exception e) // catch all for any errors (including files)
        {
          statusMessage.append(FAULT).append(e.getMessage());
          if (debug) {
            System.out.println("\nFAULT - lastfile " + targetFile);
            e.printStackTrace();
          }
          ;
        }

        // send result status to remote
        out.println(statusMessage);
        if (log) System.out.println("\t" + statusMessage);
      }
    } catch (Exception e) // usually network errors (including timeout)
    {
      if (log) System.out.println("forced instance exit " + e);
      if (debug) e.printStackTrace();
    } finally // exiting server instance
    {
      // tear down mysql
      if (this.db_rs != null) {
        try {
          this.db_rs.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_stmt != null) {
        try {
          this.db_stmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_pstmt != null) {
        try {
          this.db_pstmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_conn != null) {
        try {
          this.db_conn.close();
        } catch (SQLException SQLE) {;
        }
      }

      forceClose();
    }
  }