Search in sources :

Example 1 with Authenticator

use of org.javacord.api.util.auth.Authenticator in project Javacord by BtoBastian.

the class ProxyAuthenticator method systemDefaultAuthentication.

/**
 * Generates a {@code Basic} auth header with credentials from the system default authenticator.
 *
 * @param route    The route to which a request is done that needs to be authenticated.
 * @param request  The originating request that led to the authentication attempt.
 * @param response The response that demands authentication.
 * @return The {@code Basic} auth header.
 */
private Map<String, List<String>> systemDefaultAuthentication(Route route, Request request, Response response) {
    InetSocketAddress proxyAddress = (InetSocketAddress) route.getProxy().address();
    String host = proxyAddress.getHostString();
    InetAddress addr = proxyAddress.getAddress();
    int port = proxyAddress.getPort();
    URL url = route.getUrl();
    String protocol = url.getProtocol();
    return response.getChallenges("basic").filter(challenge -> challenge.getRealm().isPresent()).filter(challenge -> {
        String charset = challenge.getAuthParams().get("charset");
        return charset == null || charset.equalsIgnoreCase("UTF-8");
    }).map(challenge -> {
        String realm = challenge.getRealm().orElseThrow(AssertionError::new);
        PasswordAuthentication passwordAuthentication = java.net.Authenticator.requestPasswordAuthentication(host, addr, port, protocol, realm, challenge.getScheme(), url, java.net.Authenticator.RequestorType.PROXY);
        if (passwordAuthentication != null) {
            Charset charset = challenge.getAuthParams().containsKey("charset") ? StandardCharsets.UTF_8 : StandardCharsets.ISO_8859_1;
            return Credentials.basic(passwordAuthentication.getUserName(), String.valueOf(passwordAuthentication.getPassword()), charset);
        }
        return null;
    }).filter(Objects::nonNull).filter(credentials -> request.getHeaders("Proxy-Authorization").stream().noneMatch(credentials::equals)).findAny().map(credentials -> Collections.singletonMap("Proxy-Authorization", Arrays.asList(null, credentials))).orElse(null);
}
Also used : Arrays(java.util.Arrays) OkHttpResponseImpl(org.javacord.core.util.auth.OkHttpResponseImpl) Request(org.javacord.api.util.auth.Request) URL(java.net.URL) IOException(java.io.IOException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) Route(org.javacord.api.util.auth.Route) InetAddress(java.net.InetAddress) Objects(java.util.Objects) Authenticator(org.javacord.api.util.auth.Authenticator) List(java.util.List) PasswordAuthentication(java.net.PasswordAuthentication) Charset(java.nio.charset.Charset) Map(java.util.Map) Response(org.javacord.api.util.auth.Response) OkHttpRequestImpl(org.javacord.core.util.auth.OkHttpRequestImpl) Collections(java.util.Collections) OkHttpRouteImpl(org.javacord.core.util.auth.OkHttpRouteImpl) InetSocketAddress(java.net.InetSocketAddress) Objects(java.util.Objects) Charset(java.nio.charset.Charset) InetAddress(java.net.InetAddress) URL(java.net.URL) PasswordAuthentication(java.net.PasswordAuthentication)

Example 2 with Authenticator

use of org.javacord.api.util.auth.Authenticator in project Javacord by BtoBastian.

the class DiscordWebSocketAdapter method connect.

/**
 * Connects the websocket.
 */
