-
Notifications
You must be signed in to change notification settings - Fork 33
/
index.php
2220 lines (1995 loc) · 64.8 KB
/
index.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @copyright Copyright (c) 2016-2017 Lukas Reschke <lukas@statuscode.ch>
* @copyright Copyright (c) 2016 Morris Jobke <hey@morrisjobke.de>
* @copyright Copyright (c) 2018 Jonas Sulzer <jonas@violoncello.ch>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
class UpdateException extends \Exception {
protected $data;
public function __construct($data) {
$this->data = $data;
}
public function getData() {
return $this->data;
}
}
class LogException extends \Exception {
}
class RecursiveDirectoryIteratorWithoutData extends \RecursiveFilterIterator {
public function accept() {
/** @var \DirectoryIterator $this */
$excludes = [
'.rnd',
'.well-known',
'data',
'..',
];
return !(in_array($this->current()->getFilename(), $excludes, true) || $this->current()->isDir());
}
}
class Auth {
/** @var Updater */
private $updater;
/** @var string */
private $password;
/**
* @param Updater $updater
* @param string $password
*/
public function __construct(Updater $updater,
$password) {
$this->updater = $updater;
$this->password = $password;
}
/**
* Compares two strings.
*
* This method implements a constant-time algorithm to compare strings.
* Regardless of the used implementation, it will leak length information.
*
* @param string $knownString The string of known length to compare against
* @param string $userInput The string that the user can control
*
* @return bool true if the two strings are the same, false otherwise
* @license MIT
* @source https://github.com/symfony/security-core/blob/56721d5f5f63da7e08d05aa7668a5a9ef2367e1e/Util/StringUtils.php
*/
private static function equals($knownString, $userInput) {
// Avoid making unnecessary duplications of secret data
if (!is_string($knownString)) {
$knownString = (string) $knownString;
}
if (!is_string($userInput)) {
$userInput = (string) $userInput;
}
if (function_exists('hash_equals')) {
return hash_equals($knownString, $userInput);
}
$knownLen = self::safeStrlen($knownString);
$userLen = self::safeStrlen($userInput);
if ($userLen !== $knownLen) {
return false;
}
$result = 0;
for ($i = 0; $i < $knownLen; ++$i) {
$result |= (ord($knownString[$i]) ^ ord($userInput[$i]));
}
// They are only identical strings if $result is exactly 0...
return 0 === $result;
}
/**
* Returns the number of bytes in a string.
*
* @param string $string The string whose length we wish to obtain
*
* @return int
* @license MIT
* @source https://github.com/symfony/security-core/blob/56721d5f5f63da7e08d05aa7668a5a9ef2367e1e/Util/StringUtils.php
*/
private static function safeStrlen($string) {
// Premature optimization
// Since this cannot be changed at runtime, we can cache it
static $funcExists = null;
if (null === $funcExists) {
$funcExists = function_exists('mb_strlen');
}
if ($funcExists) {
return mb_strlen($string, '8bit');
}
return strlen($string);
}
/**
* Whether the current user is authenticated
*
* @return bool
*/
public function isAuthenticated() {
$storedHash = $this->updater->getConfigOption('updater.secret');
// As a sanity check the stored hash or the sent password can never be empty
if($storedHash === '' || $storedHash === null || $this->password === null) {
return false;
}
// As we still support PHP 5.4 we have to use some magic involving "crypt"
return $this->equals($storedHash, crypt($this->password, $storedHash));
}
}
class Updater {
/** @var string */
private $baseDir;
/** @var array */
private $configValues = [];
/** @var string */
private $currentVersion = 'unknown';
/** @var string */
private $buildTime;
/** @var bool */
private $updateAvailable = false;
/** @var string */
private $requestID = null;
/** @var bool */
private $disabled = false;
/**
* Updater constructor
* @param $baseDir string the absolute path to the /updater/ directory in the Nextcloud root
* @throws \Exception
*/
public function __construct($baseDir) {
$this->baseDir = $baseDir;
if($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
$configFileName = rtrim($dir, '/') . '/config.php';
} else {
$configFileName = $this->baseDir . '/../config/config.php';
}
if (!file_exists($configFileName)) {
throw new \Exception('Could not find config.php. Is this file in the "updater" subfolder of Nextcloud?');
}
/** @var array $CONFIG */
require_once $configFileName;
$this->configValues = $CONFIG;
if (php_sapi_name() !== 'cli' && ($this->configValues['upgrade.disable-web'] ?? false)) {
// updater disabled
$this->disabled = true;
return;
}
$dataDir = $this->getDataDirectoryLocation();
if(empty($dataDir) || !is_string($dataDir)) {
throw new \Exception('Could not read data directory from config.php.');
}
$versionFileName = $this->baseDir . '/../version.php';
if (!file_exists($versionFileName)) {
// fallback to version in config.php
$version = $this->getConfigOption('version');
$buildTime = '';
} else {
/** @var string $OC_VersionString */
/** @var string $OC_Build */
require_once $versionFileName;
$version = $OC_VersionString;
$buildTime = $OC_Build;
}
if($version === null) {
return;
}
if($buildTime === null) {
return;
}
// normalize version to 3 digits
$splittedVersion = explode('.', $version);
if(sizeof($splittedVersion) >= 3) {
$splittedVersion = array_slice($splittedVersion, 0, 3);
}
$this->currentVersion = implode('.', $splittedVersion);
$this->buildTime = $buildTime;
}
/**
* Returns whether the web updater is disabled
*
* @return bool
*/
public function isDisabled() {
return $this->disabled;
}
/**
* Returns current version or "unknown" if this could not be determined.
*
* @return string
*/
public function getCurrentVersion() {
return $this->currentVersion;
}
/**
* Returns currently used release channel
*
* @return string
*/
private function getCurrentReleaseChannel() {
return !is_null($this->getConfigOption('updater.release.channel')) ? $this->getConfigOption('updater.release.channel') : 'stable';
}
/**
* @return string
* @throws \Exception
*/
public function checkForUpdate() {
$response = $this->getUpdateServerResponse();
$this->silentLog('[info] checkForUpdate() ' . print_r($response, true));
$version = isset($response['version']) ? $response['version'] : '';
$versionString = isset($response['versionstring']) ? $response['versionstring'] : '';
if ($version !== '' && $version !== $this->currentVersion) {
$this->updateAvailable = true;
$releaseChannel = $this->getCurrentReleaseChannel();
$updateText = 'Update to ' . htmlentities($versionString) . ' available. (channel: "' . htmlentities($releaseChannel) . '")<br /><span class="light">Following file will be downloaded automatically:</span> <code class="light">' . $response['url'] . '</code>';
// only show changelog link for stable releases (non-RC & non-beta)
if (!preg_match('!(rc|beta)!i', $versionString)) {
$changelogURL = $this->getChangelogURL(substr($version, 0, strrpos($version, '.')));
$updateText .= '<br /><a class="external_link" href="' . $changelogURL . '" target="_blank" rel="noreferrer noopener">Open changelog ↗</a>';
}
} else {
$updateText = 'No update available.';
}
if ($this->updateAvailable && isset($response['autoupdater']) && !($response['autoupdater'] === 1 || $response['autoupdater'] === '1')) {
$this->updateAvailable = false;
$updateText .= '<br />The updater is disabled for this update - please update manually.';
}
$this->silentLog('[info] end of checkForUpdate() ' . $updateText);
return $updateText;
}
/**
* Returns bool whether update is available or not
*
* @return bool
*/
public function updateAvailable() {
return $this->updateAvailable;
}
/**
* Returns the specified config options
*
* @param string $key
* @return mixed|null Null if the entry is not found
*/
public function getConfigOption($key) {
return isset($this->configValues[$key]) ? $this->configValues[$key] : null;
}
/**
* Gets the data directory location on the local filesystem
*
* @return string
*/
private function getDataDirectoryLocation() {
return $this->configValues['datadirectory'];
}
/**
* Returns the expected files and folders as array
*
* @return array
*/
private function getExpectedElementsList() {
$expected = [
// Generic
'.',
'..',
// Folders
'.well-known',
'3rdparty',
'apps',
'config',
'core',
'data',
'dist',
'l10n',
'lib',
'ocs',
'ocs-provider',
'ocm-provider',
'resources',
'settings',
'themes',
'updater',
// Files
'.rnd',
'index.html',
'indie.json',
'.user.ini',
'console.php',
'cron.php',
'index.php',
'public.php',
'remote.php',
'status.php',
'version.php',
'robots.txt',
'.htaccess',
'AUTHORS',
'CHANGELOG.md',
'COPYING',
'COPYING-AGPL',
'occ',
'db_structure.xml',
];
return array_merge($expected, $this->getAppDirectories());
}
/**
* Returns app directories specified in config.php
*
* @return array
*/
private function getAppDirectories() {
$expected = [];
if($appsPaths = $this->getConfigOption('apps_paths')) {
foreach ($appsPaths as $appsPath) {
$parentDir = realpath($this->baseDir . '/../');
$appDir = basename($appsPath['path']);
if(strpos($appsPath['path'], $parentDir) === 0 && $appDir !== 'apps') {
$expected[] = $appDir;
}
}
}
return $expected;
}
/**
* Gets the recursive directory iterator over the Nextcloud folder
*
* @param string $folder
* @return \RecursiveIteratorIterator
*/
private function getRecursiveDirectoryIterator($folder = null) {
if ($folder === null) {
$folder = $this->baseDir . '/../';
}
return new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($folder, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
}
/**
* Checks for files that are unexpected.
*/
public function checkForExpectedFilesAndFolders() {
$this->silentLog('[info] checkForExpectedFilesAndFolders()');
$expectedElements = $this->getExpectedElementsList();
$unexpectedElements = [];
foreach (new \DirectoryIterator($this->baseDir . '/../') as $fileInfo) {
if(array_search($fileInfo->getFilename(), $expectedElements) === false) {
$unexpectedElements[] = $fileInfo->getFilename();
}
}
if (count($unexpectedElements) !== 0) {
throw new UpdateException($unexpectedElements);
}
$this->silentLog('[info] end of checkForExpectedFilesAndFolders()');
}
/**
* Checks for files that are not writable
*/
public function checkWritePermissions() {
$this->silentLog('[info] checkWritePermissions()');
$notWritablePaths = array();
$dir = new \RecursiveDirectoryIterator($this->baseDir . '/../');
$filter = new RecursiveDirectoryIteratorWithoutData($dir);
$it = new \RecursiveIteratorIterator($filter);
foreach ($it as $path => $dir) {
if(!is_writable($path)) {
$notWritablePaths[] = $path;
}
}
if(count($notWritablePaths) > 0) {
throw new UpdateException($notWritablePaths);
}
$this->silentLog('[info] end of checkWritePermissions()');
}
/**
* Sets the maintenance mode to the defined value
*
* @param bool $state
* @throws \Exception when config.php can't be written
*/
public function setMaintenanceMode($state) {
$this->silentLog('[info] setMaintenanceMode("' . ($state ? 'true' : 'false') . '")');
if($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
$configFileName = rtrim($dir, '/') . '/config.php';
} else {
$configFileName = $this->baseDir . '/../config/config.php';
}
$this->silentLog('[info] configFileName ' . $configFileName);
// usually is already tested in the constructor but just to be on the safe side
if (!file_exists($configFileName)) {
throw new \Exception('Could not find config.php.');
}
/** @var array $CONFIG */
require $configFileName;
$CONFIG['maintenance'] = $state;
$content = "<?php\n";
$content .= '$CONFIG = ';
$content .= var_export($CONFIG, true);
$content .= ";\n";
$state = file_put_contents($configFileName, $content);
if ($state === false) {
throw new \Exception('Could not write to config.php');
}
$this->silentLog('[info] end of setMaintenanceMode()');
}
/**
* Creates a backup of all files and moves it into data/updater-$instanceid/backups/nextcloud-X-Y-Z/
*
* @throws \Exception
*/
public function createBackup() {
$this->silentLog('[info] createBackup()');
$excludedElements = [
'.rnd',
'.well-known',
'data',
];
// Create new folder for the backup
$backupFolderLocation = $this->getDataDirectoryLocation() . '/updater-'.$this->getConfigOption('instanceid').'/backups/nextcloud-'.$this->getConfigOption('version') . '-' . time() . '/';
$this->silentLog('[info] backup folder location: ' . $backupFolderLocation);
$state = mkdir($backupFolderLocation, 0750, true);
if($state === false) {
throw new \Exception('Could not create backup folder location');
}
// Copy the backup files
$currentDir = $this->baseDir . '/../';
/**
* @var string $path
* @var \SplFileInfo $fileInfo
*/
foreach ($this->getRecursiveDirectoryIterator($currentDir) as $path => $fileInfo) {
$fileName = explode($currentDir, $path)[1];
$folderStructure = explode('/', $fileName, -1);
// Exclude the exclusions
if(isset($folderStructure[0])) {
if(array_search($folderStructure[0], $excludedElements) !== false) {
continue;
}
} else {
if(array_search($fileName, $excludedElements) !== false) {
continue;
}
}
// Create folder if it doesn't exist
if(!file_exists($backupFolderLocation . '/' . dirname($fileName))) {
$state = mkdir($backupFolderLocation . '/' . dirname($fileName), 0750, true);
if($state === false) {
throw new \Exception('Could not create folder: '.$backupFolderLocation.'/'.dirname($fileName));
}
}
// If it is a file copy it
if($fileInfo->isFile()) {
$state = copy($fileInfo->getRealPath(), $backupFolderLocation . $fileName);
if($state === false) {
$message = sprintf(
'Could not copy "%s" to "%s"',
$fileInfo->getRealPath(),
$backupFolderLocation . $fileName
);
if(is_readable($fileInfo->getRealPath()) === false) {
$message = sprintf(
'%s. Source %s is not readable',
$message,
$fileInfo->getRealPath()
);
}
if(is_writable($backupFolderLocation . $fileName) === false) {
$message = sprintf(
'%s. Destination %s is not writable',
$message,
$backupFolderLocation . $fileName
);
}
throw new \Exception($message);
}
}
}
$this->silentLog('[info] end of createBackup()');
}
private function getChangelogURL($versionString) {
$this->silentLog('[info] getChangelogURL()');
$changelogWebsite = 'https://nextcloud.com/changelog/';
$changelogURL = $changelogWebsite . '#' . str_replace('.', '-', $versionString);
return $changelogURL;
}
/**
* @return array
* @throws \Exception
*/
private function getUpdateServerResponse() {
$this->silentLog('[info] getUpdateServerResponse()');
$updaterServer = $this->getConfigOption('updater.server.url');
if($updaterServer === null) {
// FIXME: used deployed URL
$updaterServer = 'https://updates.nextcloud.com/updater_server/';
}
$this->silentLog('[info] updaterServer: ' . $updaterServer);
$releaseChannel = $this->getCurrentReleaseChannel();
$this->silentLog('[info] releaseChannel: ' . $releaseChannel);
$this->silentLog('[info] internal version: ' . $this->getConfigOption('version'));
$updateURL = $updaterServer . '?version='. str_replace('.', 'x', $this->getConfigOption('version')) .'xxx'.$releaseChannel.'xx'.urlencode($this->buildTime).'x'.PHP_MAJOR_VERSION.'x'.PHP_MINOR_VERSION.'x'.PHP_RELEASE_VERSION;
$this->silentLog('[info] updateURL: ' . $updateURL);
// Download update response
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $updateURL,
CURLOPT_USERAGENT => 'Nextcloud Updater',
]);
if ($this->getConfigOption('proxy') !== null) {
curl_setopt_array($curl, [
CURLOPT_PROXY => $this->getConfigOption('proxy'),
CURLOPT_PROXYUSERPWD => $this->getConfigOption('proxyuserpwd'),
CURLOPT_HTTPPROXYTUNNEL => $this->getConfigOption('proxy') ? 1 : 0,
]);
}
$response = curl_exec($curl);
if($response === false) {
throw new \Exception('Could not do request to updater server: '.curl_error($curl));
}
curl_close($curl);
// Response can be empty when no update is available
if($response === '') {
return [];
}
$xml = simplexml_load_string($response);
if($xml === false) {
throw new \Exception('Could not parse updater server XML response');
}
$json = json_encode($xml);
if($json === false) {
throw new \Exception('Could not JSON encode updater server response');
}
$response = json_decode($json, true);
if($response === null) {
throw new \Exception('Could not JSON decode updater server response.');
}
$this->silentLog('[info] getUpdateServerResponse response: ' . print_r($response, true));
return $response;
}
/**
* Downloads the nextcloud folder to $DATADIR/updater-$instanceid/downloads/$filename
*
* @throws \Exception
*/
public function downloadUpdate() {
$this->silentLog('[info] downloadUpdate()');
$response = $this->getUpdateServerResponse();
$storageLocation = $this->getDataDirectoryLocation() . '/updater-'.$this->getConfigOption('instanceid') . '/downloads/';
if(file_exists($storageLocation)) {
$this->silentLog('[info] storage location exists');
$this->recursiveDelete($storageLocation);
}
$state = mkdir($storageLocation, 0750, true);
if($state === false) {
throw new \Exception('Could not mkdir storage location');
}
$fp = fopen($storageLocation . basename($response['url']), 'w+');
$ch = curl_init($response['url']);
curl_setopt_array($ch, [
CURLOPT_FILE => $fp,
CURLOPT_USERAGENT => 'Nextcloud Updater',
]);
if ($this->getConfigOption('proxy') !== null) {
curl_setopt_array($ch, [
CURLOPT_PROXY => $this->getConfigOption('proxy'),
CURLOPT_PROXYUSERPWD => $this->getConfigOption('proxyuserpwd'),
CURLOPT_HTTPPROXYTUNNEL => $this->getConfigOption('proxy') ? 1 : 0,
]);
}
if(curl_exec($ch) === false) {
throw new \Exception('Curl error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpCode !== 200) {
$statusCodes = [
400 => 'Bad request',
401 => 'Unauthorized',
403 => 'Forbidden',
404 => 'Not Found',
500 => 'Internal Server Error',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
];
$message = 'Download failed';
if(isset($statusCodes[$httpCode])) {
$message .= ' - ' . $statusCodes[$httpCode] . ' (HTTP ' . $httpCode . ')';
} else {
$message .= ' - HTTP status code: ' . $httpCode;
}
$curlErrorMessage = curl_error($ch);
if(!empty($curlErrorMessage)) {
$message .= ' - curl error message: ' . $curlErrorMessage;
}
$message .= ' - URL: ' . htmlentities($response['url']);
throw new \Exception($message);
}
curl_close($ch);
fclose($fp);
$this->silentLog('[info] end of downloadUpdate()');
}
/**
* @return string
* @throws \Exception
*/
private function getDownloadedFilePath() {
$storageLocation = $this->getDataDirectoryLocation() . '/updater-'.$this->getConfigOption('instanceid') . '/downloads/';
$this->silentLog('[info] storage location: ' . $storageLocation);
$filesInStorageLocation = scandir($storageLocation);
$files = array_values(array_filter($filesInStorageLocation, function($path){
return $path !== '.' && $path !== '..';
}));
// only the downloaded archive
if(count($files) !== 1) {
throw new \Exception('There are more files than the downloaded archive in the downloads/ folder.');
}
return $storageLocation . '/' . $files[0];
}
/**
* Verifies the integrity of the downloaded file
*
* @throws \Exception
*/
public function verifyIntegrity() {
$this->silentLog('[info] verifyIntegrity()');
if($this->getCurrentReleaseChannel() === 'daily') {
$this->silentLog('[info] current channel is "daily" which is not signed. Skipping verification.');
return;
}
$response = $this->getUpdateServerResponse();
if(!isset($response['signature'])) {
throw new \Exception('No signature specified for defined update');
}
$certificate = <<<EOF
-----BEGIN CERTIFICATE-----
MIIEojCCA4qgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwezELMAkGA1UEBhMCREUx
GzAZBgNVBAgMEkJhZGVuLVd1ZXJ0dGVtYmVyZzEXMBUGA1UECgwOTmV4dGNsb3Vk
IEdtYkgxNjA0BgNVBAMMLU5leHRjbG91ZCBDb2RlIFNpZ25pbmcgSW50ZXJtZWRp
YXRlIEF1dGhvcml0eTAeFw0xNjA2MTIyMTA1MDZaFw00MTA2MDYyMTA1MDZaMGYx
CzAJBgNVBAYTAkRFMRswGQYDVQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxEjAQBgNV
BAcMCVN0dXR0Z2FydDEXMBUGA1UECgwOTmV4dGNsb3VkIEdtYkgxDTALBgNVBAMM
BGNvcmUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDUxcrn2DC892IX
8+dJjZVh9YeHF65n2ha886oeAizOuHBdWBfzqt+GoUYTOjqZF93HZMcwy0P+xyCf
Qqak5Ke9dybN06RXUuGP45k9UYBp03qzlUzCDalrkj+Jd30LqcSC1sjRTsfuhc+u
vH1IBuBnf7SMUJUcoEffbmmpAPlEcLHxlUGlGnz0q1e8UFzjbEFj3JucMO4ys35F
qZS4dhvCngQhRW3DaMlQLXEUL9k3kFV+BzlkPzVZEtSmk4HJujFCnZj1vMcjQBg/
Bqq1HCmUB6tulnGcxUzt/Z/oSIgnuGyENeke077W3EyryINL7EIyD4Xp7sxLizTM
FCFCjjH1AgMBAAGjggFDMIIBPzAJBgNVHRMEAjAAMBEGCWCGSAGG+EIBAQQEAwIG
QDAzBglghkgBhvhCAQ0EJhYkT3BlblNTTCBHZW5lcmF0ZWQgU2VydmVyIENlcnRp
ZmljYXRlMB0GA1UdDgQWBBQwc1H9AL8pRlW2e5SLCfPPqtqc0DCBpQYDVR0jBIGd
MIGagBRt6m6qqTcsPIktFz79Ru7DnnjtdKF+pHwwejELMAkGA1UEBhMCREUxGzAZ
BgNVBAgMEkJhZGVuLVd1ZXJ0dGVtYmVyZzESMBAGA1UEBwwJU3R1dHRnYXJ0MRcw
FQYDVQQKDA5OZXh0Y2xvdWQgR21iSDEhMB8GA1UEAwwYTmV4dGNsb3VkIFJvb3Qg
QXV0aG9yaXR5ggIQADAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUH
AwEwDQYJKoZIhvcNAQELBQADggEBADZ6+HV/+0NEH3nahTBFxO6nKyR/VWigACH0
naV0ecTcoQwDjKDNNFr+4S1WlHdwITlnNabC7v9rZ/6QvbkrOTuO9fOR6azp1EwW
2pixWqj0Sb9/dSIVRpSq+jpBE6JAiX44dSR7zoBxRB8DgVO2Afy0s80xEpr5JAzb
NYuPS7M5UHdAv2dr16fDcDIvn+vk92KpNh1NTeZFjBbRVQ9DXrgkRGW34TK8uSLI
YG6jnfJ6eJgTaO431ywWPXNg1mUMaT/+QBOgB299QVCKQU+lcZWptQt+RdsJUm46
NY/nARy4Oi4uOe88SuWITj9KhrFmEvrUlgM8FvoXA1ldrR7KiEg=
-----END CERTIFICATE-----
EOF;
$validSignature = (bool)openssl_verify(
file_get_contents($this->getDownloadedFilePath()),
base64_decode($response['signature']),
$certificate,
OPENSSL_ALGO_SHA512
);
if($validSignature === false) {
throw new \Exception('Signature of update is not valid');
}
$this->silentLog('[info] end of verifyIntegrity()');
}
/**
* Gets the version as declared in $versionFile
*
* @param string $versionFile
* @return string
* @throws \Exception If $OC_Version is not defined in $versionFile
*/
private function getVersionByVersionFile($versionFile) {
require $versionFile;
if(isset($OC_Version)) {
/** @var array $OC_Version */
return implode('.', $OC_Version);
}
throw new \Exception("OC_Version not found in $versionFile");
}
/**
* Extracts the download
*
* @throws \Exception
*/
public function extractDownload() {
$this->silentLog('[info] extractDownload()');
$downloadedFilePath = $this->getDownloadedFilePath();
$zip = new \ZipArchive;
$zipState = $zip->open($downloadedFilePath);
if ($zipState === true) {
$extraction = $zip->extractTo(dirname($downloadedFilePath));
if($extraction === false) {
throw new \Exception('Error during unpacking zipfile: '.($zip->getStatusString()));
}
$zip->close();
$state = unlink($downloadedFilePath);
if($state === false) {
throw new \Exception("Can't unlink ". $downloadedFilePath);
}
} else {
throw new \Exception("Can't handle ZIP file. Error code is: ".$zipState);
}
// Ensure that the downloaded version is not lower
$downloadedVersion = $this->getVersionByVersionFile(dirname($downloadedFilePath) . '/nextcloud/version.php');
$currentVersion = $this->getVersionByVersionFile($this->baseDir . '/../version.php');
if(version_compare($downloadedVersion, $currentVersion, '<')) {
throw new \Exception('Downloaded version is lower than installed version');
}
$this->silentLog('[info] end of extractDownload()');
}
/**
* Replaces the entry point files with files that only return a 503
*
* @throws \Exception
*/
public function replaceEntryPoints() {
$this->silentLog('[info] replaceEntryPoints()');
$filesToReplace = [
'index.php',
'status.php',
'remote.php',
'public.php',
'ocs/v1.php',
'ocs/v2.php',
];
$content = "<?php\nhttp_response_code(503);\ndie('Update in process.');";
foreach($filesToReplace as $file) {
$this->silentLog('[info] replace ' . $file);
$parentDir = dirname($this->baseDir . '/../' . $file);
if(!file_exists($parentDir)) {
$r = mkdir($parentDir);
if($r !== true) {
throw new \Exception('Can\'t create parent directory for entry point: ' . $file);
}
}
$state = file_put_contents($this->baseDir . '/../' . $file, $content);
if($state === false) {
throw new \Exception('Can\'t replace entry point: '.$file);
}
}
$this->silentLog('[info] end of replaceEntryPoints()');
}
/**
* Recursively deletes the specified folder from the system
*
* @param string $folder
* @throws \Exception
*/
private function recursiveDelete($folder) {
if(!file_exists($folder)) {
return;
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($folder, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
$directories = array();
$files = array();
foreach ($iterator as $fileInfo) {
if ($fileInfo->isDir()) {
$directories[] = $fileInfo->getRealPath();
} else {
if ($fileInfo->isLink()) {
$files[] = $fileInfo->getPathName();
} else {
$files[] = $fileInfo->getRealPath();
}
}
}
foreach ($files as $file) {
unlink($file);
}
foreach ($directories as $dir) {
rmdir($dir);
}
$state = rmdir($folder);
if($state === false) {
throw new \Exception('Could not rmdir ' . $folder);
}
}
/**
* Delete old files from the system as much as possible
*
* @throws \Exception
*/
public function deleteOldFiles() {
$this->silentLog('[info] deleteOldFiles()');
$shippedAppsFile = $this->baseDir . '/../core/shipped.json';
if(!file_exists($shippedAppsFile)) {
throw new \Exception('core/shipped.json is not available');
}
$newShippedAppsFile = $this->getDataDirectoryLocation() . '/updater-'.$this->getConfigOption('instanceid') . '/downloads/nextcloud/core/shipped.json';
if(!file_exists($newShippedAppsFile)) {
throw new \Exception('core/shipped.json is not available in the new release');
}
// Delete shipped apps
$shippedApps = array_merge(
json_decode(file_get_contents($shippedAppsFile), true)['shippedApps'],
json_decode(file_get_contents($newShippedAppsFile), true)['shippedApps']
);
foreach($shippedApps as $app) {
$this->recursiveDelete($this->baseDir . '/../apps/' . $app);
}
$configSampleFile = $this->baseDir . '/../config/config.sample.php';
if(file_exists($configSampleFile)) {
$this->silentLog('[info] config sample exists');
// Delete example config
$state = unlink($configSampleFile);
if ($state === false) {
throw new \Exception('Could not unlink sample config');
}
}
$themesReadme = $this->baseDir . '/../themes/README';
if(file_exists($themesReadme)) {
$this->silentLog('[info] themes README exists');
// Delete themes
$state = unlink($themesReadme);
if ($state === false) {
throw new \Exception('Could not delete themes README');
}
}
$this->recursiveDelete($this->baseDir . '/../themes/example/');
// Delete the rest
$excludedElements = [
'.well-known',
'data',
'index.php',
'status.php',
'remote.php',
'public.php',
'ocs/v1.php',
'ocs/v2.php',
'config',
'themes',
'apps',
'updater',
];
$excludedElements = array_merge($excludedElements, $this->getAppDirectories());
/**
* @var string $path
* @var \SplFileInfo $fileInfo
*/
foreach ($this->getRecursiveDirectoryIterator() as $path => $fileInfo) {
$currentDir = $this->baseDir . '/../';
$fileName = explode($currentDir, $path)[1];
$folderStructure = explode('/', $fileName, -1);
// Exclude the exclusions
if(isset($folderStructure[0])) {
if(array_search($folderStructure[0], $excludedElements) !== false) {
continue;
}
} else {
if(array_search($fileName, $excludedElements) !== false) {
continue;
}
}
if($fileInfo->isFile() || $fileInfo->isLink()) {