Search in sources :

Example 21 with FileDescriptor

use of java.io.FileDescriptor in project robovm by robovm.

the class NativeCryptoTest method test_SSL_SESSION_get_time.

public void test_SSL_SESSION_get_time() throws Exception {
    try {
        NativeCrypto.SSL_SESSION_get_time(NULL);
        fail();
    } catch (NullPointerException expected) {
    }
    final ServerSocket listener = new ServerSocket(0);
    {
        Hooks cHooks = new Hooks() {

            @Override
            public void afterHandshake(long session, long s, long c, Socket sock, FileDescriptor fd, SSLHandshakeCallbacks callback) throws Exception {
                long time = NativeCrypto.SSL_SESSION_get_time(session);
                assertTrue(time != 0);
                assertTrue(time < System.currentTimeMillis());
                super.afterHandshake(session, s, c, sock, fd, callback);
            }
        };
        Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates());
        Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null, null);
        Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null, null);
        client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
        server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    }
}
Also used : SSLHandshakeCallbacks(org.conscrypt.NativeCrypto.SSLHandshakeCallbacks) Future(java.util.concurrent.Future) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) FileDescriptor(java.io.FileDescriptor) SocketTimeoutException(java.net.SocketTimeoutException) SSLProtocolException(javax.net.ssl.SSLProtocolException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) SSLException(javax.net.ssl.SSLException)

Example 22 with FileDescriptor

use of java.io.FileDescriptor in project robovm by robovm.

the class FileInputStreamTest method testSkipInPipes.

public void testSkipInPipes() throws Exception {
    FileDescriptor[] pipe = Libcore.os.pipe();
    DataFeeder feeder = new DataFeeder(pipe[1]);
    try {
        feeder.start();
        FileInputStream fis = new FileInputStream(pipe[0]);
        fis.skip(SKIP_SIZE);
        verifyData(fis, SKIP_SIZE, TOTAL_SIZE - SKIP_SIZE);
        assertEquals(-1, fis.read());
        feeder.join(1000);
        assertFalse(feeder.isAlive());
    } finally {
        IoUtils.closeQuietly(pipe[0]);
    }
}
Also used : FileDescriptor(java.io.FileDescriptor) FileInputStream(java.io.FileInputStream)

Example 23 with FileDescriptor

use of java.io.FileDescriptor in project robovm by robovm.

the class InetAddress method isReachable.

private boolean isReachable(InetAddress destination, InetAddress source, int timeout) throws IOException {
    // TODO: try ICMP first (http://code.google.com/p/android/issues/detail?id=20106)
    FileDescriptor fd = IoBridge.socket(true);
    boolean reached = false;
    try {
        if (source != null) {
            IoBridge.bind(fd, source, 0);
        }
        IoBridge.connect(fd, destination, 7, timeout);
        reached = true;
    } catch (IOException e) {
        if (e.getCause() instanceof ErrnoException) {
            // "Connection refused" means the IP address was reachable.
            reached = (((ErrnoException) e.getCause()).errno == ECONNREFUSED);
        }
    }
    IoBridge.closeSocket(fd);
    return reached;
}
Also used : ErrnoException(libcore.io.ErrnoException) IOException(java.io.IOException) FileDescriptor(java.io.FileDescriptor)

Example 24 with FileDescriptor

use of java.io.FileDescriptor in project robovm by robovm.

the class PlainSocketImpl method accept.

