Search in sources :

Example 1 with PushNetworkException

use of org.whispersystems.signalservice.api.push.exceptions.PushNetworkException in project Signal-Android by WhisperSystems.

the class DeliveryReceiptJobTest method testNetworkError.

@Test
public void testNetworkError() throws IOException {
    SignalServiceMessageSender textSecureMessageSender = mock(SignalServiceMessageSender.class);
    long timestamp = System.currentTimeMillis();
    Mockito.doThrow(new PushNetworkException("network error")).when(textSecureMessageSender).sendDeliveryReceipt(any(SignalServiceAddress.class), eq(timestamp));
    DeliveryReceiptJob deliveryReceiptJob = new DeliveryReceiptJob(context, "+14152222222", timestamp, "foo");
    ObjectGraph objectGraph = ObjectGraph.create(new TestModule(textSecureMessageSender));
    objectGraph.inject(deliveryReceiptJob);
    try {
        deliveryReceiptJob.onRun();
        throw new AssertionError();
    } catch (IOException e) {
        assertTrue(deliveryReceiptJob.onShouldRetry(e));
    }
    Mockito.doThrow(new NotFoundException("not found")).when(textSecureMessageSender).sendDeliveryReceipt(any(SignalServiceAddress.class), eq(timestamp));
    try {
        deliveryReceiptJob.onRun();
        throw new AssertionError();
    } catch (IOException e) {
        assertFalse(deliveryReceiptJob.onShouldRetry(e));
    }
}
Also used : PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) SignalServiceMessageSender(org.whispersystems.signalservice.api.SignalServiceMessageSender) ObjectGraph(dagger.ObjectGraph) NotFoundException(org.whispersystems.signalservice.api.push.exceptions.NotFoundException) SignalServiceAddress(org.whispersystems.signalservice.api.push.SignalServiceAddress) IOException(java.io.IOException) Test(org.junit.Test) BaseUnitTest(org.thoughtcrime.securesms.BaseUnitTest)

Example 2 with PushNetworkException

use of org.whispersystems.signalservice.api.push.exceptions.PushNetworkException in project libsignal-service-java by signalapp.

the class PushServiceSocket method makeServiceRequest.

