Example #1
0
  String[] getMedkit(
      String[] availableResources,
      String[] requiredResources,
      String[] missions,
      double P,
      double C) {
    try {
      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec(exec);
      OutputStream os = proc.getOutputStream();
      InputStream is = proc.getInputStream();
      new ErrorReader(proc.getErrorStream()).start();

      StringBuffer sb = new StringBuffer();
      append(sb, availableResources);
      append(sb, requiredResources);
      append(sb, missions);
      sb.append(P).append('\n');
      sb.append(C).append('\n');
      os.write(sb.toString().getBytes());

      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      int N = Integer.parseInt(br.readLine().trim());
      String[] ret = new String[N];
      for (int i = 0; i < N; i++) ret[i] = br.readLine().trim();
      return ret;

    } catch (Exception e) {
      System.err.println("An error occurred while executing your program");
      e.printStackTrace();
      return null;
    }
  }
Example #2
0
 public void run() {
   try {
     InputStream in;
     OutputStream out;
     try {
       in = sk.getInputStream();
       out = sk.getOutputStream();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
     while (true) {
       try {
         int len = Utils.int32d(read(in, 4), 0);
         if (!auth && (len > 256)) return;
         Message msg = new MessageBuf(read(in, len));
         String cmd = msg.string();
         Object[] args = msg.list();
         Object[] reply;
         if (auth) {
           Command cc = commands.get(cmd);
           if (cc != null) reply = cc.run(this, args);
           else reply = new Object[] {"nocmd"};
         } else {
           if (cmd.equals("nonce")) {
             reply = new Object[] {nonce};
           } else if (cmd.equals("auth")) {
             if (Arrays.equals((byte[]) args[0], ckey)) {
               reply = new Object[] {"ok"};
               auth = true;
             } else {
               reply = new Object[] {"no"};
             }
           } else {
             return;
           }
         }
         MessageBuf rb = new MessageBuf();
         rb.addlist(reply);
         byte[] rbuf = new byte[4 + rb.size()];
         Utils.uint32e(rb.size(), rbuf, 0);
         rb.fin(rbuf, 4);
         out.write(rbuf);
       } catch (IOException e) {
         return;
       }
     }
   } catch (InterruptedException e) {
   } finally {
     try {
       sk.close();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
   }
 }
  void doTest(SSLSocket sslSocket) throws Exception {
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    System.out.println("  Writing");
    sslOS.write(280);
    sslOS.flush();
    System.out.println("  Reading");
    sslIS.read();

    sslSocket.close();
  }
Example #4
0
 public static void close(Object o) {
   try {
     if (o == null) return;
     if (o instanceof InputStream) {
       ((InputStream) o).close();
     } else if (o instanceof OutputStream) {
       ((OutputStream) o).flush();
       ((OutputStream) o).close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #5
0
 public static void copyStream(InputStream in, OutputStream out) throws IOException {
   byte[] data = new byte[BUFFER];
   int currentByte;
   while ((currentByte = in.read(data, 0, BUFFER)) != -1) {
     out.write(data, 0, currentByte);
   }
 }
Example #6
0
 void sendRequest(InputStream in, OutputStream out) throws IOException {
   out.write("GET / HTTP/1.0\r\n\r\n".getBytes());
   out.flush();
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       break;
     }
     sb.append((char) ch);
   }
   String response = sb.toString();
   if (response.startsWith("HTTP/1.0 200 ") == false) {
     throw new IOException("Invalid response: " + response);
   }
 }
Example #7
0
 /**
  * Unwatches an event.
  *
  * @param name event name
  * @throws IOException I/O exception
  */
 public void unwatch(final String name) throws IOException {
   out.write(11);
   send(name);
   info = receive();
   if (!ok()) throw new IOException(info);
   notifiers.remove(name);
 }
Example #8
0
 void handleRequest(InputStream in, OutputStream out) throws IOException {
   boolean newline = false;
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       throw new EOFException();
     }
     sb.append((char) ch);
     if (ch == '\r') {
       // empty
     } else if (ch == '\n') {
       if (newline) {
         // 2nd newline in a row, end of request
         break;
       }
       newline = true;
     } else {
       newline = false;
     }
   }
   String request = sb.toString();
   if (request.startsWith("GET / HTTP/1.") == false) {
     throw new IOException("Invalid request: " + request);
   }
   out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes());
 }
 @Override
 protected void engineSetSeed(byte[] bytes) {
   try {
     OutputStream out;
     synchronized (sLock) {
       out = getUrandomOutputStream();
     }
     out.write(bytes);
     out.flush();
   } catch (IOException e) {
     // On a small fraction of devices /dev/urandom is not writable.
     // Log and ignore.
     Log.w(PRNGFixes.class.getSimpleName(), "Failed to mix seed into " + URANDOM_FILE);
   } finally {
     mSeeded = true;
   }
 }
