forked from CollaboraOnline/richdocumentscode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.php
423 lines (361 loc) · 12.3 KB
/
proxy.php
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
416
417
418
419
420
421
422
423
<?php
/*
* Copyright (C) 2020 Collabora Productivity, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// test with:
// http://localhost/richproxy/proxy.php?req=/browser/dist/cool.html?file_path=file:///opt/libreoffice/online/test/data/hello-world.odt
function debug_log($msg)
{
// Disabled for production; enable for debugging
// error_log("richdocumentscode (proxy.php) debug, PID: " . getmypid() . ", Message: $msg");
}
function errorExit($msg)
{
print "<html><body>\n";
print "<h1>Socket proxy error</h1>\n";
print "<p>Error: " . $msg . "</p>\n";
print "</body></html>\n";
error_log("richdocumentscode (proxy.php) error exit, PID: " . getmypid() . ", Message: $msg");
http_response_code(400);
exit();
}
debug_log('Proxy v1');
// Let the webserver time us out in its own good time.
set_time_limit(0);
// Where the appimage is installed
$appImage = __DIR__ . '/collabora/Collabora_Online.AppImage';
$tmp_dir = ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : sys_get_temp_dir();
$lockfile = "$tmp_dir/coolwsd.lock";
$pidfile = "$tmp_dir/coolwsd.pid";
function getCoolwsdPid()
{
global $pidfile;
clearstatcache();
if (file_exists($pidfile))
{
$pid = rtrim(file_get_contents($pidfile));
debug_log("Coolwsd server running with pid: " . $pid);
return $pid;
}
debug_log("Coolwsd server is not running.");
return 0;
}
function isCoolwsdRunning()
{
$pid = getCoolwsdPid();
if ($pid === 0)
return 0;
return posix_kill($pid,0);
}
function startCoolwsd()
{
global $appImage;
global $pidfile;
global $lockfile;
// Extract the AppImage if FUSE is not available
$launchCmd = "bash -c \"( $appImage --pidfile=$pidfile || $appImage --appimage-extract-and-run --pidfile=$pidfile) >/dev/null & disown\"";
// Remove stale lock file (just in case)
if (file_exists("$lockfile"))
if (time() - filectime("$lockfile") > 60 * 5)
unlink("$lockfile");
// Prevent second start
$lock = @fopen("$lockfile", "x");
if ($lock)
{
// We start a new server, we don't need stale pidfile around
if (file_exists("$pidfile"))
unlink("$pidfile");
debug_log("Launch the coolwsd server: $launchCmd");
exec($launchCmd, $output, $return);
if ($return)
debug_log("Failed to launch server at $appImage.");
fclose($lock);
}
while (!isCoolwsdRunning())
sleep(1);
if (file_exists("$lockfile"))
unlink("$lockfile");
}
function stopCoolwsd()
{
$pid = getCoolwsdPid();
if (posix_kill($pid,0))
{
debug_log("Stopping the coolwsd server with pid: $pid");
posix_kill($pid, 15 /*SIGTERM*/);
}
}
// Check that the setup is suitable for running the coolwsd.
// Returns the error ID if we find a problem.
function checkCoolwsdSetup()
{
global $appImage;
if (PHP_OS_FAMILY !== 'Linux')
return 'not_linux';
if (php_uname('m') !== 'x86_64')
return 'not_x86_64';
if (!file_exists($appImage))
return 'appimage_missing';
@chmod($appImage, 0744);
clearstatcache(); // effect of chmod() won't be detected without this call
if (!is_executable($appImage))
return 'appimage_not_executable';
if (@exec('echo EXEC') !== "EXEC")
return 'exec_disabled';
exec("LD_TRACE_LOADED_OBJECTS=1 $appImage", $output, $return);
if ($return)
return 'no_glibc';
exec('( /sbin/ldconfig -p || scanelf -l ) | grep fontconfig > /dev/null 2>&1', $output, $return);
if ($return)
return 'no_fontconfig';
return '';
}
// parse and emit headers using 'header' ...
function parseLastHeader(&$chunk)
{
$headers = explode("\r\n", $chunk);
debug_log("Headers: $chunk");
$chop = 0;
$endOfHeaders = false;
foreach ($headers as $h)
{
debug_log("send: $h");
$chop += strlen($h) + 2;
if ($h === '')
{
$endOfHeaders = true;
break;
}
header($h);
}
// keep looking for the next header.
$chunk = substr($chunk, $chop);
return $endOfHeaders;
}
function startsWith($string, $with) {
return (substr($string, 0, strlen($with)) === $with);
}
if (!function_exists('getallheaders'))
{
// polyfill, e.g. on PHP 7.2 setups with nginx.
// Can be removed when 7.2 becomes unsupported
function getallheaders()
{
$headers = [];
if (!is_array($_SERVER)) {
return $headers;
}
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) === 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
// avoid unwanted escaping of req= parameter
$request = $_SERVER['QUERY_STRING'];
// only asking for status?
$statusOnly = false;
// handle parameters
if (startsWith($request, 'status')) {
$request = '';
$statusOnly = true;
} else if (startsWith($request, 'req=')) {
$request = substr($request, strlen('req='));
if (substr($request, 0, 1) !== '/')
errorExit("First ?req= param should be an absolute path: '" . $request . "'");
} else {
errorExit("The param should be 'status' or 'req=...', but is: '" . $request . "'");
}
debug_log("get URI " . $request);
if ($request === '' && !$statusOnly)
errorExit("Missing, required req= parameter");
if (startsWith($request, '/hosting/capabilities') && !isCoolwsdRunning()) {
header('Content-type: application/json');
header('Cache-Control: no-store');
print '{
"convert-to":{"available":true},
"hasMobileSupport":true,
"hasProxyPrefix":false,
"hasTemplateSaveAs":false,
"hasTemplateSource":true
}';
http_response_code(200);
exit();
}
// If we can't get a socket open in 3 seconds when that is backed by
// a dedicated thread, then we have a server missing in action.
$local = @fsockopen("localhost", 9983, $errno, $errstr, 3);
// Return the status and exit if it is a ?status request
if ($statusOnly) {
header('Content-type: application/json');
header('Cache-Control: no-store');
if (!$local) {
$err = checkCoolwsdSetup();
if (!empty($err))
print '{"status":"error","error":"' . $err . '"}';
else if (!isCoolwsdRunning()) {
startCoolwsd();
print '{"status":"starting"}';
}
} else if ($errno === 111) {
print '{"status":"starting"}';
} else {
$response = file_get_contents("http://localhost:9983/hosting/capabilities", 0, stream_context_create(["http"=>["timeout"=>1]]));
if ($response) {
// Version check.
$obj = json_decode($response);
$actVer = substr($obj->{'productVersionHash'}, 0, 8); // expVer is at most 8 characters long
$expVer = '%COOLWSD_VERSION_HASH%';
if ($actVer !== $expVer && $expVer !== '%' . 'COOLWSD_VERSION_HASH' . '%') { // deliberately split so that sed does not touch this during build-time
// Old/unexpected server version; restart.
error_log("Old server found, restarting. Expected hash $expVer but found $actVer.");
stopCoolwsd();
// wait 10 seconds max
for ($i = 0; isCoolwsdRunning() && ($i < 10); $i++)
sleep(1);
// somebody else might have restarted it in the meantime
if (!isCoolwsdRunning())
startCoolwsd();
print '{"status":"restarting"}';
}
else
print '{"status":"OK"}';
}
else
print '{"status":"starting"}';
fclose($local);
}
http_response_code(200);
exit();
}
// URL into this server of the proxy script.
if ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' )
|| (isset($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on')
) {
$proxyURL = "https://";
} else {
$proxyURL = "http://";
}
// Start the appimage if necessary
if (!$local)
{
$err = checkCoolwsdSetup();
if (!empty($err))
errorExit($err);
else if (!isCoolwsdRunning())
startCoolwsd();
$logonce = true;
while (true) {
$local = @fsockopen("localhost", 9983, $errno, $errstr, 15);
if ($errno === 111) {
if($logonce) {
debug_log("Can't yet connect to socket so sleep");
$logonce = false;
}
usleep(50 * 1000); // 50ms.
} else {
debug_log("connected?");
break;
}
}
}
if (!$local) {
errorExit("Timed out opening local socket: $errno - $errstr");
}
// Fetch our headers for later
$headers = getallheaders();
$proxyURL .= $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?req=';
debug_log("ProxyPrefix: '$proxyURL'");
$realRequest = $_SERVER['REQUEST_METHOD'] . " " . $request . " " . $_SERVER['SERVER_PROTOCOL'];
debug_log("Onward request is: '$realRequest'");
$body = file_get_contents('php://input');
debug_log("request content: '$body'");
// Oh dear - PHP's rfc1867 handling doesn't give any php://input to work with in this case.
$multiBody = '';
if ($body === '' && count($_FILES) > 0) {
debug_log("Oh dear - PHP's rfc1867 handling doesn't give any php://input to work with");
$type = $headers['Content-Type'];
$boundary = trim(explode('boundary=', $type)[1]);
foreach ($_REQUEST as $key=>$value) {
if ($key === 'req') {
continue;
}
$multiBody .= "--" . $boundary . "\r\n";
$multiBody .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n";
$multiBody .= "$value\r\n";
}
foreach ($_FILES as $file) {
$multiBody .= "--" . $boundary . "\r\n";
$multiBody .= "Content-Disposition: form-data; name=\"file\"; filename=\"" . $file['name'] . "\"\r\n";
$multiBody .= "Content-Type: " . $file['type'] . "\r\n\r\n";
if ($file['tmp_name'] === '') {
errorExit("File " . $file['name'] . " is larger than maximum up-load file-size");
}
$multiBody .= file_get_contents($file['tmp_name']) . "\r\n";
}
$multiBody .= "--" . $boundary . "--\r\n";
$body = $multiBody;
debug_log("$body");
}
fwrite($local, $realRequest . "\r\n");
// Send the headers on ...
foreach ($headers as $header => $value) {
debug_log("$header: $value\n");
if ($multiBody !== '' && $header === 'Content-Length')
{
debug_log("Substitute Content-Length of " . $value . " with " . strlen($body));
$value = strlen($body);
}
fwrite($local, "$header: $value\r\n");
}
fwrite($local, "ProxyPrefix: " . $proxyURL . "\r\n");
fwrite($local, "\r\n");
fwrite($local, $body);
debug_log("waiting for response");
$rest = '';
$parsingHeaders = true;
do {
$chunk = fread($local, 65536);
if($chunk === false) {
$error = socket_last_error($local);
echo "ERROR ! $error\n";
debug_log("error on chunk: $error");
break;
} elseif($chunk === '') {
debug_log("empty chunk last data");
if ($parsingHeaders)
errorExit("No content in reply from coolwsd. Is SSL enabled in error ?");
break;
} elseif ($parsingHeaders) {
$rest .= $chunk;
debug_log("build headers to: $rest\n");
if (parseLastHeader($rest)) {
$parsingHeaders = false;
$extOut = fopen("php://output", "w") or errorExit("fundamental error opening PHP output");
fwrite($extOut, $rest);
$rest = '';
debug_log("passed last headers");
}
} else {
fwrite($extOut, $chunk);
debug_log("proxy : " . strlen($chunk) . " bytes \n");
}
} while(true);
debug_log("closing local socket");
fclose($local);
?>