@Override
protected void accept(SocketImpl newImpl) throws IOException {
    if (usingSocks()) {
        ((PlainSocketImpl) newImpl).socksBind();
        ((PlainSocketImpl) newImpl).socksAccept();
        return;
    }
    try {
        // RovmVM note: accept() on Darwin does not honor the SO_RCVTIMEO
        // set using setSoTimeout() on blocking sockets. As a work around we 
        // do poll() if a timeout has been set followed by an accept().
        int timeout = (Integer) getOption(SO_TIMEOUT);
        int flags = Libcore.os.fcntlVoid(fd, F_GETFL);
        if (timeout > 0 && (flags & O_NONBLOCK) == 0) {
            StructPollfd pfd = new StructPollfd();
            pfd.fd = fd;
            pfd.events = (short) (POLLIN | POLLERR);
            StructPollfd[] pfds = new StructPollfd[] { pfd };
            long start = System.currentTimeMillis();
            long deadline = start + timeout;
            while (true) {
                try {
                    if (timeout <= 0 || Libcore.os.poll(pfds, timeout) == 0) {
                        throw new SocketTimeoutException("accept() timed out");
                    }
                    break;
                } catch (ErrnoException e) {
                    if (e.errno == EINTR) {
                        long now = System.currentTimeMillis();
                        timeout = (int) (deadline - now);
                    } else {
                        throw e;
                    }
                }
            }
        }
        InetSocketAddress peerAddress = new InetSocketAddress();
        FileDescriptor clientFd = Libcore.os.accept(fd, peerAddress);
        // TODO: we can't just set newImpl.fd to clientFd because a nio SocketChannel may
        // be sharing the FileDescriptor. http://b//4452981.
        newImpl.fd.setInt$(clientFd.getInt$());
        newImpl.address = peerAddress.getAddress();
        newImpl.port = peerAddress.getPort();
    } catch (ErrnoException errnoException) {
        if (errnoException.errno == EAGAIN) {
            throw new SocketTimeoutException(errnoException);
        }
        throw errnoException.rethrowAsSocketException();
    }
    // Reset the client's inherited read timeout to the Java-specified default of 0.
    newImpl.setOption(SocketOptions.SO_TIMEOUT, Integer.valueOf(0));
    newImpl.localport = IoBridge.getSocketLocalPort(newImpl.fd);
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) ErrnoException(libcore.io.ErrnoException) InetSocketAddress(java.net.InetSocketAddress) StructPollfd(libcore.io.StructPollfd) FileDescriptor(java.io.FileDescriptor)

Example 25 with FileDescriptor

use of java.io.FileDescriptor in project Conversations by siacs.

the class XmppConnectionService method attachFileToConversation.