Example #10
0
    public void run() {
      try {
        URL url = new URL(protocol + "://localhost:" + port + "/test1/" + f);
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        if (urlc instanceof HttpsURLConnection) {
          HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
          urlcs.setHostnameVerifier(
              new HostnameVerifier() {
                public boolean verify(String s, SSLSession s1) {
                  return true;
                }
              });
          urlcs.setSSLSocketFactory(ctx.getSocketFactory());
        }
        byte[] buf = new byte[4096];

        if (fixedLen) {
          urlc.setRequestProperty("XFixed", "yes");
        }
        InputStream is = urlc.getInputStream();
        File temp = File.createTempFile("Test1", null);
        temp.deleteOnExit();
        OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp));
        int c, count = 0;
        while ((c = is.read(buf)) != -1) {
          count += c;
          fout.write(buf, 0, c);
        }
        is.close();
        fout.close();

        if (count != size) {
          throw new RuntimeException("wrong amount of data returned");
        }
        String orig = root + "/" + f;
        compare(new File(orig), temp);
        temp.delete();
      } catch (Exception e) {
        e.printStackTrace();
        fail = true;
      }
    }
Example #11
0
 /**
  * Watches an event.
  *
  * @param name event name
  * @param notifier event notification
  * @throws IOException I/O exception
  */
 public void watch(final String name, final EventNotifier notifier) throws IOException {
   out.write(10);
   if (esocket == null) {
     final int eport = Integer.parseInt(receive());
     // initialize event socket
     esocket = new Socket();
     esocket.connect(new InetSocketAddress(ehost, eport), 5000);
     final OutputStream os = esocket.getOutputStream();
     receive(in, os);
     os.write(0);
     os.flush();
     final InputStream is = esocket.getInputStream();
     is.read();
     listen(is);
   }
   send(name);
   info = receive();
   if (!ok()) throw new IOException(info);
   notifiers.put(name, notifier);
 }
Example #12
0
  /**
   * Uses a cipher to transform the bytes in an input stream and sends the transformed bytes to an
   * output stream.
   *
   * @param in the input stream
   * @param out the output stream
   * @param cipher the cipher that transforms the bytes
   */
  public static void crypt(InputStream in, OutputStream out, Cipher cipher)
      throws IOException, GeneralSecurityException {
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(blockSize);
    byte[] inBytes = new byte[blockSize];
    byte[] outBytes = new byte[outputSize];

    int inLength = 0;
    ;
    boolean more = true;
    while (more) {
      inLength = in.read(inBytes);
      if (inLength == blockSize) {
        int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
        out.write(outBytes, 0, outLength);
      } else more = false;
    }
    if (inLength > 0) outBytes = cipher.doFinal(inBytes, 0, inLength);
    else outBytes = cipher.doFinal();
    out.write(outBytes);
  }
