/**
   * Open FBS file identified by {@link #fbsURL}. The stream is positioned at the entry point
   * described by <code>entryPoint</code>.
   *
   * @param entryPoint entry point information.
   * @return a newly created FBS input stream on success, <code>null</code> if any error occured and
   *     the FBS stream is not opened.
   * @throws java.io.IOException if an I/O exception occurs.
   */
  private FbsInputStream openFbsFile(FbsEntryPoint entry) throws IOException {

    System.err.println("Entering FBS at " + entry.timestamp + " ms");

    // Make sure the protocol is HTTP.
    if (!fbkURL.getProtocol().equalsIgnoreCase("http")
        || !fbsURL.getProtocol().equalsIgnoreCase("http")) {
      System.err.println("Indexed access requires HTTP protocol in URLs");
      return null;
    }

    // Seek to the keyframe.
    InputStream is = openHttpByteRange(fbkURL, entry.key_fpos, entry.key_size);
    if (is == null) {
      return null;
    }

    // Load keyframe data from the .fbk file, prepend RFB initialization data.
    DataInputStream data = new DataInputStream(is);
    byte[] keyData = new byte[rfbInitData.length + (int) entry.key_size];
    System.arraycopy(rfbInitData, 0, keyData, 0, rfbInitData.length);
    data.readFully(keyData, rfbInitData.length, (int) entry.key_size);
    data.close();

    // Open the FBS stream.
    is = openHttpByteRange(fbsURL, entry.fbs_fpos, -1);
    if (is == null) {
      return null;
    }
    return new FbsInputStream(is, entry.timestamp, keyData, entry.fbs_skip);
  }
