Welcome to mirror list, hosted at ThFree Co, Russian Federation.

JumbleUDP.java « net « jumble « morlunk « com « java « main « src - gitlab.com/quite/humla.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ab59c82b0e6f0b6482473f431ee7562459d58ab0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/*
 * Copyright (C) 2014 Andrew Comminos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.morlunk.jumble.net;

import android.util.Log;

import com.morlunk.jumble.Constants;

import java.io.IOException;
import java.net.ConnectException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.ShortBufferException;

/**
 * Class to maintain and receive packets from the UDP connection to a Mumble server.
 */
public class JumbleUDP extends JumbleNetworkThread {
    private static final int BUFFER_SIZE = 2048;
    private final CryptState mCryptState;

    private DatagramSocket mUDPSocket;
    private UDPConnectionListener mListener;
    private String mHost;
    private int mPort;
    private InetAddress mResolvedHost;
    private boolean mConnected;

    /**
     * Sets up a new UDP connection context.
     * @param cryptState Cryptographic state provider.
     */
    public JumbleUDP(CryptState cryptState) {
        mCryptState = cryptState;
    }

    public void setUDPConnectionListener(UDPConnectionListener listener) {
        mListener = listener;
    }

    public void connect(String host, int port) throws ConnectException {
        if(mConnected) throw new ConnectException("UDP connection already established!");
        mHost = host;
        mPort = port;
        startThreads();
    }

    public boolean isRunning() {
        return mConnected;
    }

    @Override
    public void run() {
        try {
            mResolvedHost = InetAddress.getByName(mHost);
            mUDPSocket = new DatagramSocket();
        } catch (final IOException e) {
            if(mListener != null) {
                executeOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        mListener.onUDPConnectionError(e);
                    }
                });
            }
            return;
        }

        mUDPSocket.connect(mResolvedHost, mPort);
        final DatagramPacket packet = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);

        Log.d(Constants.TAG, "[UDP] Created socket");
        mConnected = true;

        while(mConnected) {
            try {
                mUDPSocket.receive(packet);
                final byte[] data = packet.getData();
                final int length = packet.getLength();

                if (!mCryptState.isValid()) {
                    Log.d(Constants.TAG, "[UDP] CryptState invalid, discarding packet");
                    continue;
                }
                if (length < 5) {
                    Log.d(Constants.TAG, "[UDP] Packet too short, discarding");
                    continue;
                }

                try {
                    final byte[] buffer = mCryptState.decrypt(data, length);

                    if (mListener != null) {
                        if (buffer != null) {
                            executeOnReceiveThread(new Runnable() {
                                @Override
                                public void run() {
                                    mListener.onUDPDataReceived(buffer);
                                }
                            });
                        } else if(mCryptState.getLastGoodElapsed() > 5000000 &&
                                mCryptState.getLastRequestElapsed() > 5000000) {
                            mCryptState.resetLastRequestTime();
                            executeOnMainThread(new Runnable() {
                                @Override
                                public void run() {
                                    mListener.resyncCryptState();
                                }
                            });
                            Log.d(Constants.TAG, "[UDP] Packet failed to decrypt, discarding and " +
                                                 "requesting crypt state resync");
                        } else {
                            Log.d(Constants.TAG, "[UDP] Packet failed to decrypt, discarding");
                        }
                    }
                } catch (BadPaddingException|IllegalBlockSizeException|ShortBufferException e) {
                    Log.d(Constants.TAG, "[UDP] Discarding packet", e);
                }
            } catch (final IOException e) {
                // If a UDP exception is thrown while connected, notify the listener to fall back to TCP.
                if(mConnected && mListener != null) {
                    executeOnMainThread(new Runnable() {
                        @Override
                        public void run() {
                            mListener.onUDPConnectionError(e);
                        }
                    });
                }
                break;
            }
        }
        disconnect(); // Make sure we close the socket if disconnect wasn't controlled
    }

    public void sendMessage(final byte[] data, final int length) {
        if(!mCryptState.isValid() || !mConnected) return;
        executeOnSendThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!mCryptState.isValid() || !mConnected) return;
                    byte[] encryptedData = mCryptState.encrypt(data, length);
                    final DatagramPacket packet = new DatagramPacket(encryptedData, encryptedData.length);
                    packet.setAddress(mResolvedHost);
                    packet.setPort(mPort);
                    mUDPSocket.send(packet);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (ShortBufferException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void disconnect() {
        if(!mConnected) return;
        mConnected = false;
        executeOnSendThread(new Runnable() {
            @Override
            public void run() {
                mUDPSocket.disconnect();
                mUDPSocket.close();
            }
        });
        stopThreads();
    }

    /**
     * Note that all connection state related calls are made on the main thread.
     * onUDPDataReceived is always called on the UDP receive thread.
     */
    public interface UDPConnectionListener {
        public void onUDPDataReceived(byte[] data);
        public void onUDPConnectionError(Exception e);
        public void resyncCryptState();
    }
}