Example #13
0
  private void doManifest(
      Jar jar, String[] digestNames, MessageDigest[] algorithms, OutputStream out)
      throws Exception {

    for (Map.Entry<String, Resource> entry : jar.getResources().entrySet()) {
      String name = entry.getKey();
      if (!METAINFDIR.matcher(name).matches()) {
        out.write("\r\n".getBytes("UTF-8"));
        out.write("Name: ".getBytes("UTF-8"));
        out.write(name.getBytes("UTF-8"));
        out.write("\r\n".getBytes("UTF-8"));

        digest(algorithms, entry.getValue());
        for (int a = 0; a < algorithms.length; a++) {
          if (algorithms[a] != null) {
            byte[] digest = algorithms[a].digest();
            String header = digestNames[a] + "-Digest: " + new Base64(digest) + "\r\n";
            out.write(header.getBytes("UTF-8"));
          }
        }
      }
    }
  }
Example #14
0
 /**
  * Closes the session.
  *
  * @throws IOException Exception
  */
 public void close() throws IOException {
   send("exit");
   out.flush();
   if (esocket != null) esocket.close();
   socket.close();
 }
Example #15
0
 /**
  * Checks the next success flag.
  *
  * @return value of check
  * @throws IOException Exception
  */
 boolean ok() throws IOException {
   out.flush();
   return in.read() == 0;
 }
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    com.sun.net.ssl.SSLContext ctx = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");

    ks.load(new FileInputStream(keyFilename), cpasswd);
    kmf.init(ks, cpasswd);

    com.sun.net.ssl.TrustManager[] tms =
        new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()};

    ctx.init(kmf.getKeyManagers(), tms, null);

    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) ctx.getServerSocketFactory();

    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    sslServerSocket.setNeedClientAuth(true);

    /*
     * Create using the other type.
     */
    SSLContext ctx1 = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf1 = KeyManagerFactory.getInstance("SunX509");

    TrustManager[] tms1 = new TrustManager[] {new MyJavaxX509TrustManager()};

    kmf1.init(ks, cpasswd);

    ctx1.init(kmf1.getKeyManagers(), tms1, null);

    sslssf = (SSLServerSocketFactory) ctx1.getServerSocketFactory();

    SSLServerSocket sslServerSocket1 = (SSLServerSocket) sslssf.createServerSocket(serverPort1);
    serverPort1 = sslServerSocket1.getLocalPort();
    sslServerSocket1.setNeedClientAuth(true);

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

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    sslServerSocket.close();
    serverReady = false;

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    sslSocket = (SSLSocket) sslServerSocket1.accept();
    sslIS = sslSocket.getInputStream();
    sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    System.out.println("Server exiting!");
    System.out.flush();
  }
Example #17
0
 /**
  * Sends a string to the server.
  *
  * @param s string to be sent
  * @throws IOException I/O exception
  */
 void send(final String s) throws IOException {
   out.write((s + '\0').getBytes(UTF8));
 }
