mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 05:36:50 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
407f596b61 | ||
|
|
41d30fc8dc | ||
|
|
2e429c5b35 | ||
|
|
28afe3470b | ||
|
|
f623b24196 | ||
|
|
2016c17894 | ||
|
|
2d28077010 | ||
|
|
7011f3c3c7 | ||
|
|
1403dbd5dd | ||
|
|
6ef3845a34 | ||
|
|
de2f0914f0 | ||
|
|
080ae0985f | ||
|
|
887f49760f | ||
|
|
be77f2291b | ||
|
|
b585b849a1 | ||
|
|
0c94e3d994 | ||
|
|
4a93658d0f | ||
|
|
6da19c6254 | ||
|
|
289058be81 | ||
|
|
864675ecde | ||
|
|
c79d7e3e30 | ||
|
|
549cc6f492 | ||
|
|
aa84ab66af |
No files matched your search
@@ -9,7 +9,7 @@
|
||||
|
||||
<groupId>org.whispersystems.textsecure</groupId>
|
||||
<artifactId>TextSecureServer</artifactId>
|
||||
<version>0.31</version>
|
||||
<version>0.41</version>
|
||||
|
||||
<properties>
|
||||
<dropwizard.version>0.7.1</dropwizard.version>
|
||||
@@ -106,7 +106,7 @@
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
<version>2.6.1</version>
|
||||
<version>2.6.2</version>
|
||||
<type>jar</type>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
@@ -129,7 +129,7 @@
|
||||
<dependency>
|
||||
<groupId>org.whispersystems</groupId>
|
||||
<artifactId>websocket-resources</artifactId>
|
||||
<version>0.2.0</version>
|
||||
<version>0.2.3</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ message PubSubMessage {
|
||||
QUERY_DB = 1;
|
||||
DELIVER = 2;
|
||||
KEEPALIVE = 3;
|
||||
CLOSE = 4;
|
||||
}
|
||||
|
||||
optional Type type = 1;
|
||||
|
||||
@@ -75,6 +75,7 @@ import org.whispersystems.textsecuregcm.storage.PubSubManager;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.UrlSigner;
|
||||
import org.whispersystems.textsecuregcm.websocket.AuthenticatedConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.DeadLetterHandler;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.workers.DirectoryCommand;
|
||||
@@ -157,7 +158,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, directory, cacheClient);
|
||||
FederatedClientManager federatedClientManager = new FederatedClientManager(config.getFederationConfiguration());
|
||||
MessagesManager messagesManager = new MessagesManager(messages);
|
||||
PubSubManager pubSubManager = new PubSubManager(cacheClient);
|
||||
DeadLetterHandler deadLetterHandler = new DeadLetterHandler(messagesManager);
|
||||
PubSubManager pubSubManager = new PubSubManager(cacheClient, deadLetterHandler);
|
||||
PushServiceClient pushServiceClient = new PushServiceClient(httpClient, config.getPushConfiguration());
|
||||
WebsocketSender websocketSender = new WebsocketSender(messagesManager, pubSubManager);
|
||||
AccountAuthenticator deviceAuthenticator = new AccountAuthenticator(accountsManager);
|
||||
@@ -196,7 +198,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.jersey().register(messageController);
|
||||
|
||||
if (config.getWebsocketConfiguration().isEnabled()) {
|
||||
WebSocketEnvironment webSocketEnvironment = new WebSocketEnvironment(environment, config);
|
||||
WebSocketEnvironment webSocketEnvironment = new WebSocketEnvironment(environment, config, 90000);
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(deviceAuthenticator));
|
||||
webSocketEnvironment.setConnectListener(new AuthenticatedConnectListener(accountsManager, pushSender, messagesManager, pubSubManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController());
|
||||
|
||||
@@ -197,10 +197,14 @@ public class AccountController {
|
||||
@PUT
|
||||
@Path("/gcm/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public void setGcmRegistrationId(@Auth Account account, @Valid GcmRegistrationId registrationId) {
|
||||
public void setGcmRegistrationId(@Auth Account account, @Valid GcmRegistrationId registrationId) {
|
||||
Device device = account.getAuthenticatedDevice().get();
|
||||
device.setApnId(null);
|
||||
device.setGcmId(registrationId.getGcmRegistrationId());
|
||||
|
||||
if (registrationId.isWebSocketChannel()) device.setFetchesMessages(true);
|
||||
else device.setFetchesMessages(false);
|
||||
|
||||
accounts.update(account);
|
||||
}
|
||||
|
||||
@@ -210,6 +214,7 @@ public class AccountController {
|
||||
public void deleteGcmRegistrationId(@Auth Account account) {
|
||||
Device device = account.getAuthenticatedDevice().get();
|
||||
device.setGcmId(null);
|
||||
device.setFetchesMessages(false);
|
||||
accounts.update(account);
|
||||
}
|
||||
|
||||
@@ -221,6 +226,7 @@ public class AccountController {
|
||||
Device device = account.getAuthenticatedDevice().get();
|
||||
device.setApnId(registrationId.getApnRegistrationId());
|
||||
device.setGcmId(null);
|
||||
device.setFetchesMessages(true);
|
||||
accounts.update(account);
|
||||
}
|
||||
|
||||
@@ -230,6 +236,25 @@ public class AccountController {
|
||||
public void deleteApnRegistrationId(@Auth Account account) {
|
||||
Device device = account.getAuthenticatedDevice().get();
|
||||
device.setApnId(null);
|
||||
device.setFetchesMessages(false);
|
||||
accounts.update(account);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/wsc/")
|
||||
public void setWebSocketChannelSupported(@Auth Account account) {
|
||||
Device device = account.getAuthenticatedDevice().get();
|
||||
device.setFetchesMessages(true);
|
||||
accounts.update(account);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/wsc/")
|
||||
public void deleteWebSocketChannel(@Auth Account account) {
|
||||
Device device = account.getAuthenticatedDevice().get();
|
||||
device.setFetchesMessages(false);
|
||||
accounts.update(account);
|
||||
}
|
||||
|
||||
|
||||
@@ -120,6 +120,7 @@ public class DeviceController {
|
||||
device.setSignalingKey(accountAttributes.getSignalingKey());
|
||||
device.setFetchesMessages(accountAttributes.getFetchesMessages());
|
||||
device.setId(account.get().getNextDeviceId());
|
||||
device.setRegistrationId(accountAttributes.getRegistrationId());
|
||||
device.setLastSeen(Util.todayInMillis());
|
||||
|
||||
account.get().addDevice(device);
|
||||
|
||||
@@ -74,7 +74,7 @@ public class DirectoryController {
|
||||
rateLimiters.getContactsLimiter().validate(account.getNumber());
|
||||
|
||||
try {
|
||||
Optional<ClientContact> contact = directory.get(Base64.decodeWithoutPadding(token));
|
||||
Optional<ClientContact> contact = directory.get(decodeToken(token));
|
||||
|
||||
if (contact.isPresent()) return Response.ok().entity(contact.get()).build();
|
||||
else return Response.status(404).build();
|
||||
@@ -100,7 +100,7 @@ public class DirectoryController {
|
||||
List<byte[]> tokens = new LinkedList<>();
|
||||
|
||||
for (String encodedContact : contacts.getContacts()) {
|
||||
tokens.add(Base64.decodeWithoutPadding(encodedContact));
|
||||
tokens.add(decodeToken(encodedContact));
|
||||
}
|
||||
|
||||
List<ClientContact> intersection = directory.get(tokens);
|
||||
@@ -110,4 +110,8 @@ public class DirectoryController {
|
||||
throw new WebApplicationException(Response.status(400).build());
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] decodeToken(String encoded) throws IOException {
|
||||
return Base64.decodeWithoutPadding(encoded.replace('-', '+').replace('_', '/'));
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Base64;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.ws.rs.Consumes;
|
||||
@@ -94,8 +95,8 @@ public class MessageController {
|
||||
try {
|
||||
boolean isSyncMessage = source.getNumber().equals(destinationName);
|
||||
|
||||
if (messages.getRelay() == null) sendLocalMessage(source, destinationName, messages, isSyncMessage);
|
||||
else sendRelayMessage(source, destinationName, messages, isSyncMessage);
|
||||
if (Util.isEmpty(messages.getRelay())) sendLocalMessage(source, destinationName, messages, isSyncMessage);
|
||||
else sendRelayMessage(source, destinationName, messages, isSyncMessage);
|
||||
|
||||
return new SendMessageResponse(!isSyncMessage && source.getActiveDeviceCount() > 1);
|
||||
} catch (NoSuchUserException e) {
|
||||
|
||||
@@ -15,6 +15,7 @@ import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
@@ -37,6 +38,7 @@ public class ProvisioningController {
|
||||
@Path("/{destination}")
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public void sendProvisioningMessage(@Auth Account source,
|
||||
@PathParam("destination") String destinationName,
|
||||
@Valid ProvisioningMessage message)
|
||||
|
||||
@@ -49,8 +49,11 @@ public class ReceiptController {
|
||||
throws IOException
|
||||
{
|
||||
try {
|
||||
if (relay.isPresent()) sendRelayedReceipt(source, destination, messageId, relay.get());
|
||||
else sendDirectReceipt(source, destination, messageId);
|
||||
if (relay.isPresent() && !relay.get().isEmpty()) {
|
||||
sendRelayedReceipt(source, destination, messageId, relay.get());
|
||||
} else {
|
||||
sendDirectReceipt(source, destination, messageId);
|
||||
}
|
||||
} catch (NoSuchUserException | NotPushRegisteredException e) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
} catch (TransientPushFailureException e) {
|
||||
|
||||
@@ -20,20 +20,23 @@ public class GcmMessage {
|
||||
private int deviceId;
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
private String message;
|
||||
|
||||
@JsonProperty
|
||||
private boolean receipt;
|
||||
|
||||
@JsonProperty
|
||||
private boolean notification;
|
||||
|
||||
public GcmMessage() {}
|
||||
|
||||
public GcmMessage(String gcmId, String number, int deviceId, String message, boolean receipt) {
|
||||
this.gcmId = gcmId;
|
||||
this.number = number;
|
||||
this.deviceId = deviceId;
|
||||
this.message = message;
|
||||
this.receipt = receipt;
|
||||
public GcmMessage(String gcmId, String number, int deviceId, String message, boolean receipt, boolean notification) {
|
||||
this.gcmId = gcmId;
|
||||
this.number = number;
|
||||
this.deviceId = deviceId;
|
||||
this.message = message;
|
||||
this.receipt = receipt;
|
||||
this.notification = notification;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -25,9 +25,15 @@ public class GcmRegistrationId {
|
||||
@NotEmpty
|
||||
private String gcmRegistrationId;
|
||||
|
||||
@JsonProperty
|
||||
private boolean webSocketChannel;
|
||||
|
||||
public String getGcmRegistrationId() {
|
||||
return gcmRegistrationId;
|
||||
}
|
||||
|
||||
public boolean isWebSocketChannel() {
|
||||
return webSocketChannel;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +57,13 @@ public class PushSender {
|
||||
|
||||
private void sendGcmMessage(Account account, Device device, OutgoingMessageSignal message)
|
||||
throws TransientPushFailureException, NotPushRegisteredException
|
||||
{
|
||||
if (device.getFetchesMessages()) sendNotificationGcmMessage(account, device, message);
|
||||
else sendPayloadGcmMessage(account, device, message);
|
||||
}
|
||||
|
||||
private void sendPayloadGcmMessage(Account account, Device device, OutgoingMessageSignal message)
|
||||
throws TransientPushFailureException, NotPushRegisteredException
|
||||
{
|
||||
try {
|
||||
String number = account.getNumber();
|
||||
@@ -65,7 +72,7 @@ public class PushSender {
|
||||
boolean isReceipt = message.getType() == OutgoingMessageSignal.Type.RECEIPT_VALUE;
|
||||
EncryptedOutgoingMessage encryptedMessage = new EncryptedOutgoingMessage(message, device.getSignalingKey());
|
||||
GcmMessage gcmMessage = new GcmMessage(registrationId, number, (int) deviceId,
|
||||
encryptedMessage.toEncodedString(), isReceipt);
|
||||
encryptedMessage.toEncodedString(), isReceipt, false);
|
||||
|
||||
pushServiceClient.send(gcmMessage);
|
||||
} catch (CryptoEncodingException e) {
|
||||
@@ -73,10 +80,23 @@ public class PushSender {
|
||||
}
|
||||
}
|
||||
|
||||
private void sendNotificationGcmMessage(Account account, Device device, OutgoingMessageSignal message)
|
||||
throws TransientPushFailureException
|
||||
{
|
||||
DeliveryStatus deliveryStatus = webSocketSender.sendMessage(account, device, message, WebsocketSender.Type.GCM);
|
||||
|
||||
if (!deliveryStatus.isDelivered()) {
|
||||
GcmMessage gcmMessage = new GcmMessage(device.getGcmId(), account.getNumber(),
|
||||
(int)device.getId(), "", false, true);
|
||||
|
||||
pushServiceClient.send(gcmMessage);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendApnMessage(Account account, Device device, OutgoingMessageSignal outgoingMessage)
|
||||
throws TransientPushFailureException
|
||||
{
|
||||
DeliveryStatus deliveryStatus = webSocketSender.sendMessage(account, device, outgoingMessage, true);
|
||||
DeliveryStatus deliveryStatus = webSocketSender.sendMessage(account, device, outgoingMessage, WebsocketSender.Type.APN);
|
||||
|
||||
if (!deliveryStatus.isDelivered() && outgoingMessage.getType() != OutgoingMessageSignal.Type.RECEIPT_VALUE) {
|
||||
ApnMessage apnMessage = new ApnMessage(device.getApnId(), account.getNumber(), (int)device.getId(),
|
||||
@@ -87,6 +107,6 @@ public class PushSender {
|
||||
|
||||
private void sendWebSocketMessage(Account account, Device device, OutgoingMessageSignal outgoingMessage)
|
||||
{
|
||||
webSocketSender.sendMessage(account, device, outgoingMessage, false);
|
||||
webSocketSender.sendMessage(account, device, outgoingMessage, WebsocketSender.Type.WEB);
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,12 @@ import static org.whispersystems.textsecuregcm.storage.PubSubProtos.PubSubMessag
|
||||
|
||||
public class WebsocketSender {
|
||||
|
||||
public static enum Type {
|
||||
APN,
|
||||
GCM,
|
||||
WEB
|
||||
}
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(WebsocketSender.class);
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
@@ -46,6 +52,9 @@ public class WebsocketSender {
|
||||
private final Meter apnOnlineMeter = metricRegistry.meter(name(getClass(), "apn_online" ));
|
||||
private final Meter apnOfflineMeter = metricRegistry.meter(name(getClass(), "apn_offline"));
|
||||
|
||||
private final Meter gcmOnlineMeter = metricRegistry.meter(name(getClass(), "gcm_online" ));
|
||||
private final Meter gcmOfflineMeter = metricRegistry.meter(name(getClass(), "gcm_offline"));
|
||||
|
||||
private final Meter provisioningOnlineMeter = metricRegistry.meter(name(getClass(), "provisioning_online" ));
|
||||
private final Meter provisioningOfflineMeter = metricRegistry.meter(name(getClass(), "provisioning_offline"));
|
||||
|
||||
@@ -57,7 +66,7 @@ public class WebsocketSender {
|
||||
this.pubSubManager = pubSubManager;
|
||||
}
|
||||
|
||||
public DeliveryStatus sendMessage(Account account, Device device, OutgoingMessageSignal message, boolean apn) {
|
||||
public DeliveryStatus sendMessage(Account account, Device device, OutgoingMessageSignal message, Type channel) {
|
||||
WebsocketAddress address = new WebsocketAddress(account.getNumber(), device.getId());
|
||||
PubSubMessage pubSubMessage = PubSubMessage.newBuilder()
|
||||
.setType(PubSubMessage.Type.DELIVER)
|
||||
@@ -65,13 +74,15 @@ public class WebsocketSender {
|
||||
.build();
|
||||
|
||||
if (pubSubManager.publish(address, pubSubMessage)) {
|
||||
if (apn) apnOnlineMeter.mark();
|
||||
else websocketOnlineMeter.mark();
|
||||
if (channel == Type.APN) apnOnlineMeter.mark();
|
||||
else if (channel == Type.GCM) gcmOnlineMeter.mark();
|
||||
else websocketOnlineMeter.mark();
|
||||
|
||||
return new DeliveryStatus(true, 0);
|
||||
} else {
|
||||
if (apn) apnOfflineMeter.mark();
|
||||
else websocketOfflineMeter.mark();
|
||||
if (channel == Type.APN) apnOfflineMeter.mark();
|
||||
else if (channel == Type.GCM) gcmOfflineMeter.mark();
|
||||
else websocketOfflineMeter.mark();
|
||||
|
||||
int queueDepth = messagesManager.insert(account.getNumber(), device.getId(), message);
|
||||
pubSubManager.publish(address, PubSubMessage.newBuilder()
|
||||
|
||||
@@ -53,7 +53,7 @@ public class SmsSender {
|
||||
try {
|
||||
twilioSender.deliverSmsVerification(destination, verificationCode);
|
||||
} catch (TwilioRestException e) {
|
||||
logger.info("Twilio SMS Fallback", e);
|
||||
logger.info("Twilio SMS Failed: " + e.getErrorMessage());
|
||||
if (nexmoSender.isPresent()) {
|
||||
nexmoSender.get().deliverSmsVerification(destination, verificationCode);
|
||||
}
|
||||
@@ -70,7 +70,7 @@ public class SmsSender {
|
||||
try {
|
||||
twilioSender.deliverVoxVerification(destination, verificationCode);
|
||||
} catch (TwilioRestException e) {
|
||||
logger.info("Twilio Vox Fallback", e);
|
||||
logger.info("Twilio Vox Failed: " + e.getErrorMessage());
|
||||
if (nexmoSender.isPresent()) {
|
||||
nexmoSender.get().deliverVoxVerification(destination, verificationCode);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ public class TwilioSmsSender {
|
||||
|
||||
public static final String SAY_TWIML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
|
||||
"<Response>\n" +
|
||||
" <Say voice=\"woman\" language=\"en\">" + SmsSender.VOX_VERIFICATION_TEXT + "%s</Say>\n" +
|
||||
" <Say voice=\"woman\" language=\"en\" loop=\"3\">" + SmsSender.VOX_VERIFICATION_TEXT + "%s.</Say>\n" +
|
||||
"</Response>";
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
|
||||
@@ -43,7 +43,7 @@ public abstract class Messages {
|
||||
@Bind("destination_device") long destinationDevice);
|
||||
|
||||
@Mapper(MessageMapper.class)
|
||||
@SqlQuery("SELECT * FROM messages WHERE " + DESTINATION + " = :destination AND " + DESTINATION_DEVICE + " = :destination_device")
|
||||
@SqlQuery("SELECT * FROM messages WHERE " + DESTINATION + " = :destination AND " + DESTINATION_DEVICE + " = :destination_device ORDER BY " + TIMESTAMP + " ASC")
|
||||
abstract List<Pair<Long, OutgoingMessageSignal>> load(@Bind("destination") String destination,
|
||||
@Bind("destination_device") long destinationDevice);
|
||||
|
||||
|
||||
@@ -3,11 +3,14 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.websocket.DeadLetterHandler;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebsocketAddress;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.storage.PubSubProtos.PubSubMessage;
|
||||
import redis.clients.jedis.BinaryJedisPubSub;
|
||||
@@ -21,12 +24,16 @@ public class PubSubManager {
|
||||
private final Logger logger = LoggerFactory.getLogger(PubSubManager.class);
|
||||
private final SubscriptionListener baseListener = new SubscriptionListener();
|
||||
private final Map<String, PubSubListener> listeners = new HashMap<>();
|
||||
private final Executor threaded = Executors.newCachedThreadPool();
|
||||
|
||||
private final JedisPool jedisPool;
|
||||
private final DeadLetterHandler deadLetterHandler;
|
||||
|
||||
private final JedisPool jedisPool;
|
||||
private boolean subscribed = false;
|
||||
|
||||
public PubSubManager(JedisPool jedisPool) {
|
||||
this.jedisPool = jedisPool;
|
||||
public PubSubManager(JedisPool jedisPool, DeadLetterHandler deadLetterHandler) {
|
||||
this.jedisPool = jedisPool;
|
||||
this.deadLetterHandler = deadLetterHandler;
|
||||
initializePubSubWorker();
|
||||
waitForSubscription();
|
||||
}
|
||||
@@ -57,6 +64,12 @@ public class PubSubManager {
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void resubscribeAll() {
|
||||
for (String serializedAddress : listeners.keySet()) {
|
||||
baseListener.subscribe(serializedAddress.getBytes());
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void waitForSubscription() {
|
||||
try {
|
||||
while (!subscribed) {
|
||||
@@ -72,9 +85,13 @@ public class PubSubManager {
|
||||
@Override
|
||||
public void run() {
|
||||
for (;;) {
|
||||
logger.info("Starting Redis PubSub Subscriber...");
|
||||
|
||||
try (Jedis jedis = jedisPool.getResource()) {
|
||||
jedis.subscribe(baseListener, KEEPALIVE_CHANNEL);
|
||||
logger.warn("**** Unsubscribed from holding channel!!! ******");
|
||||
} catch (Throwable t) {
|
||||
logger.warn("*** SUBSCRIBER CONNECTION CLOSED", t);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,8 +106,8 @@ public class PubSubManager {
|
||||
publish(KEEPALIVE_CHANNEL, PubSubMessage.newBuilder()
|
||||
.setType(PubSubMessage.Type.KEEPALIVE)
|
||||
.build());
|
||||
} catch (InterruptedException e) {
|
||||
throw new AssertionError(e);
|
||||
} catch (Throwable e) {
|
||||
logger.warn("KEEPALIVE PUBLISH EXCEPTION: ", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,20 +117,30 @@ public class PubSubManager {
|
||||
private class SubscriptionListener extends BinaryJedisPubSub {
|
||||
|
||||
@Override
|
||||
public void onMessage(byte[] channel, byte[] message) {
|
||||
try {
|
||||
PubSubListener listener;
|
||||
|
||||
synchronized (PubSubManager.this) {
|
||||
listener = listeners.get(new String(channel));
|
||||
}
|
||||
|
||||
if (listener != null) {
|
||||
listener.onPubSubMessage(PubSubMessage.parseFrom(message));
|
||||
}
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
logger.warn("Error parsing PubSub protobuf", e);
|
||||
public void onMessage(final byte[] channel, final byte[] message) {
|
||||
if (Arrays.equals(KEEPALIVE_CHANNEL, channel)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final PubSubListener listener;
|
||||
|
||||
synchronized (PubSubManager.this) {
|
||||
listener = listeners.get(new String(channel));
|
||||
}
|
||||
|
||||
threaded.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
PubSubMessage receivedMessage = PubSubMessage.parseFrom(message);
|
||||
|
||||
if (listener != null) listener.onPubSubMessage(receivedMessage);
|
||||
else deadLetterHandler.handle(channel, receivedMessage);
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
logger.warn("Error parsing PubSub protobuf", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -128,6 +155,13 @@ public class PubSubManager {
|
||||
subscribed = true;
|
||||
PubSubManager.this.notifyAll();
|
||||
}
|
||||
|
||||
threaded.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
resubscribeAll();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -158,6 +158,10 @@ public final class PubSubProtos {
|
||||
* <code>KEEPALIVE = 3;</code>
|
||||
*/
|
||||
KEEPALIVE(3, 3),
|
||||
/**
|
||||
* <code>CLOSE = 4;</code>
|
||||
*/
|
||||
CLOSE(4, 4),
|
||||
;
|
||||
|
||||
/**
|
||||
@@ -176,6 +180,10 @@ public final class PubSubProtos {
|
||||
* <code>KEEPALIVE = 3;</code>
|
||||
*/
|
||||
public static final int KEEPALIVE_VALUE = 3;
|
||||
/**
|
||||
* <code>CLOSE = 4;</code>
|
||||
*/
|
||||
public static final int CLOSE_VALUE = 4;
|
||||
|
||||
|
||||
public final int getNumber() { return value; }
|
||||
@@ -186,6 +194,7 @@ public final class PubSubProtos {
|
||||
case 1: return QUERY_DB;
|
||||
case 2: return DELIVER;
|
||||
case 3: return KEEPALIVE;
|
||||
case 4: return CLOSE;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
@@ -611,12 +620,13 @@ public final class PubSubProtos {
|
||||
descriptor;
|
||||
static {
|
||||
java.lang.String[] descriptorData = {
|
||||
"\n\023PubSubMessage.proto\022\ntextsecure\"\215\001\n\rPu" +
|
||||
"\n\023PubSubMessage.proto\022\ntextsecure\"\230\001\n\rPu" +
|
||||
"bSubMessage\022,\n\004type\030\001 \001(\0162\036.textsecure.P" +
|
||||
"ubSubMessage.Type\022\017\n\007content\030\002 \001(\014\"=\n\004Ty" +
|
||||
"ubSubMessage.Type\022\017\n\007content\030\002 \001(\014\"H\n\004Ty" +
|
||||
"pe\022\013\n\007UNKNOWN\020\000\022\014\n\010QUERY_DB\020\001\022\013\n\007DELIVER" +
|
||||
"\020\002\022\r\n\tKEEPALIVE\020\003B8\n(org.whispersystems." +
|
||||
"textsecuregcm.storageB\014PubSubProtos"
|
||||
"\020\002\022\r\n\tKEEPALIVE\020\003\022\t\n\005CLOSE\020\004B8\n(org.whis" +
|
||||
"persystems.textsecuregcm.storageB\014PubSub" +
|
||||
"Protos"
|
||||
};
|
||||
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
|
||||
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
|
||||
|
||||
+21
-21
@@ -1,6 +1,5 @@
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import com.google.common.base.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.push.PushSender;
|
||||
@@ -9,6 +8,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
import org.whispersystems.websocket.setup.WebSocketConnectListener;
|
||||
@@ -33,30 +33,15 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
|
||||
@Override
|
||||
public void onWebSocketConnect(WebSocketSessionContext context) {
|
||||
Optional<Account> account = context.getAuthenticated(Account.class);
|
||||
Account account = context.getAuthenticated(Account.class).get();
|
||||
Device device = account.getAuthenticatedDevice().get();
|
||||
|
||||
if (!account.isPresent()) {
|
||||
logger.debug("WS Connection with no authentication...");
|
||||
context.getClient().close(4001, "Authentication failed");
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<Device> device = account.get().getAuthenticatedDevice();
|
||||
|
||||
if (!device.isPresent()) {
|
||||
logger.debug("WS Connection with no authenticated device...");
|
||||
context.getClient().close(4001, "Device authentication failed");
|
||||
return;
|
||||
}
|
||||
|
||||
if (device.get().getLastSeen() != Util.todayInMillis()) {
|
||||
device.get().setLastSeen(Util.todayInMillis());
|
||||
accountsManager.update(account.get());
|
||||
}
|
||||
updateLastSeen(account, device);
|
||||
closeExistingDeviceConnection(account, device);
|
||||
|
||||
final WebSocketConnection connection = new WebSocketConnection(accountsManager, pushSender,
|
||||
messagesManager, pubSubManager,
|
||||
account.get(), device.get(),
|
||||
account, device,
|
||||
context.getClient());
|
||||
|
||||
connection.onConnected();
|
||||
@@ -68,4 +53,19 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void updateLastSeen(Account account, Device device) {
|
||||
if (device.getLastSeen() != Util.todayInMillis()) {
|
||||
device.setLastSeen(Util.todayInMillis());
|
||||
accountsManager.update(account);
|
||||
}
|
||||
}
|
||||
|
||||
private void closeExistingDeviceConnection(Account account, Device device) {
|
||||
pubSubManager.publish(new WebsocketAddress(account.getNumber(), device.getId()),
|
||||
PubSubProtos.PubSubMessage.newBuilder()
|
||||
.setType(PubSubProtos.PubSubMessage.Type.CLOSE)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.OutgoingMessageSignal;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
|
||||
|
||||
public class DeadLetterHandler {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(DeadLetterHandler.class);
|
||||
|
||||
private final MessagesManager messagesManager;
|
||||
|
||||
public DeadLetterHandler(MessagesManager messagesManager) {
|
||||
this.messagesManager = messagesManager;
|
||||
}
|
||||
|
||||
public void handle(byte[] channel, PubSubProtos.PubSubMessage pubSubMessage) {
|
||||
try {
|
||||
WebsocketAddress address = new WebsocketAddress(new String(channel));
|
||||
|
||||
logger.warn("Handling dead letter to: " + address);
|
||||
|
||||
switch (pubSubMessage.getType().getNumber()) {
|
||||
case PubSubProtos.PubSubMessage.Type.DELIVER_VALUE:
|
||||
OutgoingMessageSignal message = OutgoingMessageSignal.parseFrom(pubSubMessage.getContent());
|
||||
messagesManager.insert(address.getNumber(), address.getDeviceId(), message);
|
||||
break;
|
||||
}
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
logger.warn("Bad pubsub message", e);
|
||||
} catch (InvalidWebsocketAddressException e) {
|
||||
logger.warn("Invalid websocket address", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+3
-1
@@ -34,7 +34,9 @@ public class WebSocketAccountAuthenticator implements WebSocketAuthenticator<Acc
|
||||
return Optional.absent();
|
||||
}
|
||||
|
||||
BasicCredentials credentials = new BasicCredentials(usernames[0], passwords[0]);
|
||||
BasicCredentials credentials = new BasicCredentials(usernames[0].replace(" ", "+"),
|
||||
passwords[0].replace(" ", "+"));
|
||||
|
||||
return accountAuthenticator.authenticate(credentials);
|
||||
} catch (io.dropwizard.auth.AuthenticationException e) {
|
||||
throw new AuthenticationException(e);
|
||||
|
||||
@@ -80,6 +80,10 @@ public class WebSocketConnection implements PubSubListener {
|
||||
case PubSubMessage.Type.DELIVER_VALUE:
|
||||
sendMessage(OutgoingMessageSignal.parseFrom(pubSubMessage.getContent()), Optional.<Long>absent());
|
||||
break;
|
||||
case PubSubMessage.Type.CLOSE_VALUE:
|
||||
client.close(1000, "OK");
|
||||
pubSubManager.unsubscribe(address, this);
|
||||
break;
|
||||
default:
|
||||
logger.warn("Unknown pubsub message: " + pubSubMessage.getType().getNumber());
|
||||
}
|
||||
@@ -137,7 +141,7 @@ public class WebSocketConnection implements PubSubListener {
|
||||
Optional<Account> source = accountsManager.get(message.getSource());
|
||||
|
||||
if (!source.isPresent()) {
|
||||
logger.warn("Source account disappeared? (%s)", message.getSource());
|
||||
logger.warn(String.format("Source account disappeared? (%s)", message.getSource()));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,29 @@ public class WebsocketAddress {
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public WebsocketAddress(String serialized) throws InvalidWebsocketAddressException {
|
||||
try {
|
||||
String[] parts = serialized.split(":", 2);
|
||||
|
||||
if (parts.length != 2) {
|
||||
throw new InvalidWebsocketAddressException("Bad address: " + serialized);
|
||||
}
|
||||
|
||||
this.number = parts[0];
|
||||
this.deviceId = Long.parseLong(parts[1]);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new InvalidWebsocketAddressException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public String getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public long getDeviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public String serialize() {
|
||||
return number + ":" + deviceId;
|
||||
}
|
||||
|
||||
+36
-9
@@ -5,6 +5,7 @@ import com.google.common.util.concurrent.SettableFuture;
|
||||
import com.google.protobuf.ByteString;
|
||||
import org.eclipse.jetty.websocket.api.UpgradeRequest;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
@@ -14,6 +15,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PubSubProtos;
|
||||
import org.whispersystems.textsecuregcm.util.Base64;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.websocket.AuthenticatedConnectListener;
|
||||
@@ -23,6 +25,7 @@ import org.whispersystems.textsecuregcm.websocket.WebsocketAddress;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
import org.whispersystems.websocket.setup.WebSocketConnectListener;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
@@ -32,6 +35,8 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -57,6 +62,27 @@ public class WebSocketConnectionTest {
|
||||
// private static final Session session = mock(Session.class );
|
||||
private static final PushSender pushSender = mock(PushSender.class);
|
||||
|
||||
@Test
|
||||
public void testCloseExisting() throws Exception {
|
||||
MessagesManager storedMessages = mock(MessagesManager.class );
|
||||
WebSocketConnectListener connectListener = new AuthenticatedConnectListener(accountsManager, pushSender, storedMessages, pubSubManager);
|
||||
WebSocketSessionContext sessionContext = mock(WebSocketSessionContext.class);
|
||||
Account account = mock(Account.class );
|
||||
Device device = mock(Device.class );
|
||||
|
||||
when(sessionContext.getAuthenticated(Account.class)).thenReturn(Optional.of(account));
|
||||
when(account.getAuthenticatedDevice()).thenReturn(Optional.of(device));
|
||||
when(account.getNumber()).thenReturn("+14157777777");
|
||||
when(device.getId()).thenReturn(1L);
|
||||
|
||||
connectListener.onWebSocketConnect(sessionContext);
|
||||
|
||||
ArgumentCaptor<PubSubProtos.PubSubMessage> message = ArgumentCaptor.forClass(PubSubProtos.PubSubMessage.class);
|
||||
|
||||
verify(pubSubManager).publish(eq(new WebsocketAddress("+14157777777", 1L)), message.capture());
|
||||
assertEquals(message.getValue().getType().getNumber(), PubSubProtos.PubSubMessage.Type.CLOSE_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCredentials() throws Exception {
|
||||
MessagesManager storedMessages = mock(MessagesManager.class);
|
||||
@@ -101,15 +127,16 @@ public class WebSocketConnectionTest {
|
||||
}});
|
||||
|
||||
account = webSocketAuthenticator.authenticate(upgradeRequest);
|
||||
when(sessionContext.getAuthenticated(Account.class)).thenReturn(account);
|
||||
|
||||
WebSocketClient client = mock(WebSocketClient.class);
|
||||
when(sessionContext.getClient()).thenReturn(client);
|
||||
|
||||
connectListener.onWebSocketConnect(sessionContext);
|
||||
|
||||
verify(sessionContext, times(1)).addListener(any(WebSocketSessionContext.WebSocketEventListener.class));
|
||||
verify(client).close(eq(4001), anyString());
|
||||
assertFalse(account.isPresent());
|
||||
// when(sessionContext.getAuthenticated(Account.class)).thenReturn(account);
|
||||
//
|
||||
// WebSocketClient client = mock(WebSocketClient.class);
|
||||
// when(sessionContext.getClient()).thenReturn(client);
|
||||
//
|
||||
// connectListener.onWebSocketConnect(sessionContext);
|
||||
//
|
||||
// verify(sessionContext, times(1)).addListener(any(WebSocketSessionContext.WebSocketEventListener.class));
|
||||
// verify(client).close(eq(4001), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user