private String makeServiceRequest(String urlFragment, String method, String body) throws NonSuccessfulResponseCodeException, PushNetworkException {
    Response response = getServiceConnection(urlFragment, method, body);
    int responseCode;
    String responseMessage;
    String responseBody;
    try {
        responseCode = response.code();
        responseMessage = response.message();
        responseBody = response.body().string();
    } catch (IOException ioe) {
        throw new PushNetworkException(ioe);
    }
    switch(responseCode) {
        case 413:
            throw new RateLimitException("Rate limit exceeded: " + responseCode);
        case 401:
        case 403:
            throw new AuthorizationFailedException("Authorization failed!");
        case 404:
            throw new NotFoundException("Not found");
        case 409:
            MismatchedDevices mismatchedDevices;
            try {
                mismatchedDevices = JsonUtil.fromJson(responseBody, MismatchedDevices.class);
            } catch (JsonProcessingException e) {
                Log.w(TAG, e);
                throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage);
            } catch (IOException e) {
                throw new PushNetworkException(e);
            }
            throw new MismatchedDevicesException(mismatchedDevices);
        case 410:
            StaleDevices staleDevices;
            try {
                staleDevices = JsonUtil.fromJson(responseBody, StaleDevices.class);
            } catch (JsonProcessingException e) {
                throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage);
            } catch (IOException e) {
                throw new PushNetworkException(e);
            }
            throw new StaleDevicesException(staleDevices);
        case 411:
            DeviceLimit deviceLimit;
            try {
                deviceLimit = JsonUtil.fromJson(responseBody, DeviceLimit.class);
            } catch (JsonProcessingException e) {
                throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage);
            } catch (IOException e) {
                throw new PushNetworkException(e);
            }
            throw new DeviceLimitExceededException(deviceLimit);
        case 417:
            throw new ExpectationFailedException();
        case 423:
            RegistrationLockFailure accountLockFailure;
            try {
                accountLockFailure = JsonUtil.fromJson(responseBody, RegistrationLockFailure.class);
            } catch (JsonProcessingException e) {
                Log.w(TAG, e);
                throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage);
            } catch (IOException e) {
                throw new PushNetworkException(e);
            }
            throw new LockedException(accountLockFailure.length, accountLockFailure.timeRemaining);
    }
    if (responseCode != 200 && responseCode != 204) {
        throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage);
    }
    return responseBody;
}
Also used : PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) RateLimitException(org.whispersystems.signalservice.api.push.exceptions.RateLimitException) ExpectationFailedException(org.whispersystems.signalservice.api.push.exceptions.ExpectationFailedException) NotFoundException(org.whispersystems.signalservice.api.push.exceptions.NotFoundException) NonSuccessfulResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException) StaleDevicesException(org.whispersystems.signalservice.internal.push.exceptions.StaleDevicesException) IOException(java.io.IOException) Response(okhttp3.Response) AuthorizationFailedException(org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException) MismatchedDevicesException(org.whispersystems.signalservice.internal.push.exceptions.MismatchedDevicesException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with PushNetworkException

use of org.whispersystems.signalservice.api.push.exceptions.PushNetworkException in project libsignal-service-java by signalapp.

the class PushServiceSocket method getServiceConnection.

private Response getServiceConnection(String urlFragment, String method, String body) throws PushNetworkException {
    try {
        ConnectionHolder connectionHolder = getRandom(serviceClients, random);
        OkHttpClient okHttpClient = connectionHolder.getClient().newBuilder().connectTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).readTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).build();
        Log.w(TAG, "Push service URL: " + connectionHolder.getUrl());
        Log.w(TAG, "Opening URL: " + String.format("%s%s", connectionHolder.getUrl(), urlFragment));
        Request.Builder request = new Request.Builder();
        request.url(String.format("%s%s", connectionHolder.getUrl(), urlFragment));
        if (body != null) {
            request.method(method, RequestBody.create(MediaType.parse("application/json"), body));
        } else {
            request.method(method, null);
        }
        if (credentialsProvider.getPassword() != null) {
            request.addHeader("Authorization", getAuthorizationHeader(credentialsProvider));
        }
        if (userAgent != null) {
            request.addHeader("X-Signal-Agent", userAgent);
        }
        if (connectionHolder.getHostHeader().isPresent()) {
            request.addHeader("Host", connectionHolder.getHostHeader().get());
        }
        Call call = okHttpClient.newCall(request.build());
        synchronized (connections) {
            connections.add(call);
        }
        try {
            return call.execute();
        } finally {
            synchronized (connections) {
                connections.remove(call);
            }
        }
    } catch (IOException e) {
        throw new PushNetworkException(e);
    }
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) Request(okhttp3.Request) IOException(java.io.IOException)

Example 4 with PushNetworkException

use of org.whispersystems.signalservice.api.push.exceptions.PushNetworkException in project libsignal-service-java by signalapp.

the class PushServiceSocket method uploadToCdn.

private byte[] uploadToCdn(String acl, String key, String policy, String algorithm, String credential, String date, String signature, InputStream data, String contentType, long length, OutputStreamFactory outputStreamFactory) throws PushNetworkException, NonSuccessfulResponseCodeException {
    ConnectionHolder connectionHolder = getRandom(cdnClients, random);
    OkHttpClient okHttpClient = connectionHolder.getClient().newBuilder().connectTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).readTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS).build();
    DigestingRequestBody file = new DigestingRequestBody(data, outputStreamFactory, contentType, length);
    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("acl", acl).addFormDataPart("key", key).addFormDataPart("policy", policy).addFormDataPart("Content-Type", contentType).addFormDataPart("x-amz-algorithm", algorithm).addFormDataPart("x-amz-credential", credential).addFormDataPart("x-amz-date", date).addFormDataPart("x-amz-signature", signature).addFormDataPart("file", "file", file).build();
    Request.Builder request = new Request.Builder().url(connectionHolder.getUrl()).post(requestBody);
    if (connectionHolder.getHostHeader().isPresent()) {
        request.addHeader("Host", connectionHolder.getHostHeader().get());
    }
    Call call = okHttpClient.newCall(request.build());
    synchronized (connections) {
        connections.add(call);
    }
    try {
        Response response;
        try {
            response = call.execute();
        } catch (IOException e) {
            throw new PushNetworkException(e);
        }
        if (response.isSuccessful())
            return file.getTransmittedDigest();
        else
            throw new NonSuccessfulResponseCodeException("Response: " + response);
    } finally {
        synchronized (connections) {
            connections.remove(call);
        }
    }
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) DigestingRequestBody(org.whispersystems.signalservice.internal.push.http.DigestingRequestBody) Request(okhttp3.Request) NonSuccessfulResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException) IOException(java.io.IOException) Response(okhttp3.Response) MultipartBody(okhttp3.MultipartBody) DigestingRequestBody(org.whispersystems.signalservice.internal.push.http.DigestingRequestBody) RequestBody(okhttp3.RequestBody)