Example #18
0
 /**
  * Receives a string and writes it to the specified output stream.
  *
  * @param is input stream
  * @param os output stream
  * @throws IOException I/O exception
  */
 static void receive(final InputStream is, final OutputStream os) throws IOException {
   for (int b; (b = is.read()) > 0; ) {
     // read next byte if 0xFF is received
     os.write(b == 0xFF ? is.read() : b);
   }
 }
  SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      if (endPoint.getProtocol().equals("https"))
        // if(!setHttps)
        initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("POST");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setInstanceFollowRedirects(true);

      if (message.saveRequired()) message.saveChanges();

      MimeHeaders headers = message.getMimeHeaders();

      Iterator it = headers.getAllHeaders();
      boolean hasAuth = false; // true if we find explicit Auth header
      while (it.hasNext()) {
        MimeHeader header = (MimeHeader) it.next();

        String[] values = headers.getHeader(header.getName());
        if (values.length == 1)
          httpConnection.setRequestProperty(header.getName(), header.getValue());
        else {
          StringBuffer concat = new StringBuffer();
          int i = 0;
          while (i < values.length) {
            if (i != 0) concat.append(',');
            concat.append(values[i]);
            i++;
          }

          httpConnection.setRequestProperty(header.getName(), concat.toString());
        }

        if ("Authorization".equals(header.getName())) {
          hasAuth = true;
          log.fine("SAAJ0091.p2p.https.auth.in.POST.true");
        }
      }

      if (!hasAuth && userInfo != null) {
        initAuthUserInfo(httpConnection, userInfo);
      }

      OutputStream out = httpConnection.getOutputStream();
      message.writeTo(out);

      out.flush();
      out.close();

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        }
        // else if (responseCode != HttpURLConnection.HTTP_OK)
        // else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207))
        else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0009.p2p.msg.send.failed");
      throw new SOAPExceptionImpl("Message send failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());

        byte[] bytes = readFully(httpIn);

        int length =
            httpConnection.getContentLength() == -1
                ? bytes.length
                : httpConnection.getContentLength();

        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        if (length == 0) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          ByteInputStream in = new ByteInputStream(bytes, length);
          response = messageFactory.createMessage(headers, in);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }
Example #20
0
  public static void main(String[] args) {
    try {
      if (args[0].equals("-genkey")) {
        KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = new SecureRandom();
        pairgen.initialize(KEYSIZE, random);
        KeyPair keyPair = pairgen.generateKeyPair();
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
        out.writeObject(keyPair.getPublic());
        out.close();
        out = new ObjectOutputStream(new FileOutputStream(args[2]));
        out.writeObject(keyPair.getPrivate());
        out.close();
      } else if (args[0].equals("-encrypt")) {
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        SecretKey key = keygen.generateKey();

        // wrap with RSA public key
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key publicKey = (Key) keyIn.readObject();
        keyIn.close();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] wrappedKey = cipher.wrap(key);
        DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
        out.writeInt(wrappedKey.length);
        out.write(wrappedKey);

        InputStream in = new FileInputStream(args[1]);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        crypt(in, out, cipher);
        in.close();
        out.close();
      } else {
        DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
        int length = in.readInt();
        byte[] wrappedKey = new byte[length];
        in.read(wrappedKey, 0, length);

        // unwrap with RSA private key
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key privateKey = (Key) keyIn.readObject();
        keyIn.close();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.UNWRAP_MODE, privateKey);
        Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

        OutputStream out = new FileOutputStream(args[2]);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);

        crypt(in, out, cipher);
        in.close();
        out.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
Example #21
0
 /**
  * Sends a command, argument, and input.
  *
  * @param cmd command
  * @param path path to document
  * @param input xml input
  * @throws IOException I/O exception
  */
 private void send(final int cmd, final String path, final InputStream input) throws IOException {
   out.write(cmd);
   send(path);
   send(input);
 }
  private byte[] transform(Data dereferencedData, XMLCryptoContext context)
      throws XMLSignatureException {

    if (md == null) {
      try {
        md =
            MessageDigest.getInstance(((DOMDigestMethod) digestMethod).getMessageDigestAlgorithm());
      } catch (NoSuchAlgorithmException nsae) {
        throw new XMLSignatureException(nsae);
      }
    }
    md.reset();
    DigesterOutputStream dos;
    Boolean cache = (Boolean) context.getProperty("javax.xml.crypto.dsig.cacheReference");
    if (cache != null && cache.booleanValue() == true) {
      this.derefData = copyDerefData(dereferencedData);
      dos = new DigesterOutputStream(md, true);
    } else {
      dos = new DigesterOutputStream(md);
    }
    OutputStream os = new UnsyncBufferedOutputStream(dos);
    Data data = dereferencedData;
    for (int i = 0, size = transforms.size(); i < size; i++) {
      DOMTransform transform = (DOMTransform) transforms.get(i);
      try {
        if (i < size - 1) {
          data = transform.transform(data, context);
        } else {
          data = transform.transform(data, context, os);
        }
      } catch (TransformException te) {
        throw new XMLSignatureException(te);
      }
    }

    try {
      if (data != null) {
        XMLSignatureInput xi;
        if (data instanceof ApacheData) {
          xi = ((ApacheData) data).getXMLSignatureInput();
        } else if (data instanceof OctetStreamData) {
          xi = new XMLSignatureInput(((OctetStreamData) data).getOctetStream());
        } else if (data instanceof NodeSetData) {
          TransformService spi =
              TransformService.getInstance(CanonicalizationMethod.INCLUSIVE, "DOM");
          data = spi.transform(data, context);
          xi = new XMLSignatureInput(((OctetStreamData) data).getOctetStream());
        } else {
          throw new XMLSignatureException("unrecognized Data type");
        }
        xi.updateOutputStream(os);
      }
      os.flush();
      if (cache != null && cache.booleanValue() == true) {
        this.dis = dos.getInputStream();
      }
      return dos.getDigestValue();
    } catch (Exception e) {
      throw new XMLSignatureException(e);
    }
  }
