forked from guardianproject/lildebi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NativeHelper.java
415 lines (381 loc) · 16.4 KB
/
NativeHelper.java
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package info.guardianproject.lildebi;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Scanner;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.res.AssetManager;
import android.os.Environment;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.util.Log;
public class NativeHelper {
public static int STARTING_INSTALL = 12345;
public static File app_bin;
public static File app_log;
public static File install_log;
public static File app_profiles;
public static File publicFiles;
public static File sh;
public static File install_conf;
public static File versionFile;
public static String sdcard;
public static String image_path;
public static String default_image_path;
public static String mnt;
public static String postStartScript;
public static String preStopScript;
public static boolean isInstallRunning = false;
public static boolean installInInternalStorage;
public static boolean limitTo4GB;
public static File file;
public static String profileName;
public static String generatedFileName;
public static List<String> myProfileList = new ArrayList<String>();
public static List<String> myGenProfileList = new ArrayList<String>();
public static String DIRECTORY_PATH = "/data/data/info.guardianproject.lildebi/app_profiles";
public static String Name;
public static String path_to_install_script;
public static String path_to_pre_start_script;
public static String path_to_post_start_script;
public static String gui_support;
public static String fileName;
public static void setup(Context context) {
app_bin = context.getDir("bin", Context.MODE_PRIVATE).getAbsoluteFile();
app_log = context.getDir("log", Context.MODE_PRIVATE).getAbsoluteFile();
app_profiles = context.getDir("profiles", Context.MODE_PRIVATE).getAbsoluteFile();
install_log = new File(app_log, "install.log");
// this is the same as android-8's getExternalFilesDir() but works on android-1
publicFiles = new File(Environment.getExternalStorageDirectory(),
"Android/data/" + context.getPackageName() + "/files/");
publicFiles.mkdirs();
sh = new File(app_bin, "sh");
install_conf = new File(app_bin, "install.conf");
versionFile = new File(app_bin, "VERSION");
// they did a real hackjob with the "external storage" aka SD Card path
// in 4.3/4.4, so we have to add this kludge to make sure we have a path
// we can work with.
File dir = new File(System.getenv("EXTERNAL_STORAGE"));
if (!dir.exists())
dir = Environment.getExternalStorageDirectory();
try {
sdcard = dir.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
sdcard = dir.getAbsolutePath();
}
mnt = "/data/debian";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
default_image_path = sdcard + "/debian.img";
String prefName = context.getString(R.string.pref_image_path_key);
image_path = prefs.getString(prefName, default_image_path);
prefName = context.getString(R.string.pref_limit_to_4gb_key);
limitTo4GB = prefs.getBoolean(prefName, true);
postStartScript = prefs.getString(
context.getString(R.string.pref_post_start_key),
context.getString(R.string.default_post_start_script));
preStopScript = prefs.getString(
context.getString(R.string.pref_pre_stop_key),
context.getString(R.string.default_pre_stop_script));
boolean detectedInternalInstall = false;
/* attempt to auto-detect existing internal install */
if (!isStarted()
&& new File(NativeHelper.mnt + "/etc").exists()
&& !new File(image_path).exists())
detectedInternalInstall = true;
prefName = context.getString(R.string.pref_install_on_internal_storage_key);
installInInternalStorage = prefs.getBoolean(prefName, detectedInternalInstall);
if (installInInternalStorage)
NativeHelper.image_path = NativeHelper.mnt;
try {
File folder = new File("/sdcard/profiles/");
File[] listOfFiles = folder.listFiles();
int countOfProfiles=0;
for (File file : listOfFiles) {
if (file.isFile()) {
profileName = file.getName();
myProfileList.add(profileName);
Log.d("all profiles ", profileName);
countOfProfiles++;
}
}
String n[] = new String[countOfProfiles];
for (int i = 0; i < countOfProfiles; i++) {
n[i] = myProfileList.get(i) ;
Log.d("[i] value", n[i]);
Log.d("No. of profiles", ""+countOfProfiles);
Log.d("printing data for ", ""+n[i]);
file = new File("/sdcard/profiles/" + n[i]);
Log.d("file name", file.getPath());
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(file);
prop.load(input);
Name = prop.getProperty("Name");
path_to_install_script = prop.getProperty("path_to_install_script");
path_to_install_script = prop.getProperty("path_to_pre_start_script");
path_to_post_start_script = prop.getProperty("path_to_post_start_script");
gui_support = prop.getProperty("gui_support");
Log.d("Name", Name);
File root = new File(DIRECTORY_PATH);
fileName = Name + ".sh";
File gpxfile = new File(root, fileName);
FileWriter writer;
writer = new FileWriter(gpxfile);
StringBuilder s = new StringBuilder();
s.append("export TERM=linux \n");
s.append("export HOME=/root \n");
s.append("export PATH=$app_bin:/usr/bin:/usr/sbin:/bin:/sbin:$PATH \n");
s.append("apt-get install "+ Name);
writer.append(s);
writer.flush();
writer.close();
Log.d("Name", Name);
Log.d("path_to_install_script", path_to_install_script);
Log.d("path_to_install_script", path_to_install_script);
Log.d("path_to_post_start_script", path_to_post_start_script);
Log.d("gui_support", gui_support);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}catch (Exception e) {
e.printStackTrace();
}
try {
File folder = new File(DIRECTORY_PATH);
File[] listOfFiles = folder.listFiles();
int countOfGeneratedFiles =0;
for (File file : listOfFiles) {
if (file.isFile()) {
generatedFileName = file.getName();
myGenProfileList.add(generatedFileName);
chmod(0755, new File(app_profiles, generatedFileName));
Log.d("all generated files ", generatedFileName);
countOfGeneratedFiles++;
}
}
Log.d("countOfGeneratedFiles", ""+countOfGeneratedFiles);
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean isStarted() {
if (installInInternalStorage) {
/*
* When installed on the internal storage, the "started" state means
* that the bind mounts are setup, so this checks for a directory
* that will only exist if the bind mount is setup.
*/
return new File(NativeHelper.mnt + "/system/bin").exists();
} else {
/*
* When installed on a loopback image file, then the "started" state
* means that the loopback image file is mounted, so this checks for
* a file that can only be in the loopback image.
*/
return new File(NativeHelper.mnt + "/etc").exists();
}
}
public static boolean isInstalled() {
if (installInInternalStorage)
return (new File(NativeHelper.mnt + "/etc").exists());
else
return (new File(NativeHelper.image_path).exists());
}
public static String getArgs() {
return new String(" " + app_bin.getAbsolutePath() + " " + sdcard + " "
+ image_path + " " + mnt + " ");
}
private static int readVersionFile() {
if (! versionFile.exists()) return 0;
Scanner in;
int versionCode = 0;
try {
in = new Scanner(versionFile);
versionCode = Integer.parseInt(in.next());
in.close();
} catch (Exception e) {
LilDebiAction.log.append("Can't read app version file: " + e.getLocalizedMessage() + "\n");
}
return versionCode;
}
private static void writeVersionFile(Context context) {
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
FileOutputStream fos = new FileOutputStream(versionFile);
OutputStreamWriter out = new OutputStreamWriter(fos);
out.write(String.valueOf(pInfo.versionCode) + "\n");
out.close();
fos.close();
} catch (Exception e) {
LilDebiAction.log.append("Can't write app version file: " + e.getLocalizedMessage() + "\n");
}
}
private static int getCurrentVersionCode(Context context) {
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pInfo.versionCode;
} catch (Exception e) {
LilDebiAction.log.append("Can't get app version: " + e.getLocalizedMessage() + "\n");
return 0;
}
}
public static String getLANG() {
Locale locale = Locale.getDefault();
if (locale == null)
return "";
else
return locale.getLanguage() + "_" + locale.getCountry();
}
private static void renameOldAppBin() {
String moveTo = app_bin.toString();
Calendar now = Calendar.getInstance();
int version = readVersionFile();
if (version == 0) {
moveTo += ".old";
} else {
moveTo += ".build" + String.valueOf(version);
}
moveTo += "." + String.valueOf(now.getTimeInMillis());
LilDebiAction.log.append("Moving '" + app_bin + "' to '" + moveTo + "'\n");
app_bin.renameTo(new File(moveTo));
app_bin.mkdir(); // Android normally creates this at onCreate()
}
public static void unzipDebiFiles(Context context) {
try {
AssetManager am = context.getAssets();
final String[] assetList = am.list("");
for (String asset : assetList) {
if (asset.equals("images")
|| asset.equals("sounds")
|| asset.equals("webkit")
|| asset.equals("databases") // Motorola
|| asset.equals("kioskmode")) // Samsung
continue;
int BUFFER = 2048;
final File file = new File(app_bin, asset);
InputStream tmp;
try {
tmp = am.open(asset);
} catch (FileNotFoundException e) {
e.printStackTrace();
continue;
}
final InputStream assetIS = tmp;
if (file.exists()) {
file.delete();
LilDebiAction.log.append("DebiHelper.unzipDebiFiles() deleting " + file.getAbsolutePath() + "\n");
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
int count;
byte[] data = new byte[BUFFER];
while ((count = assetIS.read(data, 0, BUFFER)) != -1) {
// System.out.write(x);
dest.write(data, 0, count);
}
dest.flush();
dest.close();
assetIS.close();
}
} catch (IOException e) {
Log.e(LilDebi.TAG, "Can't unzip", e);
}
chmod(0644, new File(app_bin, "cdebootstrap.tar"));
chmod(0644, new File(app_bin, "lildebi-common"));
chmod(0755, new File(app_bin, "create-debian-setup.sh"));
chmod(0755, new File(app_bin, "complete-debian-setup.sh"));
chmod(0755, new File(app_bin, "unmounted-install-tweaks.sh"));
chmod(0755, new File(app_bin, "delete-all-debian-setup.sh"));
chmod(0755, new File(app_bin, "configure-downloaded-image.sh"));
chmod(0755, new File(app_bin, "start-debian.sh"));
chmod(0755, new File(app_bin, "stop-debian.sh"));
chmod(0755, new File(app_bin, "shell"));
chmod(0755, new File(app_bin, "test.sh"));
chmod(0755, new File(app_bin, "gpgv"));
chmod(0755, new File(app_bin, "busybox"));
writeVersionFile(context);
}
public static void installOrUpgradeAppBin(Context context) {
if (versionFile.exists()) {
if (getCurrentVersionCode(context) > readVersionFile()) {
LilDebiAction.log.append("Upgrading '" + app_bin + "'\n");
// upgrade, rename current app_bin, then unpack
renameOldAppBin();
unzipDebiFiles(context);
} else {
Log.i(LilDebi.TAG, "Not upgrading '" + app_bin + "'\n");
}
} else {
File[] list = app_bin.listFiles();
if (list == null || list.length > 0) {
LilDebiAction.log.append("Old, unversioned app_bin dir, upgrading.\n");
renameOldAppBin();
} else {
LilDebiAction.log.append("Fresh app_bin install.\n");
}
unzipDebiFiles(context);
}
}
public static void chmod(int mode, File path) {
try {
if (!path.exists())
throw new IOException();
Class<?> fileUtils = Class.forName("android.os.FileUtils");
Method setPermissions = fileUtils.getMethod("setPermissions", String.class,
int.class, int.class, int.class);
int a = (Integer) setPermissions.invoke(null, path.getAbsolutePath(), mode,
-1, -1);
if (a != 0) {
Log.i(LilDebi.TAG, "ERROR: android.os.FileUtils.setPermissions() returned " + a
+ " for '" + path + "'");
}
} catch (ClassNotFoundException e) {
Log.i(LilDebi.TAG, "android.os.FileUtils.setPermissions() failed - ClassNotFoundException.");
} catch (IllegalAccessException e) {
Log.i(LilDebi.TAG, "android.os.FileUtils.setPermissions() failed - IllegalAccessException.");
} catch (InvocationTargetException e) {
Log.i(LilDebi.TAG, "android.os.FileUtils.setPermissions() failed - InvocationTargetException.");
} catch (NoSuchMethodException e) {
Log.i(LilDebi.TAG, "android.os.FileUtils.setPermissions() failed - NoSuchMethodException.");
} catch (IOException e) {
Log.e(LilDebi.TAG, path + " does not exist!");
e.printStackTrace();
}
}
public static boolean isSdCardPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static long getInstallPathFreeMegaBytes() {
String path;
StatFs stat;
long freeSizeInBytes;
File parent = new File(image_path).getParentFile();
try {
path = parent.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
path = parent.getAbsolutePath();
}
stat = new StatFs(path);
freeSizeInBytes = stat.getAvailableBlocks() * (long) stat.getBlockSize();
return freeSizeInBytes / 1024 / 1024;
}
}