org.whispersystems.libsignal.logging.Log Java Examples

The following examples show how to use org.whispersystems.libsignal.logging.Log. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: mollyim-android   Author: mollyim   File: SignalServiceMessageSender.java    License: GNU General Public License v3.0 6 votes vote down vote up
public ResumableUploadSpec getResumableUploadSpec() throws IOException {
  AttachmentV3UploadAttributes       v3UploadAttributes = null;
  Optional<SignalServiceMessagePipe> localPipe          = pipe.get();

  if (localPipe.isPresent()) {
    Log.d(TAG, "Using pipe to retrieve attachment upload attributes...");
    try {
      v3UploadAttributes = localPipe.get().getAttachmentV3UploadAttributes();
    } catch (IOException e) {
      Log.w(TAG, "Failed to retrieve attachment upload attributes using pipe. Falling back...");
    }
  }

  if (v3UploadAttributes == null) {
    Log.d(TAG, "Not using pipe to retrieve attachment upload attributes...");
    v3UploadAttributes = socket.getAttachmentV3UploadAttributes();
  }

  return socket.getResumableUploadSpec(v3UploadAttributes);
}
 
Example #2
Source Project: Silence   Author: SilenceIM   File: PhoneNumberFormatter.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String formatE164(String countryCode, String number) {
  try {
    PhoneNumberUtil util     = PhoneNumberUtil.getInstance();
    int parsedCountryCode    = Integer.parseInt(countryCode);
    PhoneNumber parsedNumber = util.parse(number,
                                          util.getRegionCodeForCountryCode(parsedCountryCode));

    return util.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
  } catch (NumberParseException | NumberFormatException npe) {
    Log.w(TAG, npe);
  }

  return "+"                                                     +
      countryCode.replaceAll("[^0-9]", "").replaceAll("^0*", "") +
      number.replaceAll("[^0-9]", "");
}
 
Example #3
Source Project: mollyim-android   Author: mollyim   File: SignalServiceMessageSender.java    License: GNU General Public License v3.0 6 votes vote down vote up
private List<AttachmentPointer> createAttachmentPointers(Optional<List<SignalServiceAttachment>> attachments) throws IOException {
  List<AttachmentPointer> pointers = new LinkedList<>();

  if (!attachments.isPresent() || attachments.get().isEmpty()) {
    Log.w(TAG, "No attachments present...");
    return pointers;
  }

  for (SignalServiceAttachment attachment : attachments.get()) {
    if (attachment.isStream()) {
      Log.i(TAG, "Found attachment, creating pointer...");
      pointers.add(createAttachmentPointer(attachment.asStream()));
    } else if (attachment.isPointer()) {
      Log.i(TAG, "Including existing attachment pointer...");
      pointers.add(createAttachmentPointer(attachment.asPointer()));
    }
  }

  return pointers;
}
 
Example #4
Source Project: mollyim-android   Author: mollyim   File: GroupsV2Operations.java    License: GNU General Public License v3.0 6 votes vote down vote up
private GroupAttributeBlob decryptBlob(byte[] bytes) {
  // TODO GV2: Minimum field length checking should be responsibility of clientZkGroupCipher#decryptBlob
  if (bytes == null || bytes.length == 0) {
    return GroupAttributeBlob.getDefaultInstance();
  }
  if (bytes.length < 29) {
    Log.w(TAG, "Bad encrypted blob length");
    return GroupAttributeBlob.getDefaultInstance();
  }
  try {
    return GroupAttributeBlob.parseFrom(clientZkGroupCipher.decryptBlob(bytes));
  } catch (InvalidProtocolBufferException | VerificationFailedException e) {
    Log.w(TAG, "Bad encrypted blob");
    return GroupAttributeBlob.getDefaultInstance();
  }
}
 
