aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/services/AbstractConnectionManager.java
blob: 1c4c6ca19f2a2f74017d7307380ec51c0bc9b10c (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
package de.pixart.messenger.services;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.util.Pair;

import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.AEADBlockCipher;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.KeyParameter;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.atomic.AtomicLong;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import de.pixart.messenger.Config;
import de.pixart.messenger.R;
import de.pixart.messenger.entities.DownloadableFile;

public class AbstractConnectionManager {
    protected XmppConnectionService mXmppConnectionService;
    private static final int UI_REFRESH_THRESHOLD = 250;
    private static final AtomicLong LAST_UI_UPDATE_CALL = new AtomicLong(0);

    public AbstractConnectionManager(XmppConnectionService service) {
        this.mXmppConnectionService = service;
    }

    public XmppConnectionService getXmppConnectionService() {
        return this.mXmppConnectionService;
    }

    public long getAutoAcceptFileSize() {
        long defaultValue_wifi = this.getXmppConnectionService().getResources().getInteger(R.integer.auto_accept_filesize_wifi);
        long defaultValue_mobile = this.getXmppConnectionService().getResources().getInteger(R.integer.auto_accept_filesize_mobile);
        long defaultValue_roaming = this.getXmppConnectionService().getResources().getInteger(R.integer.auto_accept_filesize_roaming);

        String config = "0";
        if (mXmppConnectionService.isWIFI()) {
            config = this.mXmppConnectionService.getPreferences().getString(
                    "auto_accept_file_size_wifi", String.valueOf(defaultValue_wifi));
        } else if (mXmppConnectionService.isMobile()) {
            config = this.mXmppConnectionService.getPreferences().getString(
                    "auto_accept_file_size_mobile", String.valueOf(defaultValue_mobile));
        } else if (mXmppConnectionService.isMobileRoaming()) {
            config = this.mXmppConnectionService.getPreferences().getString(
                    "auto_accept_file_size_roaming", String.valueOf(defaultValue_roaming));
        }
        try {
            return Long.parseLong(config);
        } catch (NumberFormatException e) {
            return defaultValue_mobile;
        }
    }

    public boolean hasStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return mXmppConnectionService.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        } else {
            return true;
        }
    }

    public static Pair<InputStream, Integer> createInputStream(DownloadableFile file, boolean gcm) throws FileNotFoundException {
        FileInputStream is;
        int size;
        is = new FileInputStream(file);
        size = (int) file.getSize();
        if (file.getKey() == null) {
            return new Pair<>(is, size);
        }
        try {
            if (gcm) {
                AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
                cipher.init(true, new AEADParameters(new KeyParameter(file.getKey()), 128, file.getIv()));
                InputStream cis = new org.bouncycastle.crypto.io.CipherInputStream(is, cipher);
                return new Pair<>(cis, cipher.getOutputSize(size));
            } else {
                IvParameterSpec ips = new IvParameterSpec(file.getIv());
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(file.getKey(), "AES"), ips);
                Log.d(Config.LOGTAG, "opening encrypted input stream");
                return new Pair<>(new CipherInputStream(is, cipher), (size / 16 + 1) * 16);
            }
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }

    public static OutputStream createAppendedOutputStream(DownloadableFile file) {
        return createOutputStream(file, false, true);
    }

    public static OutputStream createOutputStream(DownloadableFile file, boolean gcm) {
        return createOutputStream(file, gcm, false);
    }

    private static OutputStream createOutputStream(DownloadableFile file, boolean gcm, boolean append) {
        FileOutputStream os;
        try {
            os = new FileOutputStream(file, append);
            if (file.getKey() == null) {
                return os;
            }
        } catch (FileNotFoundException e) {
            return null;
        }
        try {
            if (gcm) {
                AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
                cipher.init(false, new AEADParameters(new KeyParameter(file.getKey()), 128, file.getIv()));
                return new org.bouncycastle.crypto.io.CipherOutputStream(os, cipher);
            } else {
                IvParameterSpec ips = new IvParameterSpec(file.getIv());
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(file.getKey(), "AES"), ips);
                Log.d(Config.LOGTAG, "opening encrypted output stream");
                return new CipherOutputStream(os, cipher);
            }
        } catch (InvalidKeyException e) {
            return null;
        } catch (NoSuchAlgorithmException e) {
            return null;
        } catch (NoSuchPaddingException e) {
            return null;
        } catch (InvalidAlgorithmParameterException e) {
            return null;
        }
    }

    public void updateConversationUi(boolean force) {
        synchronized (LAST_UI_UPDATE_CALL) {
            if (force || SystemClock.elapsedRealtime() - LAST_UI_UPDATE_CALL.get() >= UI_REFRESH_THRESHOLD) {
                LAST_UI_UPDATE_CALL.set(SystemClock.elapsedRealtime());
                mXmppConnectionService.updateConversationUi();
            }
        }
    }

    public PowerManager.WakeLock createWakeLock(String name) {
        PowerManager powerManager = (PowerManager) mXmppConnectionService.getSystemService(Context.POWER_SERVICE);
        return powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, name);
    }
}