public void attachFileToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
    if (FileBackend.weOwnFile(this, uri)) {
        Log.d(Config.LOGTAG, "trying to attach file that belonged to us");
        callback.error(R.string.security_error_invalid_file_access, null);
        return;
    }
    final Message message;
    if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
        message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
    } else {
        message = new Message(conversation, "", conversation.getNextEncryption());
    }
    message.setCounterpart(conversation.getNextCounterpart());
    message.setType(Message.TYPE_FILE);
    mFileAddingExecutor.execute(new Runnable() {

        private void processAsFile() {
            final String path = getFileBackend().getOriginalPath(uri);
            if (path != null) {
                message.setRelativeFilePath(path);
                getFileBackend().updateFileParams(message);
                if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
                    getPgpEngine().encrypt(message, callback);
                } else {
                    callback.success(message);
                }
            } else {
                try {
                    getFileBackend().copyFileToPrivateStorage(message, uri);
                    getFileBackend().updateFileParams(message);
                    if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
                        final PgpEngine pgpEngine = getPgpEngine();
                        if (pgpEngine != null) {
                            pgpEngine.encrypt(message, callback);
                        } else if (callback != null) {
                            callback.error(R.string.unable_to_connect_to_keychain, null);
                        }
                    } else {
                        callback.success(message);
                    }
                } catch (FileBackend.FileCopyException e) {
                    callback.error(e.getResId(), message);
                }
            }
        }

        private void processAsVideo() throws FileNotFoundException {
            Log.d(Config.LOGTAG, "processing file as video");
            message.setRelativeFilePath(message.getUuid() + ".mp4");
            final DownloadableFile file = getFileBackend().getFile(message);
            file.getParentFile().mkdirs();
            ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            final ArrayList<Integer> progressTracker = new ArrayList<>();
            final UiInformableCallback<Message> informableCallback;
            if (callback instanceof UiInformableCallback) {
                informableCallback = (UiInformableCallback<Message>) callback;
            } else {
                informableCallback = null;
            }
            MediaTranscoder.Listener listener = new MediaTranscoder.Listener() {

                @Override
                public void onTranscodeProgress(double progress) {
                    int p = ((int) Math.round(progress * 100) / 20) * 20;
                    if (!progressTracker.contains(p) && p != 100 && p != 0) {
                        progressTracker.add(p);
                        if (informableCallback != null) {
                            informableCallback.inform(getString(R.string.transcoding_video_progress, p));
                        }
                    }
                }

                @Override
                public void onTranscodeCompleted() {
                    if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
                        getPgpEngine().encrypt(message, callback);
                    } else {
                        callback.success(message);
                    }
                }

                @Override
                public void onTranscodeCanceled() {
                    processAsFile();
                }

                @Override
                public void onTranscodeFailed(Exception e) {
                    Log.d(Config.LOGTAG, "video transcoding failed " + e.getMessage());
                    processAsFile();
                }
            };
            MediaTranscoder.getInstance().transcodeVideo(fileDescriptor, file.getAbsolutePath(), MediaFormatStrategyPresets.createAndroid720pStrategy(), listener);
        }

        @Override
        public void run() {
            final String mimeType = MimeUtils.guessMimeTypeFromUri(XmppConnectionService.this, uri);
            if (mimeType != null && mimeType.startsWith("video/") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                try {
                    processAsVideo();
                } catch (Throwable e) {
                    processAsFile();
                }
            } else {
                processAsFile();
            }
        }
    });
}
Also used : OnPhoneContactsLoadedListener(eu.siacs.conversations.utils.OnPhoneContactsLoadedListener) OnBindListener(eu.siacs.conversations.xmpp.OnBindListener) OnRenameListener(eu.siacs.conversations.entities.MucOptions.OnRenameListener) XmppAxolotlMessage(eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage) Message(eu.siacs.conversations.entities.Message) FileNotFoundException(java.io.FileNotFoundException) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) PgpEngine(eu.siacs.conversations.crypto.PgpEngine) MediaTranscoder(net.ypresto.androidtranscoder.MediaTranscoder) ParcelFileDescriptor(android.os.ParcelFileDescriptor) FileDescriptor(java.io.FileDescriptor) UiInformableCallback(eu.siacs.conversations.ui.UiInformableCallback) OtrException(net.java.otr4j.OtrException) FileNotFoundException(java.io.FileNotFoundException) InvalidJidException(eu.siacs.conversations.xmpp.jid.InvalidJidException) CertificateException(java.security.cert.CertificateException) ParcelFileDescriptor(android.os.ParcelFileDescriptor) DownloadableFile(eu.siacs.conversations.entities.DownloadableFile)

Aggregations

FileDescriptor (java.io.FileDescriptor)361 IOException (java.io.IOException)161 ParcelFileDescriptor (android.os.ParcelFileDescriptor)95 ErrnoException (android.system.ErrnoException)95 FileInputStream (java.io.FileInputStream)82 File (java.io.File)51 AssetFileDescriptor (android.content.res.AssetFileDescriptor)37 FileOutputStream (java.io.FileOutputStream)35 Bitmap (android.graphics.Bitmap)30 LocalSocket (android.net.LocalSocket)26 FileNotFoundException (java.io.FileNotFoundException)26 SmallTest (android.test.suitebuilder.annotation.SmallTest)17 InputStream (java.io.InputStream)15 Socket (java.net.Socket)14 ErrnoException (libcore.io.ErrnoException)14 Test (org.junit.Test)14 ServerSocket (java.net.ServerSocket)13 SSLHandshakeCallbacks (org.conscrypt.NativeCrypto.SSLHandshakeCallbacks)13 RemoteException (android.os.RemoteException)12 BitmapFactory (android.graphics.BitmapFactory)11