private void connect() {
    try {
        WebSocketFactory factory = new WebSocketFactory();
        String webSocketUri = getGateway(api) + "?encoding=json&v=" + Javacord.DISCORD_GATEWAY_VERSION;
        Proxy proxy = api.getProxy().orElseGet(() -> {
            List<Proxy> proxies = api.getProxySelector().orElseGet(ProxySelector::getDefault).select(URI.create(webSocketUri.replace("wss://", "https://").replace("ws://", "http://")));
            return proxies.stream().filter(p -> p.type() == Proxy.Type.DIRECT).findAny().orElseGet(() -> proxies.stream().filter(p -> p.type() == Proxy.Type.HTTP).findAny().orElseGet(() -> proxies.get(0)));
        });
        switch(proxy.type()) {
            case DIRECT:
                // nothing to do
                break;
            case HTTP:
                SocketAddress proxyAddress = proxy.address();
                if (!(proxyAddress instanceof InetSocketAddress)) {
                    throw new WebSocketException(null, "HTTP proxies without an InetSocketAddress are not supported currently");
                }
                InetSocketAddress proxyInetAddress = ((InetSocketAddress) proxyAddress);
                String proxyHost = proxyInetAddress.getHostString();
                int proxyPort = proxyInetAddress.getPort();
                ProxySettings proxySettings = factory.getProxySettings();
                proxySettings.setHost(proxyHost).setPort(proxyPort);
                Optional<Authenticator> proxyAuthenticator = api.getProxyAuthenticator();
                URL webSocketUrl = URI.create(webSocketUri.replace("wss://", "https://").replace("ws://", "http://")).toURL();
                if (proxyAuthenticator.isPresent()) {
                    Map<String, List<String>> requestHeaders = proxyAuthenticator.get().authenticate(new NvWebSocketRouteImpl(webSocketUrl, proxy, proxyInetAddress), new Request() {
                    }, new NvWebSocketResponseImpl());
                    if (requestHeaders != null) {
                        requestHeaders.forEach((headerName, headerValues) -> {
                            if (headerValues == null) {
                                proxySettings.getHeaders().remove(headerName);
                                return;
                            }
                            if (headerValues.isEmpty()) {
                                return;
                            }
                            String firstHeaderValue = headerValues.get(0);
                            if (firstHeaderValue == null) {
                                proxySettings.getHeaders().remove(headerName);
                            } else {
                                proxySettings.addHeader(headerName, firstHeaderValue);
                            }
                            headerValues.stream().skip(1).forEach(headerValue -> proxySettings.addHeader(headerName, headerValue));
                        });
                    }
                } else {
                    PasswordAuthentication credentials = java.net.Authenticator.requestPasswordAuthentication(proxyHost, proxyInetAddress.getAddress(), proxyPort, webSocketUrl.getProtocol(), null, "Basic", webSocketUrl, java.net.Authenticator.RequestorType.PROXY);
                    if (credentials != null) {
                        proxySettings.setId(credentials.getUserName()).setPassword(String.valueOf(credentials.getPassword()));
                    }
                }
                break;
            default:
                throw new WebSocketException(null, "Proxies of type '" + proxy.type() + "' are not supported currently");
        }
        if (api.isTrustAllCertificates()) {
            factory.setSSLSocketFactory(new TrustAllTrustManager().createSslSocketFactory());
        }
        WebSocket websocket = factory.createSocket(webSocketUri);
        this.websocket.set(websocket);
        websocket.addHeader("Accept-Encoding", "gzip");
        websocket.addListener(this);
        websocket.addListener(new WebSocketLogger());
        if (sessionId == null) {
            api.getGatewayIdentifyRatelimiter().requestQuota();
        }
        websocket.connect();
    } catch (Throwable t) {
        logger.warn("An error occurred while connecting to websocket", t);
        if (reconnect) {
            reconnectingOrResumingLock.lock();
            try {
                reconnectAttempt.incrementAndGet();
            } finally {
                reconnectingOrResumingLock.unlock();
            }
            logger.info("Trying to reconnect/resume in {} seconds!", api.getReconnectDelay(reconnectAttempt.get()));
            // Reconnect after a (short?) delay depending on the amount of reconnect attempts
            api.getThreadPool().getScheduler().schedule(() -> {
                gatewayWriteLock.lock();
                try {
                    gateway = null;
                } finally {
                    gatewayWriteLock.unlock();
                }
                this.connect();
            }, api.getReconnectDelay(reconnectAttempt.get()), TimeUnit.SECONDS);
        }
    }
}
Also used : ResumeEventImpl(org.javacord.core.event.connection.ResumeEventImpl) UserUpdateHandler(org.javacord.core.util.handler.user.UserUpdateHandler) RestMethod(org.javacord.core.util.rest.RestMethod) TypingStartHandler(org.javacord.core.util.handler.user.TypingStartHandler) Proxy(java.net.Proxy) ThreadMembersUpdateHandler(org.javacord.core.util.handler.channel.thread.ThreadMembersUpdateHandler) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) NvWebSocketRouteImpl(org.javacord.core.util.auth.NvWebSocketRouteImpl) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ThreadListSyncHandler(org.javacord.core.util.handler.channel.thread.ThreadListSyncHandler) Activity(org.javacord.api.entity.activity.Activity) MessageUpdateHandler(org.javacord.core.util.handler.message.MessageUpdateHandler) BlockingQueue(java.util.concurrent.BlockingQueue) Logger(org.apache.logging.log4j.Logger) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) ChannelDeleteHandler(org.javacord.core.util.handler.channel.ChannelDeleteHandler) WebSocketFactory(com.neovisionaries.ws.client.WebSocketFactory) MessageCreateHandler(org.javacord.core.util.handler.message.MessageCreateHandler) NvWebSocketResponseImpl(org.javacord.core.util.auth.NvWebSocketResponseImpl) InviteDeleteHandler(org.javacord.core.util.handler.channel.invite.InviteDeleteHandler) ThreadUpdateHandler(org.javacord.core.util.handler.channel.thread.ThreadUpdateHandler) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ChannelPinsUpdateHandler(org.javacord.core.util.handler.channel.ChannelPinsUpdateHandler) ArrayList(java.util.ArrayList) GuildMembersChunkHandler(org.javacord.core.util.handler.guild.GuildMembersChunkHandler) PasswordAuthentication(java.net.PasswordAuthentication) VoiceServerUpdateHandler(org.javacord.core.util.handler.guild.VoiceServerUpdateHandler) MessageReactionAddHandler(org.javacord.core.util.handler.message.reaction.MessageReactionAddHandler) GuildMemberAddHandler(org.javacord.core.util.handler.guild.GuildMemberAddHandler) GuildRoleUpdateHandler(org.javacord.core.util.handler.guild.role.GuildRoleUpdateHandler) DiscordApiImpl(org.javacord.core.DiscordApiImpl) PresenceUpdateHandler(org.javacord.core.util.handler.user.PresenceUpdateHandler) LoggerUtil(org.javacord.core.util.logging.LoggerUtil) Lock(java.util.concurrent.locks.Lock) Intent(org.javacord.api.entity.intent.Intent) User(org.javacord.api.entity.user.User) GuildBanAddHandler(org.javacord.core.util.handler.guild.GuildBanAddHandler) WebhooksUpdateHandler(org.javacord.core.util.handler.channel.WebhooksUpdateHandler) GuildMemberRemoveHandler(org.javacord.core.util.handler.guild.GuildMemberRemoveHandler) SocketAddress(java.net.SocketAddress) GuildRoleDeleteHandler(org.javacord.core.util.handler.guild.role.GuildRoleDeleteHandler) URL(java.net.URL) ChannelCreateHandler(org.javacord.core.util.handler.channel.ChannelCreateHandler) PriorityBlockingQueue(java.util.concurrent.PriorityBlockingQueue) ProxySelector(java.net.ProxySelector) Authenticator(org.javacord.api.util.auth.Authenticator) GuildBanRemoveHandler(org.javacord.core.util.handler.guild.GuildBanRemoveHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GuildUpdateHandler(org.javacord.core.util.handler.guild.GuildUpdateHandler) RestRequest(org.javacord.core.util.rest.RestRequest) InteractionCreateHandler(org.javacord.core.util.handler.interaction.InteractionCreateHandler) URI(java.net.URI) GuildEmojisUpdateHandler(org.javacord.core.util.handler.guild.GuildEmojisUpdateHandler) ServerImpl(org.javacord.core.entity.server.ServerImpl) GuildDeleteHandler(org.javacord.core.util.handler.guild.GuildDeleteHandler) ThreadCreateHandler(org.javacord.core.util.handler.channel.thread.ThreadCreateHandler) GuildStickersUpdateHandler(org.javacord.core.util.handler.guild.GuildStickersUpdateHandler) AtomicMarkableReference(java.util.concurrent.atomic.AtomicMarkableReference) InetSocketAddress(java.net.InetSocketAddress) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ServerVoiceChannel(org.javacord.api.entity.channel.ServerVoiceChannel) MessageReactionRemoveAllHandler(org.javacord.core.util.handler.message.reaction.MessageReactionRemoveAllHandler) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) List(java.util.List) LostConnectionEvent(org.javacord.api.event.connection.LostConnectionEvent) WebSocketListener(com.neovisionaries.ws.client.WebSocketListener) WebSocketException(com.neovisionaries.ws.client.WebSocketException) Optional(java.util.Optional) ResumeEvent(org.javacord.api.event.connection.ResumeEvent) ResumedHandler(org.javacord.core.util.handler.ResumedHandler) ReadyHandler(org.javacord.core.util.handler.ReadyHandler) GuildMemberUpdateHandler(org.javacord.core.util.handler.guild.GuildMemberUpdateHandler) Nameable(org.javacord.api.entity.Nameable) VoiceStateUpdateHandler(org.javacord.core.util.handler.guild.VoiceStateUpdateHandler) Request(org.javacord.api.util.auth.Request) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) PresencesReplaceHandler(org.javacord.core.util.handler.user.PresencesReplaceHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) GuildCreateHandler(org.javacord.core.util.handler.guild.GuildCreateHandler) ProxySettings(com.neovisionaries.ws.client.ProxySettings) ReconnectEvent(org.javacord.api.event.connection.ReconnectEvent) DataFormatException(java.util.zip.DataFormatException) TrustAllTrustManager(org.javacord.core.util.http.TrustAllTrustManager) ThreadDeleteHandler(org.javacord.core.util.handler.channel.thread.ThreadDeleteHandler) ReconnectEventImpl(org.javacord.core.event.connection.ReconnectEventImpl) WeakHashMap(java.util.WeakHashMap) ExecutorService(java.util.concurrent.ExecutorService) MessageDeleteBulkHandler(org.javacord.core.util.handler.message.MessageDeleteBulkHandler) ReentrantLock(java.util.concurrent.locks.ReentrantLock) WebSocketFrame(com.neovisionaries.ws.client.WebSocketFrame) LostConnectionEventImpl(org.javacord.core.event.connection.LostConnectionEventImpl) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) WebSocketLogger(org.javacord.core.util.logging.WebSocketLogger) ChannelUpdateHandler(org.javacord.core.util.handler.channel.ChannelUpdateHandler) MessageReactionRemoveHandler(org.javacord.core.util.handler.message.reaction.MessageReactionRemoveHandler) WebSocketAdapter(com.neovisionaries.ws.client.WebSocketAdapter) Javacord(org.javacord.api.Javacord) TimeUnit(java.util.concurrent.TimeUnit) InviteCreateHandler(org.javacord.core.util.handler.channel.invite.InviteCreateHandler) Condition(java.util.concurrent.locks.Condition) MessageDeleteHandler(org.javacord.core.util.handler.message.MessageDeleteHandler) Server(org.javacord.api.entity.server.Server) WebSocket(com.neovisionaries.ws.client.WebSocket) GuildRoleCreateHandler(org.javacord.core.util.handler.guild.role.GuildRoleCreateHandler) Collections(java.util.Collections) WebSocketException(com.neovisionaries.ws.client.WebSocketException) NvWebSocketRouteImpl(org.javacord.core.util.auth.NvWebSocketRouteImpl) InetSocketAddress(java.net.InetSocketAddress) ProxySettings(com.neovisionaries.ws.client.ProxySettings) RestRequest(org.javacord.core.util.rest.RestRequest) Request(org.javacord.api.util.auth.Request) TrustAllTrustManager(org.javacord.core.util.http.TrustAllTrustManager) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) URL(java.net.URL) NvWebSocketResponseImpl(org.javacord.core.util.auth.NvWebSocketResponseImpl) WebSocket(com.neovisionaries.ws.client.WebSocket) Proxy(java.net.Proxy) WebSocketLogger(org.javacord.core.util.logging.WebSocketLogger) WebSocketFactory(com.neovisionaries.ws.client.WebSocketFactory) ArrayList(java.util.ArrayList) List(java.util.List) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Authenticator(org.javacord.api.util.auth.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Aggregations

InetSocketAddress (java.net.InetSocketAddress)2 PasswordAuthentication (java.net.PasswordAuthentication)2 URL (java.net.URL)2 Collections (java.util.Collections)2 List (java.util.List)2 Map (java.util.Map)2 Authenticator (org.javacord.api.util.auth.Authenticator)2 Request (org.javacord.api.util.auth.Request)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 JsonNodeFactory (com.fasterxml.jackson.databind.node.JsonNodeFactory)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 ProxySettings (com.neovisionaries.ws.client.ProxySettings)1 WebSocket (com.neovisionaries.ws.client.WebSocket)1 WebSocketAdapter (com.neovisionaries.ws.client.WebSocketAdapter)1 WebSocketException (com.neovisionaries.ws.client.WebSocketException)1 WebSocketFactory (com.neovisionaries.ws.client.WebSocketFactory)1 WebSocketFrame (com.neovisionaries.ws.client.WebSocketFrame)1 WebSocketListener (com.neovisionaries.ws.client.WebSocketListener)1 IOException (java.io.IOException)1