Example #23
0
  /** Unpacks a resource to a temp. file */
  public static File unpackInstaller(String resourceName) {
    // Array to hold all results (this code is slightly more
    // generally that it needs to be)
    File[] results = new File[1];
    URL[] urls = new URL[1];

    // Determine size of download
    ClassLoader cl = Main.class.getClassLoader();
    urls[0] = cl.getResource(Config.getInstallerResource());
    if (urls[0] == null) {
      Config.trace("Could not find resource: " + Config.getInstallerResource());
      return null;
    }

    int totalSize = 0;
    int totalRead = 0;
    for (int i = 0; i < urls.length; i++) {
      if (urls[i] != null) {
        try {
          URLConnection connection = urls[i].openConnection();
          totalSize += connection.getContentLength();
        } catch (IOException ioe) {
          Config.trace("Got exception: " + ioe);
          return null;
        }
      }
    }

    // Unpack each file
    for (int i = 0; i < urls.length; i++) {
      if (urls[i] != null) {
        // Create temp. file to store unpacked file in
        InputStream in = null;
        OutputStream out = null;
        try {
          // Use extension from URL (important for dll files)
          String extension = new File(urls[i].getFile()).getName();
          int lastdotidx = (extension != null) ? extension.lastIndexOf('.') : -1;
          if (lastdotidx == -1) {
            extension = ".dat";
          } else {
            extension = extension.substring(lastdotidx);
          }

          // Create output stream
          results[i] = File.createTempFile("jre", extension);
          results[i].deleteOnExit();
          out = new FileOutputStream(results[i]);

          // Create inputstream
          URLConnection connection = urls[i].openConnection();
          in = connection.getInputStream();

          int read = 0;
          byte[] buf = new byte[BUFFER_SIZE];
          while ((read = in.read(buf)) != -1) {
            out.write(buf, 0, read);
            // Notify delegate
            totalRead += read;
            if (totalRead > totalSize && totalSize != 0) totalSize = totalRead;

            // Update UI
            if (totalSize != 0) {
              int percent = (100 * totalRead) / totalSize;
              setStepText(STEP_UNPACK, Config.getWindowStepProgress(STEP_UNPACK, percent));
            }
          }
        } catch (IOException ie) {
          Config.trace("Got exception while downloading resource: " + ie);
          for (int j = 0; j < results.length; j++) {
            if (results[j] != null) results[j].delete();
          }
          return null;
        } finally {
          try {
            if (in != null) in.close();
            if (out != null) out.close();
          } catch (IOException io) {
            /* ignore */
          }
        }
      }
    }

    setStepText(STEP_UNPACK, Config.getWindowStep(STEP_UNPACK));
    return results[0];
  }