Beispiel #2
0
 public void run() {
   try {
     boolean connected = true;
     System.out.println("a client has connected!");
     dis = new DataInputStream(s.getInputStream());
     dos = new DataOutputStream(s.getOutputStream());
     while (connected) {
       int cid = clients.indexOf(this) + 1;
       try {
         String str = dis.readUTF();
         System.out.println(str);
         for (int i = 0; i < clients.size(); i++) {
           clients.get(i).dos.writeUTF("Client" + cid + ":" + str);
         }
       } catch (IOException e) {
         connected = false;
       }
     }
     dis.close();
     dos.close();
     s.close();
     clients.remove(this);
     System.out.println("a client is qiut!");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Beispiel #3
0
  public static void main(String[] args) {
    try {
      Socket s1 = new Socket("127.0.0.1", 57643);

      InputStream is = s1.getInputStream();
      DataInputStream dis = new DataInputStream(is);
      System.out.println(dis.readUTF());

      OutputStream os = s1.getOutputStream();
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeUTF("Oh my gosh...");

      dis.close();
      is.close();
      dos.close();
      os.close();

      s1.close();
    } catch (ConnectException connExc) {
      connExc.printStackTrace();
      System.out.println("Server connection failed");
    } catch (IOException ioExc) {
      ioExc.printStackTrace();
    }
  }
 public void close() {
   try {
     if (streamIn != null) streamIn.close();
   } catch (IOException ioe) {
     System.out.println("Error closing input stream: " + ioe);
   }
 }
 // --------------------------------------------------
 public void close() {
   try {
     is.close();
     os.close();
     socket.close();
     responseArea.appendText("***Connection closed" + "\n");
   } catch (IOException e) {
     responseArea.appendText("IO Exception" + "\n");
   }
 }
Beispiel #6
0
  public static void main(String[] args) {

    // setting default port and host name
    String host = "localhost";
    int port = 8080;

    // command line arguments
    if (args.length < 2) {
      System.out.println("Default port has been set: " + port);
    } else {
      host = args[0];
      port = Integer.parseInt(args[1]);
    }

    /*
     * Now open a socket on host and port names set above
     */
    try {
      clientSocket = new Socket(host, port);

      inputstream = new DataInputStream(clientSocket.getInputStream());
      outputstream = new PrintStream(clientSocket.getOutputStream());

      // inputLine reads lines from cmd
      inputLine =
          new BufferedReader(
              new InputStreamReader(
                  System.in)); // default sized input buffer (can define size as well)

    } catch (IOException e) {
      System.err.println("IO exception");
      // e.printStackTrace();
    }

    if (clientSocket != null && inputstream != null && outputstream != null) {
      try {
        // creating thread to read from server
        ClientThread newclient = new ClientThread();
        Thread t = new Thread(newclient);
        t.start(); // executes a call to run () method

        while (flag == true) {
          outputstream.println(inputLine.readLine().trim());
        }

        // Close the output stream, input stream and socket in reverse order that they were created
        outputstream.close();
        inputstream.close();
        clientSocket.close();

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #7
0
 private void closeConnection() {
   Debug.println("NetScan closing connection", 5);
   try {
     if (in != null) in.close();
     if (socket != null) socket.close();
     if (serverSocket != null) {
       serverSocket.close();
     }
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
Beispiel #8
0
 // Close socket and IO streams, change appearance/functionality of some components
 private void closeAll() throws IOException {
   displayArea.append("\nConnection closing");
   output.close();
   input.close();
   connection.close();
   // We are no longer connected
   connection = null;
   // Change components
   serverField.setEditable(true);
   connectButton.setLabel("Connect to server above");
   enterField.setEnabled(false);
 }
 public int[] readProgress() {
   int progress[] = new int[2];
   try {
     DataInputStream in =
         new DataInputStream(new BufferedInputStream(new FileInputStream(resume_file)));
     progress[0] = in.readInt();
     progress[1] = in.readInt();
     in.close();
   } catch (FileNotFoundException e) {
     Log.e(TAG, "readProgress file not found.");
   } catch (IOException e) {
     Log.e(TAG, e.getMessage());
   }
   return progress;
 }
Beispiel #10
0
 public void stop() {
   if (thread != null) {
     thread.stop();
     thread = null;
   }
   try {
     if (console != null) console.close();
     if (streamOut != null) streamOut.close();
     if (socket != null) socket.close();
   } catch (IOException ioe) {
     System.out.println("Error closing ...");
   }
   client.close();
   client.stop();
 }
Beispiel #11
0
  public void nick_name(String msg) {
    try {
      String name = msg.substring(13);
      this.setName(name);
      Vector v = father.onlineList;
      boolean isRepeatedName = false;
      int size = v.size();
      for (int i = 0; i < size; i++) {
        ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
        if (tempSat.getName().equals(name)) {
          isRepeatedName = true;
          break;
        }
      }
      if (isRepeatedName == true) {
        dout.writeUTF("<#NAME_REPEATED#>");
        din.close();
        dout.close();
        sc.close();
        flag = false;
      } else {
        v.add(this);
        father.refreshList();
        String nickListMsg = "";
        StringBuilder nickListMsgSb = new StringBuilder();
        size = v.size();
        for (int i = 0; i < size; i++) {
          ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
          nickListMsgSb.append("!");
          nickListMsgSb.append(tempSat.getName());
        }
        nickListMsgSb.append("<#NICK_LIST#>");
        nickListMsg = nickListMsgSb.toString();
        Vector tempv = father.onlineList;
        size = tempv.size();
        for (int i = 0; i < size; i++) {
          ServerAgentThread tempSat = (ServerAgentThread) tempv.get(i);
          tempSat.dout.writeUTF(nickListMsg);
          if (tempSat != this) {
            tempSat.dout.writeUTF("<#MSG#>" + this.getName() + "is now online....");
          }
        }
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /** @param args the command line arguments */
  public static void main(String[] args) {
    // TODO code application logic here

    long lNumOfLines = 0;
    List list1 = new ArrayList();

    try {
      FileInputStream fstream = new FileInputStream("n:\\myphd\\dataset\\gps.csv");
      // Get the object of DataInputStream
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      // Read File Line By Line
      while ((strLine = br.readLine()) != null) {
        // Print the content on the console
        lNumOfLines++;
        list1.add(strLine.trim());
      }
      // Close the input stream
      in.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }

    long lTotal = 1000000;
    long numberOfLines = 0;
    long lStep = lTotal / lNumOfLines;
    System.out.println("lTotal:" + lTotal + " numberOfLines:" + numberOfLines + "lStep:" + lStep);
    float fSpeed = 100;
    float newfSpeed = 0;
    for (int iNum = 0; iNum < lStep; iNum++) {
      Random randomGenerator = new Random();
      int randomInt = randomGenerator.nextInt(1000);
      float f = (float) randomInt / 10000.0f;
      System.out.println("Random Int:" + randomInt + " f:" + f);
      if ((randomInt % 2) == 0) {
        newfSpeed = fSpeed + fSpeed * f;
        System.out.println("Even");
      } else {
        newfSpeed = fSpeed - fSpeed * f;
        System.out.println("odd");
      }
      // InsertInstance(fLat,fLon,fAlt,fSpeed,sDate,sTimestamp,sBTAddress,sBTName,sURI);
      System.out.println("generated speed:" + newfSpeed);
    }
  }
Beispiel #13
0
 // 读取保存的下载信息(文件指针位置)
 private void read_nPos() {
   try {
     DataInputStream input = new DataInputStream(new FileInputStream(tmpFile));
     int nCount = input.readInt();
     nStartPos = new long[nCount];
     nEndPos = new long[nCount];
     for (int i = 0; i < nStartPos.length; i++) {
       nStartPos[i] = input.readLong();
       nEndPos[i] = input.readLong();
     }
     input.close();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  public static PnmImage get_PNMstream(String cid, String tid, int fw, int fh) {
    PnmImage pnmstream = null;

    try {
      Socket imgdecSocket = new Socket("localhost", 50000);
      DataOutputStream os = new DataOutputStream(imgdecSocket.getOutputStream());
      DataInputStream is = new DataInputStream(imgdecSocket.getInputStream());
      byte[] header = new byte[7];

      os.writeBytes("PNM request\n");
      if (cid != null) os.writeBytes(cid + "\n");
      else if (tid != null) os.writeBytes(tid + "\n");
      else os.writeBytes("0\n");
      os.writeBytes(fw + "\n");
      os.writeBytes(fh + "\n");

      read_stream(is, header, 7);

      if (header[0] == 80) {
        // P5: gray, P6: color
        byte magicknum = header[1];
        if (magicknum == 5 || magicknum == 6) {
          int c = magicknum == 6 ? 3 : 1;
          int w = (header[2] & 0xff) << 8 | (header[3] & 0xff);
          int h = (header[4] & 0xff) << 8 | (header[5] & 0xff);
          int maxval = header[6] & 0xff;
          int length = w * h * c;

          if (maxval == 255 && length != 0) {
            pnmstream = new PnmImage(c, w, h);
            read_stream(is, pnmstream.get_data(), length);
          } else System.err.println("Error in get_PNMstream(), only 255 is accepted");
        } else System.err.println("Error in get_PNMstream(), wrong magick number" + header[1]);
      } else System.err.println("Error in get_PNMstream(), Not starting with P");

      os.close();
      is.close();
      imgdecSocket.close();
    } catch (UnknownHostException e) {
      System.err.println("Trying to connect to unknown host: " + e);
    } catch (IOException e) {
      System.err.println("IOException: " + e);
    }
    return pnmstream;
  }
Beispiel #15
0
 /**
  * Send a plugin JAR file to the client
  *
  * @param data the plugin name
  */
 private void sendPlugin(ObjectConnection oc, String data) {
   DataInputStream dis = null;
   try {
     dis = new DataInputStream(new FileInputStream(APPLICATIONS_DIRECTORY + data + ".jar"));
     byte[] buf = new byte[dis.available()];
     dis.readFully(buf);
     oc.write(buf);
   } catch (Exception e) {
     Logging.getLogger().warning("Unable to send the file: " + data + ".jar");
   } finally {
     if (dis != null) {
       try {
         dis.close();
       } catch (IOException ioe) {
       }
     }
   }
 }
  private final byte[] loadfile(String s, byte abyte0[]) {
    try {
      File file = new File(s);
      System.out.println("trying to load:" + file);
      int i = (int) file.length();
      DataInputStream datainputstream = new DataInputStream(new FileInputStream(s));
      byte abyte1[] = new byte[i];
      datainputstream.readFully(abyte1, 0, i);
      datainputstream.close();
      m.reset();
      m.update(abyte1);
      byte abyte2[] = m.digest();
      for (int j = 0; j < 20; j++) if (abyte2[j] != abyte0[j]) return null;

      return abyte1;
    } catch (Exception _ex) {
      return null;
    }
  }
 byte[] download(File f) {
   if (!f.exists()) {
     IJ.error("Plugin Installer", "File not found: " + f);
     return null;
   }
   byte[] data = null;
   try {
     int len = (int) f.length();
     InputStream in = new BufferedInputStream(new FileInputStream(f));
     DataInputStream dis = new DataInputStream(in);
     data = new byte[len];
     dis.readFully(data);
     dis.close();
   } catch (Exception e) {
     IJ.error("Plugin Installer", "" + e);
     data = null;
   }
   return data;
 }
  // {{{ handleClient() method
  private boolean handleClient(final Socket client, DataInputStream in) throws Exception {
    int key = in.readInt();
    if (key != authKey) {
      Log.log(
          Log.ERROR,
          this,
          client + ": wrong" + " authorization key (got " + key + ", expected " + authKey + ")");
      in.close();
      client.close();

      return false;
    } else {
      // Reset the timeout
      client.setSoTimeout(0);

      Log.log(Log.DEBUG, this, client + ": authenticated" + " successfully");

      final String script = in.readUTF();
      Log.log(Log.DEBUG, this, script);

      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              try {
                NameSpace ns = new NameSpace(BeanShell.getNameSpace(), "EditServer namespace");
                ns.setVariable("socket", client);
                BeanShell.eval(null, ns, script);
              } catch (org.gjt.sp.jedit.bsh.UtilEvalError e) {
                Log.log(Log.ERROR, this, e);
              } finally {
                try {
                  BeanShell.getNameSpace().setVariable("socket", null);
                } catch (org.gjt.sp.jedit.bsh.UtilEvalError e) {
                  Log.log(Log.ERROR, this, e);
                }
              }
            }
          });

      return true;
    }
  } // }}}
 private final int getuid(String s) {
   try {
     File file = new File(s + "uid.dat");
     if (!file.exists() || file.length() < 4L) {
       DataOutputStream dataoutputstream =
           new DataOutputStream(new FileOutputStream(s + "uid.dat"));
       dataoutputstream.writeInt((int) (Math.random() * 99999999D));
       dataoutputstream.close();
     }
   } catch (Exception _ex) {
   }
   try {
     DataInputStream datainputstream = new DataInputStream(new FileInputStream(s + "uid.dat"));
     int i = datainputstream.readInt();
     datainputstream.close();
     return i + 1;
   } catch (Exception _ex) {
     return 0;
   }
 }
  public final void run() {
    if (socketthread) {
      socketrun();
      return;
    }
    socketthread = true;
    try {
      boolean flag = false;
      try {
        String s = getParameter("member");
        int i = Integer.parseInt(s);
        if (i == 1) flag = true;
      } catch (Exception _ex) {
      }
      loading = getImage(new URL(getCodeBase(), "loading.jpg"));
      mt = new MediaTracker(this);
      mt.addImage(loading, 0);
      m = MessageDigest.getInstance("SHA");
      System.out.println(link.class);
      String s1 = ".file_store_32/";
      if (s1 == null) return;
      link.uid = getuid(s1);
      link.mainapp = this;
      link.numfile = 0;
      for (int j = 0; j < 14; j++)
        if (flag || !internetname[j].endsWith(".mem")) {
          for (int k = 0; k < 4; k++) {
            if (k == 3) return;
            byte abyte0[] = loadfile(s1 + localname[j], sha[j]);
            if (abyte0 != null) {
              if (j > 0) link.putjag(internetname[j], abyte0);
              break;
            }
            try {
              URL url = new URL(getCodeBase(), internetname[j]);
              DataInputStream datainputstream = new DataInputStream(url.openStream());
              int l = size[j];
              byte abyte1[] = new byte[l];
              for (int i1 = 0; i1 < l; i1 += 1000) {
                int j1 = l - i1;
                if (j1 > 1000) j1 = 1000;
                datainputstream.readFully(abyte1, i1, j1);
                showpercent(nicename[j], (i1 * 100) / l, barpos[j]);
              }

              datainputstream.close();
              FileOutputStream fileoutputstream = new FileOutputStream(s1 + localname[j]);
              fileoutputstream.write(abyte1);
              fileoutputstream.close();
            } catch (Exception _ex) {
            }
          }
        }
      System.out.println(cloader.class);
      cloader cloader1 = new cloader();
      cloader1.zip = new ZipFile(s1 + localname[0]);
      cloader1.link = Class.forName("link");
      inner = new mudclient_Debug();
      loadMacros();
      // inner = (Applet)cloader1.loadClass("mudclient").newInstance();
      inner.init();
      inner.start();
      return;
    } catch (Exception exception) {
      System.out.println(exception + " " + exception.getMessage());
      exception.printStackTrace();
      return;
    }
  }
 public void closeStreams() throws IOException {
   in.close();
   out.close();
   socket.close();
 }
Beispiel #22
0
  /** Internal method. Get and check response packet from searchd. */
  private byte[] _GetResponse(Socket sock) {
    /* connect */
    DataInputStream sIn = null;
    InputStream SockInput = null;
    try {
      SockInput = sock.getInputStream();
      sIn = new DataInputStream(SockInput);

    } catch (IOException e) {
      _error = "getInputStream() failed: " + e;
      return null;
    }

    /* read response */
    byte[] response = null;
    short status = 0, ver = 0;
    int len = 0;
    try {
      /* read status fields */
      status = sIn.readShort();
      ver = sIn.readShort();
      len = sIn.readInt();

      /* read response if non-empty */
      if (len <= 0) {
        _error = "invalid response packet size (len=" + len + ")";
        return null;
      }

      response = new byte[len];
      sIn.readFully(response, 0, len);

      /* check status */
      if (status == SEARCHD_WARNING) {
        DataInputStream in = new DataInputStream(new ByteArrayInputStream(response));

        int iWarnLen = in.readInt();
        _warning = new String(response, 4, iWarnLen);

        System.arraycopy(response, 4 + iWarnLen, response, 0, response.length - 4 - iWarnLen);

      } else if (status == SEARCHD_ERROR) {
        _error = "searchd error: " + new String(response, 4, response.length - 4);
        return null;

      } else if (status == SEARCHD_RETRY) {
        _error = "temporary searchd error: " + new String(response, 4, response.length - 4);
        return null;

      } else if (status != SEARCHD_OK) {
        _error = "searched returned unknown status, code=" + status;
        return null;
      }

    } catch (IOException e) {
      if (len != 0) {
        /* get trace, to provide even more failure details */
        PrintWriter ew = new PrintWriter(new StringWriter());
        e.printStackTrace(ew);
        ew.flush();
        ew.close();
        String sTrace = ew.toString();

        /* build error message */
        _error =
            "failed to read searchd response (status="
                + status
                + ", ver="
                + ver
                + ", len="
                + len
                + ", trace="
                + sTrace
                + ")";
      } else {
        _error = "received zero-sized searchd response (searchd crashed?): " + e.getMessage();
      }
      return null;

    } finally {
      if (_socket == null) {
        try {
          if (sIn != null) sIn.close();
          if (sock != null && !sock.isConnected()) sock.close();
        } catch (IOException e) {
          /* silently ignore close failures; nothing could be done anyway */
        }
      }
    }

    return response;
  }
  public static void main(String[] args) throws Exception {
    // prompt user to enter a port number

    System.out.print("Enter the port number: ");
    Scanner scan = new Scanner(System.in);
    int port = scan.nextInt();
    scan.nextLine();
    System.out.print("Enter the host name: ");
    String hostName = scan.nextLine();

    // Initialize a key pair generator with the SKIP parameters we sepcified, and genrating a pair
    // This will take a while: 5...15 seconrds

    System.out.println("Generating a Diffie-Hellman keypair: ");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
    kpg.initialize(PARAMETER_SPEC);
    KeyPair keyPair = kpg.genKeyPair();
    System.out.println("key pair has been made...");

    // one the key pair has been generated, we want to listen on
    // a given port for a connection to come in
    // once we get a connection, we will get two streams, One for input
    // and one for output
    // open a port and wait for a connection

    ServerSocket ss = new ServerSocket(port);
    System.out.println("Listeining on port " + port + " ...");
    Socket socket = ss.accept();

    // use to output and input primitive data type

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());

    // next thing to do is send our public key and receive client's
    // this corresponds to server step 3 and step 4 in the diagram

    System.out.println("Sending my public key...");
    byte[] keyBytes = keyPair.getPublic().getEncoded();
    out.writeInt(keyBytes.length);
    out.write(keyBytes);
    System.out.println("Server public key bytes: " + CryptoUtils.toHex(keyBytes));

    // receive the client's public key

    System.out.println("Receiving client's public key...");
    DataInputStream in = new DataInputStream(socket.getInputStream());
    keyBytes = new byte[in.readInt()];
    in.readFully(keyBytes);

    // create client's public key

    KeyFactory kf = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes);
    PublicKey clientPublicKey = kf.generatePublic(x509Spec);

    // print out client's public key bytes

    System.out.println(
        "Client public key bytes: " + CryptoUtils.toHex(clientPublicKey.getEncoded()));

    // we can now use the client's public key and
    // our own private key to perform the key agreement

    System.out.println("Performing the key agreement ... ");
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(clientPublicKey, true);

    // in a chat application, each character is sendt over the wire, separetly encrypted,
    // Instead of using ECB, we are goin to use CFB, with a block size of 8 bits(1byte)
    // to send each character. We will encrypt the same character in a different way
    // each time. But in order to use CFB8, we need an IVof 8 bytes. We will create
    // that IV randomly and and send it to the client. It doesn't matter if somoene
    // eavesdrops on the IV when it is sent over the wire. it's not sensitive info

    // creating the IV and sending it corresponds to step 6 and 7

    byte[] iv = new byte[8];
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(iv);
    out.write(iv);

    // we generate the secret byte array we share with the client and use it
    // to create the session key (Step 8)

    byte[] sessionKeyBytes = ka.generateSecret();

    // create the session key

    SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec DESedeSpec = new DESedeKeySpec(sessionKeyBytes);
    SecretKey sessionKey = skf.generateSecret(DESedeSpec);

    // printout session key bytes

    System.out.println("Session key bytes: " + CryptoUtils.toHex(sessionKey.getEncoded()));

    // now use tha that session key and IV to create a CipherInputStream. We will use them to read
    // all character
    // that are sent to us by the client

    System.out.println("Creating the cipher stream ...");
    Cipher decrypter = Cipher.getInstance("DESede/CFB8/NoPadding");
    IvParameterSpec spec = new IvParameterSpec(iv);
    decrypter.init(Cipher.DECRYPT_MODE, sessionKey, spec);
    CipherInputStream cipherIn = new CipherInputStream(socket.getInputStream(), decrypter);

    // we just keep reading the input and print int to the screen, until -1 sent over

    int theCharacter = 0;
    theCharacter = cipherIn.read();
    while (theCharacter != -1) {
      System.out.print((char) theCharacter);
      theCharacter = cipherIn.read();
    }
    // once -1 is received we want to close up our stream and exit

    cipherIn.close();
    in.close();
    out.close();
    socket.close();
  }
  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 #25
0
  /*========================================================================*/
  public void run() {
    /*========================================================================*/
    Thread me = Thread.currentThread();
    RUNNING_LOOP:
    while (thread == me) {
      try {
        // Thread.currentThread().sleep(100);
        int command = dis.readInt();
        switch (command) {
          case -1:
            System.out.println("Got a request to exit");
            /*--------------------------------*/
            /* Command: exit this application */
            /*--------------------------------*/
            break RUNNING_LOOP;
          case 0:
            System.out.println("Got a command #0");
            break;
          case 1:
            /*-------------------------------------------------*/
            /* Command: receiving admin threads status         */
            /* Proto: [NbAdmins:int]                           */
            /*        [Adm1Id:int]                             */
            /*        [Adm1UsernameSize]                       */
            /*        [Adm1User:str50]                         */
            /*        [Adm1Status:int]                         */
            /*        ... until all admins are reported...     */
            /*-------------------------------------------------*/
            System.out.println("Got data on admin connections");
            int nbAdmins = dis.readInt();
            System.out.println("We have " + nbAdmins + "admin connections alike");
            // javax.swing.JButton btnKill[] = new javax.swing.JButton[nbAdmins];
            for (i = 0; i < 10; i++) {
              tblAdmins.setValueAt("", i, 0);
              tblAdmins.setValueAt("", i, 1);
              tblAdmins.setValueAt("", i, 2);
              tblAdmins.setValueAt("", i, 3);
            }
            // tblAdmins.selectAll();
            // tblAdmins.clearSelection();
            for (int i = 0; i < nbAdmins; i++) {
              int id = dis.readInt();
              int usernameSize = dis.readInt();
              byte strData[] = new byte[usernameSize];
              dis.readFully(strData);
              String user = new String(strData);
              int status = dis.readInt();
              tblAdmins.setValueAt(new Integer(id), i, 0);
              tblAdmins.setValueAt(user, i, 1);
              tblAdmins.setValueAt(new Integer(status), i, 2);
              // btnKill[i] = new javax.swing.JButton();
              // tblAdmins.setValueAt(btnKill[i],id,3);

            }
            break;
          default:
            System.out.println("Got unrecognized message");
            break;
        }
      } catch (IOException ioe) {
      }
    } // end of RUNNING_LOOP
    try {
      dis.close();
      dos.close();
    } catch (IOException ioe) {
    }
    System.exit(0);
  }
Beispiel #26
0
 public void close() throws IOException {
   if (socket != null) socket.close();
   if (streamIn != null) streamIn.close();
   if (streamOut != null) streamOut.close();
 }
Beispiel #27
0
  public static String getWindows() {
    String cmd1 = "netsh wlan show profiles";
    String cmd2 = "netsh wlan export profile name=";
    String keyword1 = "User profiles";
    String wlanProfileArr[];
    String wlanProfileName;
    int match = 0;
    int count = 0;
    ArrayList<String> profileList = new ArrayList<String>();
    try {
      // Get wlan profile names
      Process p1 = Runtime.getRuntime().exec(cmd1);
      BufferedReader in1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
      String line = null;
      // Checks if string match "User profiles"
      while ((line = in1.readLine()) != null) {
        // Checks if string match "User profiles"
        if (match == 0) {
          if (line.toLowerCase().contains(keyword1.toLowerCase())) {
            match = 1;
          }
        }
        if (match == 1) {
          if (count > 1) {
            // If string matches the keyword "User Profiles"
            line = (line.replaceAll("\\s+$", "").replaceAll("^\\s+", ""));
            if (line.length() > 0) {
              wlanProfileName =
                  (line.split(":")[1]).replaceAll("\\s+$", "").replaceAll("^\\s+", "");
              ;
              profileList.add(wlanProfileName);
            }
          }
          count += 1;
        }
      }
      in1.close();
    } catch (IOException e) {
    }

    try {
      String tmpDir = System.getProperty("java.io.tmpdir");
      if (!(tmpDir.endsWith("/") || tmpDir.endsWith("\\")))
        tmpDir = tmpDir + System.getProperty("file.separator");

      // Export WLAN Profile to XML file
      for (Iterator iterator = profileList.iterator(); iterator.hasNext(); ) {
        String profileName = iterator.next().toString();
        Process p2 = Runtime.getRuntime().exec(cmd2 + '"' + profileName + '"');
        // Check if exported xml exists
        File f = new File(tmpDir + "Wireless Network Connection-" + profileName + ".xml");
        if (f.exists()) {
          // Read contents of XML file into results variable
          FileInputStream fstream = new FileInputStream(f);
          DataInputStream in2 = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in2));
          String xmlToStr;
          while ((xmlToStr = br.readLine()) != null) {
            result += xmlToStr;
          }
          in2.close();
        }
      }
    } catch (IOException e) {
    }
    return result;
  }