summaryrefslogtreecommitdiff
path: root/tools/gator/daemon/Setup.cpp
blob: 0d39572e9b12cdc3c100b47e534745db8556b3fb (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
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
/**
 * Copyright (C) ARM Limited 2014-2015. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

#include "Setup.h"

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <unistd.h>

#include "Config.h"
#include "DynBuf.h"
#include "Logging.h"
#include "SessionData.h"

#define GATOR_MSG "gator: "
#define GATOR_ERROR "gator: error: "
#define GATOR_CONFIRM "gator: confirm: "

bool getLinuxVersion(int version[3]) {
	// Check the kernel version
	struct utsname utsname;
	if (uname(&utsname) != 0) {
		logg.logMessage("uname failed");
		return false;
	}

	version[0] = 0;
	version[1] = 0;
	version[2] = 0;

	int part = 0;
	char *ch = utsname.release;
	while (*ch >= '0' && *ch <= '9' && part < 3) {
		version[part] = 10*version[part] + *ch - '0';

		++ch;
		if (*ch == '.') {
			++part;
			++ch;
		}
	}

	return true;
}

static int pgrep_gator(DynBuf *const printb) {
	DynBuf b;

	DIR *proc = opendir("/proc");
	if (proc == NULL) {
		logg.logError(GATOR_ERROR "opendir failed");
		handleException();
	}

	int self = getpid();

	struct dirent *dirent;
	while ((dirent = readdir(proc)) != NULL) {
		char *endptr;
		const int pid = strtol(dirent->d_name, &endptr, 10);
		if (*endptr != '\0' || (pid == self)) {
			// Ignore proc items that are not integers like ., cpuinfo, etc...
			continue;
		}

		if (!printb->printf("/proc/%i/stat", pid)) {
			logg.logError(GATOR_ERROR "DynBuf::printf failed");
			handleException();
		}

		if (!b.read(printb->getBuf())) {
			// This is not a fatal error - the thread just doesn't exist any more
			continue;
		}

		char *comm = strchr(b.getBuf(), '(');
		if (comm == NULL) {
			logg.logError(GATOR_ERROR "parsing stat comm begin failed");
			handleException();
		}
		++comm;
		char *const str = strrchr(comm, ')');
		if (str == NULL) {
			logg.logError(GATOR_ERROR "parsing stat comm end failed");
			handleException();
		}
		*str = '\0';

		if (strncmp(comm, "gator", 5) != 0) {
			continue;
		}

		char state;
		const int count = sscanf(str + 2, " %c ", &state);
		if (count != 1) {
			logg.logError(GATOR_ERROR "parsing stat state failed");
			handleException();
		}

		if (state == 'Z') {
			// This gator is a zombie, ignore
			continue;
		}

		// Assume there is only one gator process
		return pid;
	}

	closedir(proc);

	return -1;
}

static bool confirm(const char *const message) {
	char buf[1<<10];

	printf(GATOR_CONFIRM "%s\n", message);
	while (fgets(buf, sizeof(buf), stdin) != NULL) {
		if (strcmp(buf, "y\n") == 0) {
			return true;
		}
		if (strcmp(buf, "n\n") == 0) {
			return false;
		}
		// Ignore unrecognized input
	}

	return false;
}

void update(const char *const gatorPath) {
	printf(GATOR_MSG "starting\n");

	int version[3];
	if (!getLinuxVersion(version)) {
		logg.logError(GATOR_ERROR "getLinuxVersion failed");
		handleException();
	}

	if (KERNEL_VERSION(version[0], version[1], version[2]) < KERNEL_VERSION(3, 4, 0)) {
		logg.logError(GATOR_ERROR "Streamline can't automatically setup gator as this kernel version is not supported. Please upgrade the kernel on your device.");
		handleException();
	}

	if (geteuid() != 0) {
		char buf[1<<10];
		snprintf(buf, sizeof(buf),
			 "which sudo &&"
			 "("
			   "sudo -n %1$s -u ||"
			   "("
			     "echo " GATOR_MSG "trying sudo;"
			     // Streamline will provide the password
			     "sudo %1$s -u"
			   ")"
			 ") || ("
			   "echo " GATOR_MSG "trying su;"
		/*
		 * Different versions of su handle additional -c command line options differently and expect the
		 * arguments in different ways. Try both ways wrapped in a shell.
		 *
		 * Then invoke another shell after su as it avoids odd failures on some Android systems
		 */
			   "su -c \"sh -c '%1$s -u'\" ||"
			   "su -c sh -c '%1$s -u'"
			 ")",
			 gatorPath);
		execlp("sh", "sh", "-c", buf, NULL);
		// Streamline will provide the password if needed

		logg.logError(GATOR_ERROR "Streamline was unable to sudo to root on your device. Please double check passwords, ensure sudo or su work with this user or try a different username.");
		handleException();
	}
	printf(GATOR_MSG "now root\n");

	if (access("/sys/module/gator", F_OK) == 0) {
		if (!confirm("Streamline has detected that the gator kernel module is loaded on your device. Click yes to switch to user space gator, click no to abort the install.")) {
			printf("gator: cancel\n");
			exit(-1);
		}
	}

	// setenforce 0 not needed for userspace gator

	// Kill existing gator
	DynBuf printb;
	int gator_main = pgrep_gator(&printb);
	if (gator_main > 0) {
		if (kill(gator_main, SIGTERM) != 0) {
			logg.logError(GATOR_ERROR "kill SIGTERM failed");
			handleException();
		}
		if (!printb.printf("/proc/%i/exe", gator_main)) {
			logg.logError(GATOR_ERROR "DynBuf::printf failed");
			handleException();
		}
		for (int i = 0; ; ++i) {
			// /proc/<pid>/exe exists but will not be accessible for zombies
			if (access(printb.getBuf(), F_OK) != 0) {
				break;
			}
			if (i == 5) {
				if (kill(gator_main, SIGKILL) != 0) {
					logg.logError(GATOR_ERROR "kill SIGKILL failed");
					handleException();
				}
			} else if (i >= 10) {
				logg.logError(GATOR_ERROR "unable to kill running gator");
				handleException();
			}
			sleep(1);
		}
	}
	printf(GATOR_MSG "no gatord running\n");

	umount("/dev/gator");
	syscall(__NR_delete_module, "gator", O_NONBLOCK);

	if (access("/sys/module/gator", F_OK) == 0) {
		logg.logError(GATOR_ERROR "Unable to unload gator.ko, the gator module may be built into the kernel or gator.ko cannot be unloaded. Rebooting the device may resolve the issue.");
		handleException();
	}

	rename("gatord", "gatord.old");
	rename("gator.ko", "gator.ko.old");

	// Rename gatord.YYYYMMDDHHMMSSMMMM to gatord
	char *newGatorPath = strdup(gatorPath);
	char *dot = strrchr(newGatorPath, '.');
	if (dot != NULL) {
		*dot = '\0';
		if (rename(gatorPath, newGatorPath) != 0) {
			logg.logError(GATOR_ERROR "rename failed");
			handleException();
		}
	}

	char buf[128];
	int pipefd[2];
	if (pipe_cloexec(pipefd) != 0) {
		logg.logError(GATOR_ERROR "pipe failed");
		handleException();
	}

	// Fork and start gatord (redirect stdin, stdout and stderr so shell can close)
	int child = fork();
	if (child < 0) {
		logg.logError(GATOR_ERROR "fork failed");
		handleException();
	} else if (child == 0) {
		int inFd;
		int outFd;
		int errFd;
		int result = -1;

		buf[0] = '\0';
		close(pipefd[0]);

		inFd = open("/dev/null", O_RDONLY | O_CLOEXEC);
		if (inFd < 0) {
			snprintf(buf, sizeof(buf), GATOR_ERROR "open of /dev/null failed");
			goto fail_exit;
		}
		outFd = open("gatord.out", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
		if (outFd < 0) {
			snprintf(buf, sizeof(buf), GATOR_ERROR "open of gatord.out failed");
			goto fail_exit;
		}
		errFd = open("gatord.err", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
		if (errFd < 0) {
			snprintf(buf, sizeof(buf), GATOR_ERROR "open of gatord.err failed");
			goto fail_exit;
		}
		if (dup2(inFd, STDIN_FILENO) < 0) {
			snprintf(buf, sizeof(buf), GATOR_ERROR "dup2 for stdin failed");
			goto fail_exit;
		}
		fflush(stdout);
		if (dup2(outFd, STDOUT_FILENO) < 0) {
			snprintf(buf, sizeof(buf), GATOR_ERROR "dup2 for stdout failed");
			goto fail_exit;
		}
		fflush(stderr);
		if (dup2(errFd, STDERR_FILENO) < 0) {
			snprintf(buf, sizeof(buf), GATOR_ERROR "dup2 for stderr failed");
			goto fail_exit;
		}

		snprintf(buf, sizeof(buf), GATOR_MSG "done");
		result = 0;

	fail_exit:
		if (buf[0] != '\0') {
			const ssize_t bytes = write(pipefd[1], buf, sizeof(buf));
			// Can't do anything if this fails
			(void)bytes;
		}
		close(pipefd[1]);

		if (result == 0) {
			// Continue to execute gator normally
			return;
		}
		exit(-1);
	}

	close(pipefd[1]);
	const ssize_t bytes = read(pipefd[0], buf, sizeof(buf));
	if (bytes > 0) {
		printf("%s\n", buf);
	}
	close(pipefd[0]);

	// Exit so parent shell can move on
	exit(0);
}