Example #5
Source Project: mollyim-android   Author: mollyim   File: PhoneNumberFormatter.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String formatE164(String countryCode, String number) {
  try {
    PhoneNumberUtil util     = PhoneNumberUtil.getInstance();
    int parsedCountryCode    = Integer.parseInt(countryCode);
    PhoneNumber parsedNumber = util.parse(number,
                                          util.getRegionCodeForCountryCode(parsedCountryCode));

    return util.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
  } catch (NumberParseException | NumberFormatException npe) {
    Log.w(TAG, npe);
  }

  return "+"                                                     +
      countryCode.replaceAll("[^0-9]", "").replaceAll("^0*", "") +
      number.replaceAll("[^0-9]", "");
}
 
Example #6
Source Project: libsignal-service-java   Author: signalapp   File: WebSocketConnection.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public synchronized void onMessage(WebSocket webSocket, ByteString payload) {
  Log.w(TAG, "WSC onMessage()");
  try {
    WebSocketMessage message = WebSocketMessage.parseFrom(payload.toByteArray());

    Log.w(TAG, "Message Type: " + message.getType().getNumber());

    if (message.getType().getNumber() == WebSocketMessage.Type.REQUEST_VALUE)  {
      incomingRequests.add(message.getRequest());
    } else if (message.getType().getNumber() == WebSocketMessage.Type.RESPONSE_VALUE) {
      SettableFuture<Pair<Integer, String>> listener = outgoingRequests.get(message.getResponse().getId());
      if (listener != null) listener.set(new Pair<>(message.getResponse().getStatus(),
                                                    new String(message.getResponse().getBody().toByteArray())));
    }

    notifyAll();
  } catch (InvalidProtocolBufferException e) {
    Log.w(TAG, e);
  }
}
 
