40 private $defaultAlgo =
'sha384';
43 private $hasErrors =
false;
46 private $registryFile;
52 private $tmpParentDir;
67 private $errorPrinter;
72 private $verbosePrinter;
91 callable $infoPrinter =
null,
92 callable $errorPrinter =
null,
93 callable $verbosePrinter =
null
95 $this->registryFile = $registryFile;
96 $this->libDir = $libDir;
97 $this->infoPrinter = $infoPrinter ??
static function ( $_ ) {
99 $this->errorPrinter = $errorPrinter ?? $this->infoPrinter;
100 $this->verbosePrinter = $verbosePrinter ??
static function ( $_ ) {
106 $this->tmpParentDir =
"{$this->libDir}/.foreign/tmp";
109 $cacheHome = getenv(
'XDG_CACHE_HOME' ) ? realpath( getenv(
'XDG_CACHE_HOME' ) ) :
false;
110 $this->cacheDir = $cacheHome ?
"$cacheHome/mw-foreign" :
"{$this->libDir}/.foreign/cache";
119 public function run( $action, $module ) {
120 $actions = [
'update',
'verify',
'make-sri' ];
121 if ( !in_array( $action, $actions ) ) {
122 $this->error(
"Invalid action.\n\nMust be one of " . implode(
', ', $actions ) .
'.' );
125 $this->action = $action;
127 $this->registry = Yaml::parseFile( $this->registryFile );
128 if ( $module ===
'all' ) {
130 } elseif ( isset( $this->registry[$module] ) ) {
131 $modules = [ $module => $this->registry[$module] ];
133 $this->error(
"Unknown module name.\n\nMust be one of:\n" .
134 wordwrap( implode(
', ', array_keys( $this->registry ) ), 80 ) .
140 foreach (
$modules as $moduleName => $info ) {
141 $this->verbose(
"\n### {$moduleName}\n\n" );
143 if ( $this->action ===
'update' ) {
144 $this->output(
"... updating '{$moduleName}'\n" );
145 } elseif ( $this->action ===
'verify' ) {
146 $this->output(
"... verifying '{$moduleName}'\n" );
148 $this->output(
"... checking '{$moduleName}'\n" );
155 if ( !isset( $info[
'type'] ) ) {
156 throw new Exception(
"Module '$moduleName' must have a 'type' key." );
159 $this->validateLicense( $moduleName, $info );
161 $destDir =
"{$this->libDir}/$moduleName";
163 if ( $this->action ===
'update' ) {
164 $this->verbose(
"... emptying directory for $moduleName\n" );
168 $this->verbose(
"... preparing {$this->tmpParentDir}\n" );
171 throw new Exception(
"Unable to create {$this->tmpParentDir}" );
174 switch ( $info[
'type'] ) {
176 $this->handleTypeTar( $moduleName, $destDir, $info );
179 $this->handleTypeFile( $moduleName, $destDir, $info );
182 $this->handleTypeMultiFile( $moduleName, $destDir, $info );
185 throw new Exception(
"Unknown type '{$info['type']}' for '$moduleName'" );
190 if ( $this->hasErrors ) {
207 private function cacheKey( $src, $integrity, $moduleName ) {
208 $key = $moduleName .
'_' . hash(
'fnv132', $integrity ) .
'_' . basename( $src );
209 $key = preg_replace(
'/[.\/+?=_-]+/',
'_', $key );
210 return rtrim( $key,
'_' );
217 private function cacheGet( $key ) {
219 return @file_get_contents(
"{$this->cacheDir}/$key.data" );
226 private function cacheSet( $key, $data ) {
228 @mkdir( $this->cacheDir, 0777,
true );
229 file_put_contents(
"{$this->cacheDir}/$key.data", $data, LOCK_EX );
238 private function fetch(
string $src, $integrity,
string $moduleName ) {
239 if ( $integrity !==
null ) {
240 $key = $this->cacheKey( $src, $integrity, $moduleName );
241 $data = $this->cacheGet( $key );
248 ->create( $src, [
'method' =>
'GET',
'followRedirects' =>
false ], __METHOD__ );
249 if ( !$req->execute()->isOK() ) {
250 throw new Exception(
"Failed to download resource at {$src}" );
252 if ( $req->getStatus() !== 200 ) {
253 throw new Exception(
"Unexpected HTTP {$req->getStatus()} response from {$src}" );
255 $data = $req->getContent();
256 $algo = $integrity ===
null ? $this->defaultAlgo : explode(
'-', $integrity )[0];
257 $actualIntegrity = $algo .
'-' . base64_encode( hash( $algo, $data,
true ) );
258 if ( $integrity === $actualIntegrity ) {
259 $this->verbose(
"... passed integrity check for {$src}\n" );
260 $key = $this->cacheKey( $src, $actualIntegrity, $moduleName );
261 $this->cacheSet( $key, $data );
262 } elseif ( $this->action ===
'make-sri' ) {
263 $this->output(
"Integrity for {$src}\n\tintegrity: {$actualIntegrity}\n" );
265 $expectedIntegrity = $integrity ??
'null';
266 throw new Exception(
"Integrity check failed for {$src}\n" .
267 "\tExpected: {$expectedIntegrity}\n" .
268 "\tActual: {$actualIntegrity}"
279 private function handleTypeFile( $moduleName, $destDir, array $info ) {
280 if ( !isset( $info[
'src'] ) ) {
281 throw new Exception(
"Module '$moduleName' must have a 'src' key." );
283 $data = $this->fetch( $info[
'src'], $info[
'integrity'] ??
null, $moduleName );
284 $dest = $info[
'dest'] ?? basename( $info[
'src'] );
285 $path =
"$destDir/$dest";
286 if ( $this->action ===
'verify' && sha1_file(
$path ) !== sha1( $data ) ) {
287 $this->error(
"File for '$moduleName' is different.\n" );
289 if ( $this->action ===
'update' ) {
291 file_put_contents(
"$destDir/$dest", $data );
300 private function handleTypeMultiFile( $moduleName, $destDir, array $info ) {
301 if ( !isset( $info[
'files'] ) ) {
302 throw new Exception(
"Module '$moduleName' must have a 'files' key." );
304 foreach ( $info[
'files'] as $dest =>
$file ) {
305 if ( !isset(
$file[
'src'] ) ) {
306 throw new Exception(
"Module '$moduleName' file '$dest' must have a 'src' key." );
308 $data = $this->fetch(
$file[
'src'],
$file[
'integrity'] ??
null, $moduleName );
309 $path =
"$destDir/$dest";
310 if ( $this->action ===
'verify' && sha1_file(
$path ) !== sha1( $data ) ) {
311 $this->error(
"File '$dest' for '$moduleName' is different.\n" );
312 } elseif ( $this->action ===
'update' ) {
314 file_put_contents(
"$destDir/$dest", $data );
324 private function handleTypeTar( $moduleName, $destDir, array $info ) {
325 $info += [
'src' =>
null,
'integrity' =>
null,
'dest' => null ];
326 if ( $info[
'src'] ===
null ) {
327 throw new Exception(
"Module '$moduleName' must have a 'src' key." );
330 $data = $this->fetch( $info[
'src'], $info[
'integrity'], $moduleName );
331 $tmpFile =
"{$this->tmpParentDir}/$moduleName.tar";
332 $this->verbose(
"... writing '$moduleName' src to $tmpFile\n" );
333 file_put_contents( $tmpFile, $data );
334 $p =
new PharData( $tmpFile );
335 $tmpDir =
"{$this->tmpParentDir}/$moduleName";
336 $p->extractTo( $tmpDir );
339 if ( $info[
'dest'] ===
null ) {
341 $toCopy = [ $tmpDir => $destDir ];
345 foreach ( $info[
'dest'] as $fromSubPath => $toSubPath ) {
347 $fromPaths = glob(
"{$tmpDir}/{$fromSubPath}", GLOB_BRACE );
349 throw new Exception(
"Path '$fromSubPath' of '$moduleName' not found." );
351 foreach ( $fromPaths as $fromPath ) {
352 $toCopy[$fromPath] = $toSubPath ===
null
353 ?
"$destDir/" . basename( $fromPath )
354 :
"$destDir/$toSubPath/" . basename( $fromPath );
358 foreach ( $toCopy as $from => $to ) {
359 if ( $this->action ===
'verify' ) {
360 $this->verbose(
"... verifying $to\n" );
361 if ( is_dir( $from ) ) {
362 $rii =
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
364 RecursiveDirectoryIterator::SKIP_DOTS
367 foreach ( $rii as
$file ) {
368 $remote =
$file->getPathname();
369 $local = strtr( $remote, [ $from => $to ] );
370 if ( sha1_file( $remote ) !== sha1_file( $local ) ) {
371 $this->error(
"File '$local' is different.\n" );
374 } elseif ( sha1_file( $from ) !== sha1_file( $to ) ) {
375 $this->error(
"File '$to' is different.\n" );
377 } elseif ( $this->action ===
'update' ) {
378 $this->verbose(
"... moving $from to $to\n" );
380 if ( !rename( $from, $to ) ) {
381 throw new Exception(
"Could not move $from to $to." );
390 private function verbose( $text ) {
391 ( $this->verbosePrinter )( $text );
397 private function output( $text ) {
398 ( $this->infoPrinter )( $text );
404 private function error( $text ) {
405 $this->hasErrors =
true;
406 ( $this->errorPrinter )( $text );
409 private function cleanUp() {
414 foreach ( $this->registry as $module => $info ) {
415 if ( $info[
'type'] ===
'file' || $info[
'type'] ===
'tar' ) {
416 $knownKeys[] = $this->cacheKey( $info[
'src'], $info[
'integrity'], $module );
417 } elseif ( $info[
'type'] ===
'multi-file' ) {
418 foreach ( $info[
'files'] as
$file ) {
419 $knownKeys[] = $this->cacheKey(
$file[
'src'],
$file[
'integrity'], $module );
423 foreach ( glob(
"{$this->cacheDir}/*" ) as $cacheFile ) {
424 if ( !in_array( basename( $cacheFile,
'.data' ), $knownKeys ) ) {
425 unlink( $cacheFile );
434 private function validateLicense( $moduleName, $info ) {
435 if ( !isset( $info[
'license'] ) || !is_string( $info[
'license'] ) ) {
436 throw new Exception(
"Module '$moduleName' needs a valid SPDX license; no license is currently present" );
438 $licenses =
new SpdxLicenses();
439 if ( !$licenses->validate( $info[
'license'] ) ) {
441 "Module '$moduleName' has an invalid SPDX license identifier '{$info['license']}', "
442 .
"see <https://spdx.org/licenses/>.\n"