summaryrefslogtreecommitdiffhomepage
path: root/app/src/main/java/com/wireguard/android/util/RootShell.java
blob: 2dc02b56c50e6a50055f5ee06a436249064015f0 (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
/*
 * Copyright © 2017-2018 WireGuard LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

package com.wireguard.android.util;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;

import com.wireguard.android.BuildConfig;
import com.wireguard.android.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.UUID;

/**
 * Helper class for running commands as root.
 */

public class RootShell {
    private static final String SU = "su";
    private static final String TAG = "WireGuard/" + RootShell.class.getSimpleName();

    private final Context context;
    private final String deviceNotRootedMessage;
    private final File localBinaryDir;
    private final File localTemporaryDir;
    private final Object lock = new Object();
    private final String preamble;
    @Nullable private Process process;
    @Nullable private BufferedReader stderr;
    @Nullable private OutputStreamWriter stdin;
    @Nullable private BufferedReader stdout;

    public RootShell(final Context context) {
        deviceNotRootedMessage = context.getString(R.string.error_root);
        final File cacheDir = context.getCacheDir();
        localBinaryDir = new File(cacheDir, "bin");
        localTemporaryDir = new File(cacheDir, "tmp");
        preamble = String.format("export CALLING_PACKAGE=%s PATH=\"%s:$PATH\" TMPDIR='%s'; id -u\n",
                BuildConfig.APPLICATION_ID, localBinaryDir, localTemporaryDir);
        this.context = context;
    }

    private static boolean isExecutableInPath(final String name) {
        final String path = System.getenv("PATH");
        if (path == null)
            return false;
        for (final String dir : path.split(":"))
            if (new File(dir, name).canExecute())
                return true;
        return false;
    }

    private boolean isRunning() {
        synchronized (lock) {
            try {
                // Throws an exception if the process hasn't finished yet.
                if (process != null)
                    process.exitValue();
                return false;
            } catch (final IllegalThreadStateException ignored) {
                // The existing process is still running.
                return true;
            }
        }
    }

    /**
     * Run a command in a root shell.
     *
     * @param output  Lines read from stdout are appended to this list. Pass null if the
     *                output from the shell is not important.
     * @param command Command to run as root.
     * @return The exit value of the command.
     */
    public int run(@Nullable final Collection<String> output, final String command)
            throws IOException, NoRootException {
        synchronized (lock) {
            /* Start inside synchronized block to prevent a concurrent call to stop(). */
            start();
            final String marker = UUID.randomUUID().toString();
            final String script = "echo " + marker + "; echo " + marker + " >&2; (" + command +
                    "); ret=$?; echo " + marker + " $ret; echo " + marker + " $ret >&2\n";
            Log.v(TAG, "executing: " + command);
            stdin.write(script);
            stdin.flush();
            String line;
            int errnoStdout = Integer.MIN_VALUE;
            int errnoStderr = Integer.MAX_VALUE;
            int markersSeen = 0;
            while ((line = stdout.readLine()) != null) {
                if (line.startsWith(marker)) {
                    ++markersSeen;
                    if (line.length() > marker.length() + 1) {
                        errnoStdout = Integer.valueOf(line.substring(marker.length() + 1));
                        break;
                    }
                } else if (markersSeen > 0) {
                    if (output != null)
                        output.add(line);
                    Log.v(TAG, "stdout: " + line);
                }
            }
            while ((line = stderr.readLine()) != null) {
                if (line.startsWith(marker)) {
                    ++markersSeen;
                    if (line.length() > marker.length() + 1) {
                        errnoStderr = Integer.valueOf(line.substring(marker.length() + 1));
                        break;
                    }
                } else if (markersSeen > 2) {
                    Log.v(TAG, "stderr: " + line);
                }
            }
            if (markersSeen != 4)
                throw new IOException(context.getString(R.string.shell_marker_count_error, markersSeen));
            if (errnoStdout != errnoStderr)
                throw new IOException(context.getString(R.string.shell_exit_status_read_error));
            Log.v(TAG, "exit: " + errnoStdout);
            return errnoStdout;
        }
    }

    public void start() throws IOException, NoRootException {
        if (!isExecutableInPath(SU))
            throw new NoRootException(deviceNotRootedMessage);
        synchronized (lock) {
            if (isRunning())
                return;
            if (!localBinaryDir.isDirectory() && !localBinaryDir.mkdirs())
                throw new FileNotFoundException(context.getString(R.string.create_bin_dir_error));
            if (!localTemporaryDir.isDirectory() && !localTemporaryDir.mkdirs())
                throw new FileNotFoundException(context.getString(R.string.create_temp_dir_error));
            try {
                final ProcessBuilder builder = new ProcessBuilder().command(SU);
                builder.environment().put("LC_ALL", "C");
                try {
                    process = builder.start();
                } catch (final IOException e) {
                    // A failure at this stage means the device isn't rooted.
                    throw new NoRootException(deviceNotRootedMessage, e);
                }
                stdin = new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8);
                stdout = new BufferedReader(new InputStreamReader(process.getInputStream(),
                        StandardCharsets.UTF_8));
                stderr = new BufferedReader(new InputStreamReader(process.getErrorStream(),
                        StandardCharsets.UTF_8));
                stdin.write(preamble);
                stdin.flush();
                // Check that the shell started successfully.
                final String uid = stdout.readLine();
                if (!"0".equals(uid)) {
                    Log.w(TAG, "Root check did not return correct UID: " + uid);
                    throw new NoRootException(deviceNotRootedMessage);
                }
                if (!isRunning()) {
                    String line;
                    while ((line = stderr.readLine()) != null) {
                        Log.w(TAG, "Root check returned an error: " + line);
                        if (line.contains("Permission denied"))
                            throw new NoRootException(deviceNotRootedMessage);
                    }
                    throw new IOException(context.getString(R.string.shell_start_error, process.exitValue()));
                }
            } catch (final IOException | NoRootException e) {
                stop();
                throw e;
            }
        }
    }

    public void stop() {
        synchronized (lock) {
            if (process != null) {
                process.destroy();
                process = null;
            }
        }
    }

    public static class NoRootException extends Exception {
        public NoRootException(final String message, final Throwable cause) {
            super(message, cause);
        }

        public NoRootException(final String message) {
            super(message);
        }
    }
}