aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java/org/pacien/tincapp/commands/Executor.kt
diff options
context:
space:
mode:
Diffstat (limited to 'app/src/main/java/org/pacien/tincapp/commands/Executor.kt')
-rw-r--r--app/src/main/java/org/pacien/tincapp/commands/Executor.kt34
1 files changed, 1 insertions, 33 deletions
diff --git a/app/src/main/java/org/pacien/tincapp/commands/Executor.kt b/app/src/main/java/org/pacien/tincapp/commands/Executor.kt
index 29e011f..0a8a774 100644
--- a/app/src/main/java/org/pacien/tincapp/commands/Executor.kt
+++ b/app/src/main/java/org/pacien/tincapp/commands/Executor.kt
@@ -1,6 +1,6 @@
1/* 1/*
2 * Tinc App, an Android binding and user interface for the tinc mesh VPN daemon 2 * Tinc App, an Android binding and user interface for the tinc mesh VPN daemon
3 * Copyright (C) 2017-2018 Pacien TRAN-GIRARD 3 * Copyright (C) 2017-2020 Pacien TRAN-GIRARD
4 * 4 *
5 * This program is free software: you can redistribute it and/or modify 5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by 6 * it under the terms of the GNU General Public License as published by
@@ -30,42 +30,10 @@ import java.io.InputStreamReader
30 * @author pacien 30 * @author pacien
31 */ 31 */
32internal object Executor { 32internal object Executor {
33 private const val FAILED = -1
34 private const val SUCCESS = 0
35
36 class CommandExecutionException(msg: String) : Exception(msg) 33 class CommandExecutionException(msg: String) : Exception(msg)
37 34
38 init {
39 System.loadLibrary("exec")
40 }
41
42 /**
43 * @return FAILED (-1) on error, forked child PID otherwise
44 */
45 private external fun forkExec(args: Array<String>): Int
46
47 /**
48 * @return FAILED (-1) on error, the exit status of the process otherwise
49 */
50 private external fun wait(pid: Int): Int
51
52 private fun read(stream: InputStream) = BufferedReader(InputStreamReader(stream)).readLines() 35 private fun read(stream: InputStream) = BufferedReader(InputStreamReader(stream)).readLines()
53 36
54 fun forkExec(cmd: Command): CompletableFuture<Unit> {
55 val pid = forkExec(cmd.asArray()).also {
56 if (it == FAILED) throw CommandExecutionException("Could not fork child process.")
57 }
58
59 return runAsyncTask {
60 val exitCode = wait(pid)
61 when (exitCode) {
62 SUCCESS -> Unit
63 FAILED -> throw CommandExecutionException("Process terminated abnormally.")
64 else -> throw CommandExecutionException("Non-zero exit status code ($exitCode).")
65 }
66 }
67 }
68
69 fun run(cmd: Command): Process = try { 37 fun run(cmd: Command): Process = try {
70 ProcessBuilder(cmd.asList()).start() 38 ProcessBuilder(cmd.asList()).start()
71 } catch (e: IOException) { 39 } catch (e: IOException) {