Java Code Examples for org.whispersystems.libsignal.logging.Log#w()

The following examples show how to use org.whispersystems.libsignal.logging.Log#w() . 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: 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 2
Source File: SignalServiceContent.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static SignalServiceDataMessage.Quote createQuote(SignalServiceProtos.DataMessage content) throws ProtocolInvalidMessageException {
  if (!content.hasQuote()) return null;

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

  for (SignalServiceProtos.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 3
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 4
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 5
Source File: PushServiceSocket.java    From mollyim-android 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 6
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 7
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 8
Source File: WebSocketConnection.java    From libsignal-service-java 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()");
  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 9
Source File: WebSocketConnection.java    From libsignal-service-java 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.w(TAG, "Sending keep alive...");
      sendKeepAlive();
    } catch (Throwable e) {
      Log.w(TAG, e);
    }
  }
}
 
Example 10
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public SignalServiceProfile retrieveProfileByUsername(String username, Optional<UnidentifiedAccess> unidentifiedAccess)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  String response = makeServiceRequest(String.format(PROFILE_USERNAME_PATH, username), "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 11
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 12
Source File: SignalServiceAccountManager.java    From libsignal-service-java with 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 13
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public AttachmentV3UploadAttributes getAttachmentV3UploadAttributes() throws NonSuccessfulResponseCodeException, PushNetworkException {
  String response = makeServiceRequest(ATTACHMENT_V3_PATH, "GET", null);
  try {
    return JsonUtil.fromJson(response, AttachmentV3UploadAttributes.class);
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example 14
Source File: SignalServiceAccountManager.java    From mollyim-android 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 15
Source File: PhoneNumberFormatter.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public static String formatNumberInternational(String number) {
  try {
    PhoneNumberUtil util     = PhoneNumberUtil.getInstance();
    PhoneNumber parsedNumber = util.parse(number, null);
    return util.format(parsedNumber, PhoneNumberFormat.INTERNATIONAL);
  } catch (NumberParseException e) {
    Log.w(TAG, e);
    return number;
  }
}
 
Example 16
Source File: PhoneNumberFormatter.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public static String getInternationalFormatFromE164(String e164number) {
  try {
    PhoneNumberUtil util     = PhoneNumberUtil.getInstance();
    PhoneNumber parsedNumber = util.parse(e164number, null);
    return util.format(parsedNumber, PhoneNumberFormat.INTERNATIONAL);
  } catch (NumberParseException e) {
    Log.w(TAG, e);
    return e164number;
  }
}
 
Example 17
Source File: SessionBuilder.java    From Silence with 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 18
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private byte[] uploadToCdn2(String resumableUrl, InputStream data, String contentType, long length, OutputStreamFactory outputStreamFactory, ProgressListener progressListener, CancelationSignal cancelationSignal) throws IOException {
  ConnectionHolder connectionHolder = getRandom(cdnClientsMap.get(2), random);
  OkHttpClient     okHttpClient     = connectionHolder.getClient()
                                                      .newBuilder()
                                                      .connectTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS)
                                                      .readTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS)
                                                      .build();

  ResumeInfo           resumeInfo = getResumeInfo(resumableUrl, length);
  DigestingRequestBody file       = new DigestingRequestBody(data, outputStreamFactory, contentType, length, progressListener, cancelationSignal, resumeInfo.contentStart);

  if (resumeInfo.contentStart == length) {
    Log.w(TAG, "Resume start point == content length");
    try (NowhereBufferedSink buffer = new NowhereBufferedSink()) {
      file.writeTo(buffer);
    }
    return file.getTransmittedDigest();
  }

  Request.Builder request = new Request.Builder().url(resumableUrl)
                                                 .put(file)
                                                 .addHeader("Content-Range", resumeInfo.contentRange);

  if (connectionHolder.getHostHeader().isPresent()) {
    request.header("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);
    }
  }
}
 
Example 19
Source File: DeviceContactsInputStream.java    From libsignal-service-java with GNU General Public License v3.0 4 votes vote down vote up
public DeviceContact read() throws IOException {
  long   detailsLength     = readRawVarint32();
  byte[] detailsSerialized = new byte[(int)detailsLength];
  Util.readFully(in, detailsSerialized);

  SignalServiceProtos.ContactDetails details = SignalServiceProtos.ContactDetails.parseFrom(detailsSerialized);

  if (!SignalServiceAddress.isValidAddress(details.getUuid(), details.getNumber())) {
    throw new IOException("Missing contact address!");
  }

  SignalServiceAddress                    address     = new SignalServiceAddress(UuidUtil.parseOrNull(details.getUuid()), details.getNumber());
  Optional<String>                        name        = Optional.fromNullable(details.getName());
  Optional<SignalServiceAttachmentStream> avatar      = Optional.absent();
  Optional<String>                        color       = details.hasColor() ? Optional.of(details.getColor()) : Optional.<String>absent();
  Optional<VerifiedMessage>               verified    = Optional.absent();
  Optional<byte[]>                        profileKey  = Optional.absent();
  boolean                                 blocked     = false;
  Optional<Integer>                       expireTimer = Optional.absent();

  if (details.hasAvatar()) {
    long        avatarLength      = details.getAvatar().getLength();
    InputStream avatarStream      = new LimitedInputStream(in, avatarLength);
    String      avatarContentType = details.getAvatar().getContentType();

    avatar = Optional.of(new SignalServiceAttachmentStream(avatarStream, avatarContentType, avatarLength, Optional.<String>absent(), false, null));
  }

  if (details.hasVerified()) {
    try {
      if (!SignalServiceAddress.isValidAddress(details.getVerified().getDestinationUuid(), details.getVerified().getDestinationE164())) {
        throw new InvalidMessageException("Missing Verified address!");
      }
      IdentityKey          identityKey = new IdentityKey(details.getVerified().getIdentityKey().toByteArray(), 0);
      SignalServiceAddress destination = new SignalServiceAddress(UuidUtil.parseOrNull(details.getVerified().getDestinationUuid()),
                                                                  details.getVerified().getDestinationE164());

      VerifiedMessage.VerifiedState state;

      switch (details.getVerified().getState()) {
        case VERIFIED:  state = VerifiedMessage.VerifiedState.VERIFIED;   break;
        case UNVERIFIED:state = VerifiedMessage.VerifiedState.UNVERIFIED; break;
        case DEFAULT:   state = VerifiedMessage.VerifiedState.DEFAULT;    break;
        default:        throw new InvalidMessageException("Unknown state: " + details.getVerified().getState());
      }

      verified = Optional.of(new VerifiedMessage(destination, identityKey, state, System.currentTimeMillis()));
    } catch (InvalidKeyException | InvalidMessageException e) {
      Log.w(TAG, e);
      verified = Optional.absent();
    }
  }

  if (details.hasProfileKey()) {
    profileKey = Optional.fromNullable(details.getProfileKey().toByteArray());
  }

  if (details.hasExpireTimer() && details.getExpireTimer() > 0) {
    expireTimer = Optional.of(details.getExpireTimer());
  }

  blocked = details.getBlocked();

  return new DeviceContact(address, name, avatar, color, verified, profileKey, blocked, expireTimer);
}
 
Example 20
Source File: WebSocketConnection.java    From libsignal-service-java with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onMessage(WebSocket webSocket, String text) {
  Log.w(TAG, "onMessage(text)! " + text);
}