Example #7
Source Project: mollyim-android   Author: mollyim   File: PushServiceSocket.java    License: GNU General Public License v3.0 6 votes vote down vote up
public ProfileAndCredential retrieveVersionedProfileAndCredential(UUID target, ProfileKey profileKey, Optional<UnidentifiedAccess> unidentifiedAccess)
    throws NonSuccessfulResponseCodeException, PushNetworkException, VerificationFailedException
{
  ProfileKeyVersion                  profileKeyIdentifier = profileKey.getProfileKeyVersion(target);
  ProfileKeyCredentialRequestContext requestContext       = clientZkProfileOperations.createProfileKeyCredentialRequestContext(random, target, profileKey);
  ProfileKeyCredentialRequest        request              = requestContext.getRequest();

  String version           = profileKeyIdentifier.serialize();
  String credentialRequest = Hex.toStringCondensed(request.serialize());
  String subPath           = String.format("%s/%s/%s", target, version, credentialRequest);

  String response = makeServiceRequest(String.format(PROFILE_PATH, subPath), "GET", null, NO_HEADERS, unidentifiedAccess);

  try {
    SignalServiceProfile signalServiceProfile = JsonUtil.fromJson(response, SignalServiceProfile.class);

    ProfileKeyCredential profileKeyCredential = signalServiceProfile.getProfileKeyCredentialResponse() != null
                                              ? clientZkProfileOperations.receiveProfileKeyCredential(requestContext, signalServiceProfile.getProfileKeyCredentialResponse())
                                              : null;

    return new ProfileAndCredential(signalServiceProfile, SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL, Optional.fromNullable(profileKeyCredential));
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #8
Source Project: mollyim-android   Author: mollyim   File: PushServiceSocket.java    License: GNU General Public License v3.0 6 votes vote down vote up
public SignalServiceProfile retrieveVersionedProfile(UUID target, ProfileKey profileKey, Optional<UnidentifiedAccess> unidentifiedAccess)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  ProfileKeyVersion profileKeyIdentifier = profileKey.getProfileKeyVersion(target);

  String version = profileKeyIdentifier.serialize();
  String subPath = String.format("%s/%s", target, version);

  String response = makeServiceRequest(String.format(PROFILE_PATH, subPath), "GET", null, NO_HEADERS, unidentifiedAccess);

  try {
    return JsonUtil.fromJson(response, SignalServiceProfile.class);
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #9
Source Project: libsignal-protocol-java   Author: signalapp   File: SessionState.java    License: GNU General Public License v3.0 6 votes vote down vote up
private Pair<Chain,Integer> getReceiverChain(ECPublicKey senderEphemeral) {
  List<Chain> receiverChains = sessionStructure.getReceiverChainsList();
  int         index          = 0;

  for (Chain receiverChain : receiverChains) {
    try {
      ECPublicKey chainSenderRatchetKey = Curve.decodePoint(receiverChain.getSenderRatchetKey().toByteArray(), 0);

      if (chainSenderRatchetKey.equals(senderEphemeral)) {
        return new Pair<>(receiverChain,index);
      }
    } catch (InvalidKeyException e) {
      Log.w("SessionRecordV2", e);
    }

    index++;
  }

  return null;
}
 
Example #10
Source Project: mollyim-android   Author: mollyim   File: PushTransportDetails.java    License: GNU General Public License v3.0 6 votes vote down vote up
public byte[] getStrippedPaddingMessageBody(byte[] messageWithPadding) {
  if      (messageVersion < 2) throw new AssertionError("Unknown version: " + messageVersion);
  else if (messageVersion == 2) return messageWithPadding;

  int paddingStart = 0;

  for (int i=messageWithPadding.length-1;i>=0;i--) {
    if (messageWithPadding[i] == (byte)0x80) {
      paddingStart = i;
      break;
    } else if (messageWithPadding[i] != (byte)0x00) {
      Log.w(TAG, "Padding byte is malformed, returning unstripped padding.");
      return messageWithPadding;
    }
  }

  byte[] strippedMessage = new byte[paddingStart];
  System.arraycopy(messageWithPadding, 0, strippedMessage, 0, strippedMessage.length);

  return strippedMessage;
}
 
Example #11
Source Project: bcm-android   Author: bcmapp   File: PushTransportDetails.java    License: GNU General Public License v3.0 6 votes vote down vote up
public byte[] getStrippedPaddingMessageBody(byte[] messageWithPadding) {
  if      (messageVersion < 2) throw new AssertionError("Unknown version: " + messageVersion);
  else if (messageVersion == 2) return messageWithPadding;

  int paddingStart = 0;

  for (int i=messageWithPadding.length-1;i>=0;i--) {
    if (messageWithPadding[i] == (byte)0x80) {
      paddingStart = i;
      break;
    } else if (messageWithPadding[i] != (byte)0x00) {
      Log.w(TAG, "Padding byte is malformed, returning unstripped padding.");
      return messageWithPadding;
    }
  }

  byte[] strippedMessage = new byte[paddingStart];
  System.arraycopy(messageWithPadding, 0, strippedMessage, 0, strippedMessage.length);

  return strippedMessage;
}
 
Example #12
Source Project: libsignal-service-java   Author: signalapp   File: SignalServiceMessageSender.java    License: GNU General Public License v3.0 6 votes vote down vote up
private byte[] createMultiDeviceFetchTypeContent(SignalServiceSyncMessage.FetchType fetchType) {
  Content.Builder                 container    = Content.newBuilder();
  SyncMessage.Builder             syncMessage  = createSyncMessageBuilder();
  SyncMessage.FetchLatest.Builder fetchMessage = SyncMessage.FetchLatest.newBuilder();

  switch (fetchType) {
    case LOCAL_PROFILE:
      fetchMessage.setType(SyncMessage.FetchLatest.Type.LOCAL_PROFILE);
      break;
    case STORAGE_MANIFEST:
      fetchMessage.setType(SyncMessage.FetchLatest.Type.STORAGE_MANIFEST);
      break;
    default:
      Log.w(TAG, "Unknown fetch type!");
      break;
  }

  return container.setSyncMessage(syncMessage.setFetchLatest(fetchMessage)).build().toByteArray();
}
 
Example #13
Source Project: libsignal-service-java   Author: signalapp   File: SignalServiceMessageSender.java    License: GNU General Public License v3.0 6 votes vote down vote up
private List<AttachmentPointer> createAttachmentPointers(Optional<List<SignalServiceAttachment>> attachments) throws IOException {
  List<AttachmentPointer> pointers = new LinkedList<>();

  if (!attachments.isPresent() || attachments.get().isEmpty()) {
    Log.w(TAG, "No attachments present...");
    return pointers;
  }

  for (SignalServiceAttachment attachment : attachments.get()) {
    if (attachment.isStream()) {
      Log.w(TAG, "Found attachment, creating pointer...");
      pointers.add(createAttachmentPointer(attachment.asStream()));
    } else if (attachment.isPointer()) {
      Log.w(TAG, "Including existing attachment pointer...");
      pointers.add(createAttachmentPointer(attachment.asPointer()));
    }
  }

  return pointers;
}
 
Example #14
Source Project: libsignal-service-java   Author: signalapp   File: SignalServiceCipher.java    License: GNU General Public License v3.0 6 votes vote down vote up
private SignalServiceDataMessage.Quote createQuote(DataMessage content) {
  if (!content.hasQuote()) return null;

  List<SignalServiceDataMessage.Quote.QuotedAttachment> attachments = new LinkedList<>();

  for (DataMessage.Quote.QuotedAttachment attachment : content.getQuote().getAttachmentsList()) {
    attachments.add(new SignalServiceDataMessage.Quote.QuotedAttachment(attachment.getContentType(),
                                                                        attachment.getFileName(),
                                                                        attachment.hasThumbnail() ? createAttachmentPointer(attachment.getThumbnail()) : null));
  }

  if (SignalServiceAddress.isValidAddress(content.getQuote().getAuthorUuid(), content.getQuote().getAuthorE164())) {
    SignalServiceAddress address = new SignalServiceAddress(UuidUtil.parseOrNull(content.getQuote().getAuthorUuid()), content.getQuote().getAuthorE164());

    return new SignalServiceDataMessage.Quote(content.getQuote().getId(),
                                              address,
                                              content.getQuote().getText(),
                                              attachments);
  } else {
    Log.w(TAG, "Quote was missing an author! Returning null.");
    return null;
  }
}
 
Example #15
Source Project: libsignal-service-java   Author: signalapp   File: PhoneNumberFormatter.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String formatE164(String countryCode, String number) {
  try {
    PhoneNumberUtil util     = PhoneNumberUtil.getInstance();
    int parsedCountryCode    = Integer.parseInt(countryCode);
    PhoneNumber parsedNumber = util.parse(number,
                                          util.getRegionCodeForCountryCode(parsedCountryCode));

    return util.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
  } catch (NumberParseException | NumberFormatException npe) {
    Log.w(TAG, npe);
  }

  return "+"                                                     +
      countryCode.replaceAll("[^0-9]", "").replaceAll("^0*", "") +
      number.replaceAll("[^0-9]", "");
}
 
Example #16
Source Project: libsignal-service-java   Author: signalapp   File: PushServiceSocket.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void setProfileAvatar(ProfileAvatarData profileAvatar)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  String                        response       = makeServiceRequest(String.format(PROFILE_PATH, "form/avatar"), "GET", null);
  ProfileAvatarUploadAttributes formAttributes;

  try {
    formAttributes = JsonUtil.fromJson(response, ProfileAvatarUploadAttributes.class);
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }

  if (profileAvatar != null) {
    uploadToCdn("", formAttributes.getAcl(), formAttributes.getKey(),
                formAttributes.getPolicy(), formAttributes.getAlgorithm(),
                formAttributes.getCredential(), formAttributes.getDate(),
                formAttributes.getSignature(), profileAvatar.getData(),
                profileAvatar.getContentType(), profileAvatar.getDataLength(),
                profileAvatar.getOutputStreamFactory(), null);
  }
}
 
Example #17
Source Project: libsignal-service-java   Author: signalapp   File: PushTransportDetails.java    License: GNU General Public License v3.0 6 votes vote down vote up
public byte[] getStrippedPaddingMessageBody(byte[] messageWithPadding) {
  if      (messageVersion < 2) throw new AssertionError("Unknown version: " + messageVersion);
  else if (messageVersion == 2) return messageWithPadding;

  int paddingStart = 0;

  for (int i=messageWithPadding.length-1;i>=0;i--) {
    if (messageWithPadding[i] == (byte)0x80) {
      paddingStart = i;
      break;
    } else if (messageWithPadding[i] != (byte)0x00) {
      Log.w(TAG, "Padding byte is malformed, returning unstripped padding.");
      return messageWithPadding;
    }
  }

  byte[] strippedMessage = new byte[paddingStart];
  System.arraycopy(messageWithPadding, 0, strippedMessage, 0, strippedMessage.length);

  return strippedMessage;
}
 
Example #18
Source Project: mollyim-android   Author: mollyim   File: SignalServiceAccountManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void reportContactDiscoveryServiceMatch() {
  try {
    this.pushServiceSocket.reportContactDiscoveryServiceMatch();
  } catch (IOException e) {
    Log.w(TAG, "Request to indicate a contact discovery result match failed. Ignoring.", e);
  }
}
 
Example #19
Source Project: mollyim-android   Author: mollyim   File: SignalServiceAccountManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void reportContactDiscoveryServiceMismatch() {
  try {
    this.pushServiceSocket.reportContactDiscoveryServiceMismatch();
  } catch (IOException e) {
    Log.w(TAG, "Request to indicate a contact discovery result mismatch failed. Ignoring.", e);
  }
}
 
Example #20
Source Project: mollyim-android   Author: mollyim   File: SignalServiceAccountManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void reportContactDiscoveryServiceAttestationError(String reason) {
  try {
    this.pushServiceSocket.reportContactDiscoveryServiceAttestationError(reason);
  } catch (IOException e) {
    Log.w(TAG, "Request to indicate a contact discovery attestation error failed. Ignoring.", e);
  }
}
 
Example #21
Source Project: mollyim-android   Author: mollyim   File: SignalServiceAccountManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void reportContactDiscoveryServiceUnexpectedError(String reason) {
  try {
    this.pushServiceSocket.reportContactDiscoveryServiceUnexpectedError(reason);
  } catch (IOException e) {
    Log.w(TAG, "Request to indicate a contact discovery unexpected error failed. Ignoring.", e);
  }
}
 
Example #22
Source Project: mollyim-android   Author: mollyim   File: SignalServiceAccountManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Optional<SignalStorageManifest> getStorageManifest(StorageKey storageKey) throws IOException {
  try {
    String          authToken       = this.pushServiceSocket.getStorageAuth();
    StorageManifest storageManifest = this.pushServiceSocket.getStorageManifest(authToken);

    return Optional.of(SignalStorageModels.remoteToLocalStorageManifest(storageManifest, storageKey));
  } catch (InvalidKeyException | NotFoundException e) {
    Log.w(TAG, "Error while fetching manifest.", e);
    return Optional.absent();
  }
}
 
Example #23
Source Project: mollyim-android   Author: mollyim   File: SignalServiceAccountManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Optional<SignalStorageManifest> getStorageManifestIfDifferentVersion(StorageKey storageKey, long manifestVersion) throws IOException, InvalidKeyException {
  try {
    String          authToken       = this.pushServiceSocket.getStorageAuth();
    StorageManifest storageManifest = this.pushServiceSocket.getStorageManifestIfDifferentVersion(authToken, manifestVersion);

    if (storageManifest.getValue().isEmpty()) {
      Log.w(TAG, "Got an empty storage manifest!");
      return Optional.absent();
    }

    return Optional.of(SignalStorageModels.remoteToLocalStorageManifest(storageManifest, storageKey));
  } catch (NoContentException e) {
    return Optional.absent();
  }
}
 
Example #24
Source Project: mollyim-android   Author: mollyim   File: SignalServiceAccountManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public List<SignalStorageRecord> readStorageRecords(StorageKey storageKey, List<StorageId> storageKeys) throws IOException, InvalidKeyException {
  if (storageKeys.isEmpty()) {
    return Collections.emptyList();
  }

  List<SignalStorageRecord> result    = new ArrayList<>();
  ReadOperation.Builder     operation = ReadOperation.newBuilder();
  Map<ByteString, Integer>  typeMap   = new HashMap<>();

  for (StorageId key : storageKeys) {
    typeMap.put(ByteString.copyFrom(key.getRaw()), key.getType());

    if (StorageId.isKnownType(key.getType())) {
      operation.addReadKey(ByteString.copyFrom(key.getRaw()));
    } else {
      result.add(SignalStorageRecord.forUnknown(key));
    }
  }

  String       authToken = this.pushServiceSocket.getStorageAuth();
  StorageItems items     = this.pushServiceSocket.readStorageItems(authToken, operation.build());

  if (items.getItemsCount() != storageKeys.size()) {
    Log.w(TAG, "Failed to find all remote keys! Requested: " + storageKeys.size() + ", Found: " + items.getItemsCount());
  }

  for (StorageItem item : items.getItemsList()) {
    Integer type = typeMap.get(item.getKey());
    if (type != null) {
      result.add(SignalStorageModels.remoteToLocalStorageRecord(item, type, storageKey));
    } else {
      Log.w(TAG, "No type found! Skipping.");
    }
  }

  return result;
}
 
Example #25
Source Project: Silence   Author: SilenceIM   File: SessionBuilder.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void processResponse(KeyExchangeMessage message)
    throws StaleKeyExchangeException, InvalidKeyException
{
  SessionRecord sessionRecord                  = sessionStore.loadSession(remoteAddress);
  SessionState  sessionState                   = sessionRecord.getSessionState();
  boolean       hasPendingKeyExchange          = sessionState.hasPendingKeyExchange();
  boolean       isSimultaneousInitiateResponse = message.isResponseForSimultaneousInitiate();

  if (!hasPendingKeyExchange || sessionState.getPendingKeyExchangeSequence() != message.getSequence()) {
    Log.w(TAG, "No matching sequence for response. Is simultaneous initiate response: " + isSimultaneousInitiateResponse);
    if (!isSimultaneousInitiateResponse) throw new StaleKeyExchangeException();
    else                                 return;
  }

  SymmetricSignalProtocolParameters.Builder parameters = SymmetricSignalProtocolParameters.newBuilder();

  parameters.setOurBaseKey(sessionRecord.getSessionState().getPendingKeyExchangeBaseKey())
            .setOurRatchetKey(sessionRecord.getSessionState().getPendingKeyExchangeRatchetKey())
            .setOurIdentityKey(sessionRecord.getSessionState().getPendingKeyExchangeIdentityKey())
            .setTheirBaseKey(message.getBaseKey())
            .setTheirRatchetKey(message.getRatchetKey())
            .setTheirIdentityKey(message.getIdentityKey());

  if (!sessionRecord.isFresh()) sessionRecord.archiveCurrentState();

  RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters.create());

  if (!Curve.verifySignature(message.getIdentityKey().getPublicKey(),
                             message.getBaseKey().serialize(),
                             message.getBaseKeySignature()))
  {
    throw new InvalidKeyException("Base key signature doesn't match!");
  }

  identityKeyStore.saveIdentity(remoteAddress, message.getIdentityKey());
  sessionStore.storeSession(remoteAddress, sessionRecord);
}
 
Example #26
Source Project: mollyim-android   Author: mollyim   File: SignalServiceMessageSender.java    License: GNU General Public License v3.0 5 votes vote down vote up
private SignalServiceAttachmentPointer uploadAttachmentV2(SignalServiceAttachmentStream attachment, byte[] attachmentKey, PushAttachmentData attachmentData) throws NonSuccessfulResponseCodeException, PushNetworkException {
  AttachmentV2UploadAttributes       v2UploadAttributes = null;
  Optional<SignalServiceMessagePipe> localPipe          = pipe.get();

  if (localPipe.isPresent()) {
    Log.d(TAG, "Using pipe to retrieve attachment upload attributes...");
    try {
      v2UploadAttributes = localPipe.get().getAttachmentV2UploadAttributes();
    } catch (IOException e) {
      Log.w(TAG, "Failed to retrieve attachment upload attributes using pipe. Falling back...");
    }
  }

  if (v2UploadAttributes == null) {
    Log.d(TAG, "Not using pipe to retrieve attachment upload attributes...");
    v2UploadAttributes = socket.getAttachmentV2UploadAttributes();
  }

  Pair<Long, byte[]> attachmentIdAndDigest = socket.uploadAttachment(attachmentData, v2UploadAttributes);

  return new SignalServiceAttachmentPointer(0,
                                            new SignalServiceAttachmentRemoteId(attachmentIdAndDigest.first()),
                                            attachment.getContentType(),
                                            attachmentKey,
                                            Optional.of(Util.toIntExact(attachment.getLength())),
                                            attachment.getPreview(),
                                            attachment.getWidth(), attachment.getHeight(),
                                            Optional.of(attachmentIdAndDigest.second()),
                                            attachment.getFileName(),
                                            attachment.getVoiceNote(),
                                            attachment.getCaption(),
                                            attachment.getBlurHash(),
                                            attachment.getUploadTimestamp());
}
 
Example #27
Source Project: mollyim-android   Author: mollyim   File: SignalServiceMessageSender.java    License: GNU General Public License v3.0 5 votes vote down vote up
private byte[] createMultiDeviceSyncKeysContent(KeysMessage keysMessage) {
  Content.Builder          container   = Content.newBuilder();
  SyncMessage.Builder      syncMessage = createSyncMessageBuilder();
  SyncMessage.Keys.Builder builder     = SyncMessage.Keys.newBuilder();

  if (keysMessage.getStorageService().isPresent()) {
    builder.setStorageService(ByteString.copyFrom(keysMessage.getStorageService().get().serialize()));
  } else {
    Log.w(TAG, "Invalid keys message!");
  }

  return container.setSyncMessage(syncMessage.setKeys(builder)).build().toByteArray();
}
 
Example #28
Source Project: libsignal-service-java   Author: signalapp   File: WebSocketConnection.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized void onFailure(WebSocket webSocket, Throwable t, Response response) {
  Log.w(TAG, "onFailure()");
  Log.w(TAG, t);

  if (response != null && (response.code() == 401 || response.code() == 403)) {
    if (listener != null) listener.onAuthenticationFailure();
  }

  if (client != null) {
    onClosed(webSocket, 1000, "OK");
  }
}
 
Example #29
Source Project: mollyim-android   Author: mollyim   File: SignalServiceEnvelope.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void verifyMac(byte[] ciphertext, SecretKeySpec macKey) throws IOException {
  try {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(macKey);

    if (ciphertext.length < MAC_SIZE + 1)
      throw new IOException("Invalid MAC!");

    mac.update(ciphertext, 0, ciphertext.length - MAC_SIZE);

    byte[] ourMacFull  = mac.doFinal();
    byte[] ourMacBytes = new byte[MAC_SIZE];
    System.arraycopy(ourMacFull, 0, ourMacBytes, 0, ourMacBytes.length);

    byte[] theirMacBytes = new byte[MAC_SIZE];
    System.arraycopy(ciphertext, ciphertext.length-MAC_SIZE, theirMacBytes, 0, theirMacBytes.length);

    Log.w(TAG, "Our MAC: " + Hex.toString(ourMacBytes));
    Log.w(TAG, "Thr MAC: " + Hex.toString(theirMacBytes));

    if (!Arrays.equals(ourMacBytes, theirMacBytes)) {
      throw new IOException("Invalid MAC compare!");
    }
  } catch (NoSuchAlgorithmException | InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example #30
Source Project: mollyim-android   Author: mollyim   File: SignalServiceProfile.java    License: GNU General Public License v3.0 5 votes vote down vote up
public ProfileKeyCredentialResponse getProfileKeyCredentialResponse() {
  if (credential == null) return null;

  try {
    return new ProfileKeyCredentialResponse(credential);
  } catch (InvalidInputException e) {
    Log.w(TAG, e);
    return null;
  }
}