Example 5 with PushNetworkException

use of org.whispersystems.signalservice.api.push.exceptions.PushNetworkException in project libsignal-service-java by signalapp.

the class PushServiceSocket method downloadAttachment.

private void downloadAttachment(String url, File localDestination, int maxSizeBytes, ProgressListener listener) throws IOException {
    URL downloadUrl = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection();
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.setRequestMethod("GET");
    connection.setDoInput(true);
    try {
        if (connection.getResponseCode() != 200) {
            throw new NonSuccessfulResponseCodeException("Bad response: " + connection.getResponseCode());
        }
        OutputStream output = new FileOutputStream(localDestination);
        InputStream input = connection.getInputStream();
        byte[] buffer = new byte[4096];
        int contentLength = connection.getContentLength();
        int read, totalRead = 0;
        if (contentLength > maxSizeBytes) {
            throw new NonSuccessfulResponseCodeException("File exceeds maximum size.");
        }
        while ((read = input.read(buffer)) != -1) {
            output.write(buffer, 0, read);
            totalRead += read;
            if (totalRead > maxSizeBytes) {
                localDestination.delete();
                throw new NonSuccessfulResponseCodeException("File exceeds maximum size.");
            }
            if (listener != null) {
                listener.onAttachmentProgress(contentLength, totalRead);
            }
        }
        output.close();
        Log.w(TAG, "Downloaded: " + url + " to: " + localDestination.getAbsolutePath());
    } catch (IOException ioe) {
        throw new PushNetworkException(ioe);
    } finally {
        connection.disconnect();
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) PushNetworkException(org.whispersystems.signalservice.api.push.exceptions.PushNetworkException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DigestingOutputStream(org.whispersystems.signalservice.api.crypto.DigestingOutputStream) FileOutputStream(java.io.FileOutputStream) NonSuccessfulResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException) IOException(java.io.IOException) URL(java.net.URL)

Aggregations

PushNetworkException (org.whispersystems.signalservice.api.push.exceptions.PushNetworkException)22 IOException (java.io.IOException)19 Response (okhttp3.Response)13 NonSuccessfulResponseCodeException (org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException)13 Call (okhttp3.Call)12 OkHttpClient (okhttp3.OkHttpClient)11 Request (okhttp3.Request)11 ProfileKeyCredentialResponse (org.signal.zkgroup.profiles.ProfileKeyCredentialResponse)10 ReceiptCredentialResponse (org.signal.zkgroup.receipts.ReceiptCredentialResponse)10 CredentialResponse (org.whispersystems.signalservice.api.groupsv2.CredentialResponse)10 CallingResponse (org.whispersystems.signalservice.api.messages.calls.CallingResponse)10 VerifyDeviceResponse (org.whispersystems.signalservice.api.messages.multidevice.VerifyDeviceResponse)10 StorageAuthResponse (org.whispersystems.signalservice.api.storage.StorageAuthResponse)10 DiscoveryResponse (org.whispersystems.signalservice.internal.contacts.entities.DiscoveryResponse)10 KeyBackupResponse (org.whispersystems.signalservice.internal.contacts.entities.KeyBackupResponse)10 TokenResponse (org.whispersystems.signalservice.internal.contacts.entities.TokenResponse)10 ProfileKeyCredentialRequest (org.signal.zkgroup.profiles.ProfileKeyCredentialRequest)8 ReceiptCredentialRequest (org.signal.zkgroup.receipts.ReceiptCredentialRequest)8 ChangePhoneNumberRequest (org.whispersystems.signalservice.api.account.ChangePhoneNumberRequest)8 DiscoveryRequest (org.whispersystems.signalservice.internal.contacts.entities.DiscoveryRequest)8