summaryrefslogtreecommitdiff
path: root/public/index.php
blob: f0bbf78650aa80eada85e0a2c2291afaf2d8aa89 (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
<?php

session_name("a3e0f0ee-9f5a-4be2-88cb-3b7ceb626d00");
session_start();

function get(string $id, string $name): ?string {
    $file = __DIR__ . "/../_runners/$id/results/" . $name;
    if (!is_file($file))
        return null;
    return file_get_contents($file);
}

function csrf_token(): string {
    return $_SESSION["csrf-token"] = base64_encode(random_bytes(30));
}

function getid(): string {
    return str_pad(bin2hex(random_bytes(16)), 32, "0", STR_PAD_LEFT);
}

function delTree($dir) { 
    foreach (scandir($dir) as $ent) {
        if ($ent === "." || $ent === "..")
            continue;
        $path = $dir . DIRECTORY_SEPARATOR . $ent;
        if (is_dir($path))
            delTree($path);
        else
            unlink($path);
    }
    return rmdir($dir);
}

function file_cachebuster(string $filename): string {
    return htmlentities(urlencode(md5(
        strval(filemtime($filename)) . 
        strval(filesize($filename))
    )));
}

$defaultCode = <<<java
public class Program {
    public static void main(String[] args) {
        // Your code here
        System.out.println("Hello, world!");
    }
}
java;

const CODE_MAXLENGTH = 16383;

$code = null;

if (!empty($_GET["c"])) {
    $compressedCode = @base64_decode($_GET["c"], true);
    if ($compressedCode !== false) {
        $uncompressedCode = @gzinflate($compressedCode, CODE_MAXLENGTH);
        if ($compressedCode !== false) {
            $code = &$uncompressedCode;
        }
    }
}

$result = null;

if (isset($_POST["code"]) && strlen($_POST["code"]) <= CODE_MAXLENGTH) {
    header("Content-Type: application/json");

    $code = $_POST["code"];
    $csrf = $_POST["csrf"] ?? null;
    
    if ($csrf === null || $csrf !== $_SESSION["csrf-token"]) {
        echo json_encode([
            "ok" => false,
            "message" => "CSRF token mismatch",
            "csrf" => csrf_token(),
        ]);
        exit;
    }

    if (($_POST["permalink"] ?? "") === "1") {
        echo json_encode([
            "ok" => true,
            "data" => base64_encode(gzdeflate($code, 9, ZLIB_ENCODING_RAW)),
        ]);
        exit;
    }

    $id = getid();

    $runnerDir = __DIR__ . "/../_runners/$id";
    $srcDir = $runnerDir . "/src";

    mkdir($srcDir, recursive: true);

    file_put_contents($srcDir . "/Program.java", $code);

    $isInDocker = getenv("IS_IN_DOCKER") === "1";

    if ($isInDocker)
        file_put_contents("php://stderr", "[debug] In Docker\n");
    chdir(__DIR__ . "/..");

    $stderrFile = sys_get_temp_dir() . "/tmp{$id}.2";
    exec(
        ($isInDocker ? "su-exec root " : "") .
        "./compile-and-run.sh '$id' Program 2>'$stderrFile'", $resultStr, $code);
    $resultStr = implode("\n", $resultStr);
    if (is_file($stderrFile)) {
        $stderrContents = file_get_contents($stderrFile);
        unlink($stderrFile);
        if (!empty($stderrContents)) {
            file_put_contents("php://stderr", "compile-and-run.sh failed: $stderrContents\n");
            if ($code != 0) {
                echo json_encode([
                    "ok" => false,
                    "message" => "Execution failed:\n$stderrContents",
                    "csrf" => csrf_token(),
                ]);
                delTree($runnerDir);
                exit;
            }
        }
    }
    chdir(__DIR__);
    file_put_contents("php://stderr", "result: $result\n");

    $csrf = csrf_token();


    $result = [
        "compile" => [
            "status" => get($id, "c.s"),
            "stdout" => get($id, "c.0"),
            "stderr" => get($id, "c.1"),
        ],
        "run" => [
            "status" => get($id, "r.s"),
            "stdout" => get($id, "r.0"),
            "stderr" => get($id, "r.1"),
        ],
        "runner" => $id,
        "ok" => true,
        "csrf" => $csrf,
    ];

    if ($isInDocker)
        exec("su-exec root rm -rf '$runnerDir'");
    else
        delTree($runnerDir);

    echo json_encode($result);
    exit;
}

$csrf = csrf_token();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Java</title>
    <link rel="stylesheet" href="dist/codemirror.css">
    <link rel="stylesheet" href="dist/eclipse.css">
    <link rel="stylesheet" href="site.css?_=<?= file_cachebuster(__DIR__ . "/site.css") ?>">
    <script src="dist/jquery-1.12.4.min.js"></script>
    <script src="dist/codemirror.js"></script>
    <script src="dist/clike.js"></script>
    <script src="site.js?_=<?= file_cachebuster(__DIR__ . "/site.js") ?>"></script>
</head>
<body>
    <div id="loader" style="display: none;">
        <div id="spinner"></div>
    </div>
    <h1>&#9749;&#65039; Java Compiler</h1>
    <p>Powered by Eclipse Temurin 23.</p>
    <p>
        <strong>Limitations:</strong>
        Compilation and execution time is limited to 30 seconds each.
        Your program won't have any network access and RAM is limited to 32 MiB.
        Source code size is limited to 16 KiB. Files will not be persisted between executions.
        Your program's main method needs to be contained inside a class named <code>Program</code>,
        as the code gets written to a file named <code>Program.java</code>.
    </p>
    <form method="POST">
        <input name="csrf" id="csrf-token" type="hidden" value="<?= htmlentities($csrf) ?>">
        <textarea maxlength="<?= CODE_MAXLENGTH ?>" id="editor" name="code" rows="20"><?= htmlentities($code ?? $defaultCode) ?></textarea>
        <div id="toolbar">
            <button type="submit">&#9654;&#65039;&nbsp;Compile &amp; run</button>
            <button type="button" id="dlCodeButton">&#128190;&#65039;&nbsp;Download code as file</button>
            <button type="button" id="permalink">&#128279;&#65039;&nbsp;Permalink</button>
        </div>
    </form>
    <div id="output" style="display: none;"></div>
    <div id="footer">
        &copy; <?= date("Y") ?> <a href="https://jkohl.link/" target="_blank">Jonas Kohl</a>.
        <a href="https://git.jkohl.link/online-java-compiler.git" target="_blank">Source code</a>.
        <a href="javascript:;" id="toggleFullWidth">Toggle full width</a>
    </div>
</body>
</html>