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 File: PhoneNumberFormatter.java    From Silence with 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 #2
Source File: SignalServiceMessageSender.java    From libsignal-service-java with 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 #3
Source File: SignalServiceCipher.java    From libsignal-service-java with 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 #4
Source File: PushTransportDetails.java    From bcm-android with 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 #5
Source File: GroupsV2Operations.java    From mollyim-android with 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 #6
Source File: SignalServiceMessageSender.java    From libsignal-service-java with 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 #7
Source File: PhoneNumberFormatter.java    From mollyim-android with 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 #8
Source File: PhoneNumberFormatter.java    From libsignal-service-java with 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 #9
Source File: SignalServiceMessageSender.java    From mollyim-android with 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 #10
Source File: SessionState.java    From libsignal-protocol-java with 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 #11
Source File: PushServiceSocket.java    From mollyim-android with 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 #12
Source File: SignalServiceMessageSender.java    From mollyim-android with 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 #13
Source File: PushServiceSocket.java    From mollyim-android with 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 #14
Source File: PushServiceSocket.java    From libsignal-service-java with 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 #15
Source File: WebSocketConnection.java    From libsignal-service-java with 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 #16
Source File: PushTransportDetails.java    From libsignal-service-java with 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 #17
Source File: PushTransportDetails.java    From mollyim-android with 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 File: AccountAttributesV2.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public AccountAttributesV2(String signalingKey, int registrationId, boolean fetchesMessages, String pubKey, String privateKey) {
    this.signalingKey = signalingKey;
    this.registrationId = registrationId;
    this.voice = true;
    this.video = true;
    this.fetchesMessages = fetchesMessages;
    this.pubKey = pubKey;
    this.privateKey = privateKey;

    Log.i("bindOpenId public V2:", pubKey);
    Log.i("bindOpenId private V2:", privateKey);
}
 
Example #19
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public SignalServiceProfile retrieveProfile(SignalServiceAddress target, Optional<UnidentifiedAccess> unidentifiedAccess)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  try {
    String response = makeServiceRequest(String.format(PROFILE_PATH, target.getIdentifier()), "GET", null, NO_HEADERS, unidentifiedAccess);
    return JsonUtil.fromJson(response, SignalServiceProfile.class);
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #20
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public List<ContactTokenDetails> retrieveDirectory(Set<String> contactTokens)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  try {
    ContactTokenList        contactTokenList = new ContactTokenList(new LinkedList<>(contactTokens));
    String                  response         = makeServiceRequest(DIRECTORY_TOKENS_PATH, "PUT", JsonUtil.toJson(contactTokenList));
    ContactTokenDetailsList activeTokens     = JsonUtil.fromJson(response, ContactTokenDetailsList.class);

    return activeTokens.getContacts();
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #21
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public void cancelInFlightRequests() {
  synchronized (connections) {
    Log.w(TAG, "Canceling: " + connections.size());
    for (Call connection : connections) {
      Log.w(TAG, "Canceling: " + connection);
      connection.cancel();
    }
  }
}
 
Example #22
Source File: SignalServiceAccountManager.java    From libsignal-service-java with 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 #23
Source File: AccountAttributesV3.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public AccountAttributesV3(String openId, String privateKey, String pubKey) {
    this.voice = false;
    this.video = false;
    this.fetchesMessages = true;
    this.openId = openId;
    this.privateKey = privateKey;
    this.pubKey = pubKey;

    Log.i("bindOpenId public V3:", pubKey);
    Log.i("bindOpenId private V3:", privateKey);
}
 
Example #24
Source File: WebSocketConnection.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void disconnect() {
  Log.i(TAG, "disconnect()");

  if (client != null) {
    client.close(1000, "OK");
    client    = null;
    connected = false;
  }

  if (keepAliveSender != null) {
    keepAliveSender.shutdown();
    keepAliveSender = null;
  }
}
 
Example #25
Source File: JsonUtil.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static String toJson(Object object) {
  try {
    return objectMapper.writeValueAsString(object);
  } catch (JsonProcessingException e) {
    Log.w(TAG, e);
    return "";
  }
}
 
Example #26
Source File: WebSocketConnection.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void run() {
  while (!stop.get()) {
    try {
      sleepTimer.sleep(TimeUnit.SECONDS.toMillis(KEEPALIVE_TIMEOUT_SECONDS));

      Log.d(TAG, "Sending keep alive...");
      sendKeepAlive();
    } catch (Throwable e) {
      Log.w(TAG, e);
    }
  }
}
 
Example #27
Source File: WebSocketConnection.java    From mollyim-android with 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()", t);

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

  if (client != null) {
    onClosed(webSocket, 1000, "OK");
  }
}
 
Example #28
Source File: WebSocketConnection.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized void onClosed(WebSocket webSocket, int code, String reason) {
  Log.i(TAG, "onClose()");
  this.connected = false;

  Iterator<Map.Entry<Long, OutgoingRequest>> iterator = outgoingRequests.entrySet().iterator();

  while (iterator.hasNext()) {
    Map.Entry<Long, OutgoingRequest> entry = iterator.next();
    entry.getValue().getResponseFuture().setException(new IOException("Closed: " + code + ", " + reason));
    iterator.remove();
  }

  if (keepAliveSender != null) {
    keepAliveSender.shutdown();
    keepAliveSender = null;
  }

  if (listener != null) {
    listener.onDisconnected();
  }

  Util.wait(this, Math.min(++attempts * 200, TimeUnit.SECONDS.toMillis(15)));

  if (client != null) {
    client.close(1000, "OK");
    client    = null;
    connected = false;
    connect();
  }

  notifyAll();
}
 
Example #29
Source File: WebSocketConnection.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized void onOpen(WebSocket webSocket, Response response) {
  if (client != null && keepAliveSender == null) {
    Log.i(TAG, "onOpen() connected");
    attempts        = 0;
    connected       = true;
    keepAliveSender = new KeepAliveSender();
    keepAliveSender.start();

    if (listener != null) listener.onConnected();
  }
}
 
Example #30
Source File: PhoneNumberFormatter.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public static String formatNumber(String number, String localNumber)
    throws InvalidNumberException
{
  if (number.contains("@")) {
    throw new InvalidNumberException("Possible attempt to use email address.");
  }

  number = number.replaceAll("[^0-9+]", "");

  if (number.length() == 0) {
    throw new InvalidNumberException("No valid characters found.");
  }

  if (number.charAt(0) == '+')
    return number;

  try {
    PhoneNumberUtil util          = PhoneNumberUtil.getInstance();
    PhoneNumber localNumberObject = util.parse(localNumber, null);

    String localCountryCode       = util.getRegionCodeForNumber(localNumberObject);
    Log.w(TAG, "Got local CC: " + localCountryCode);

    PhoneNumber numberObject      = util.parse(number, localCountryCode);
    return util.format(numberObject, PhoneNumberFormat.E164);
  } catch (NumberParseException e) {
    Log.w(TAG, e);
    return impreciseFormatNumber(number, localNumber);
  }
}