1 package org.apache.archiva.webdav;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import com.google.common.io.Files;
23 import org.apache.archiva.admin.model.RepositoryAdminException;
24 import org.apache.archiva.admin.model.beans.ManagedRepository;
25 import org.apache.archiva.admin.model.beans.RemoteRepository;
26 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
27 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
28 import org.apache.archiva.audit.AuditEvent;
29 import org.apache.archiva.audit.AuditListener;
30 import org.apache.archiva.audit.Auditable;
31 import org.apache.archiva.common.filelock.FileLockManager;
32 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
33 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
34 import org.apache.archiva.common.utils.PathUtil;
35 import org.apache.archiva.common.utils.VersionUtil;
36 import org.apache.archiva.configuration.ArchivaConfiguration;
37 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
38 import org.apache.archiva.indexer.merger.IndexMerger;
39 import org.apache.archiva.indexer.merger.IndexMergerException;
40 import org.apache.archiva.indexer.merger.IndexMergerRequest;
41 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTask;
42 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTaskRequest;
43 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
44 import org.apache.archiva.indexer.search.RepositorySearch;
45 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
46 import org.apache.archiva.metadata.repository.storage.RelocationException;
47 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
48 import org.apache.archiva.model.ArchivaRepositoryMetadata;
49 import org.apache.archiva.model.ArtifactReference;
50 import org.apache.archiva.policies.ProxyDownloadException;
51 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
52 import org.apache.archiva.redback.authentication.AuthenticationException;
53 import org.apache.archiva.redback.authentication.AuthenticationResult;
54 import org.apache.archiva.redback.authorization.AuthorizationException;
55 import org.apache.archiva.redback.authorization.UnauthorizedException;
56 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
57 import org.apache.archiva.redback.policy.AccountLockedException;
58 import org.apache.archiva.redback.policy.MustChangePasswordException;
59 import org.apache.archiva.redback.system.SecuritySession;
60 import org.apache.archiva.redback.users.User;
61 import org.apache.archiva.redback.users.UserManager;
62 import org.apache.archiva.repository.ManagedRepositoryContent;
63 import org.apache.archiva.repository.RepositoryContentFactory;
64 import org.apache.archiva.repository.RepositoryException;
65 import org.apache.archiva.repository.RepositoryNotFoundException;
66 import org.apache.archiva.repository.content.legacy.LegacyPathParser;
67 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
68 import org.apache.archiva.repository.layout.LayoutException;
69 import org.apache.archiva.repository.metadata.MetadataTools;
70 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
71 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
72 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
73 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
74 import org.apache.archiva.security.ServletAuthenticator;
75 import org.apache.archiva.webdav.util.MimeTypes;
76 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
77 import org.apache.archiva.webdav.util.WebdavMethodUtil;
78 import org.apache.archiva.xml.XMLException;
79 import org.apache.commons.io.FileUtils;
80 import org.apache.commons.io.FilenameUtils;
81 import org.apache.commons.lang.StringUtils;
82 import org.apache.commons.lang.SystemUtils;
83 import org.apache.jackrabbit.webdav.DavException;
84 import org.apache.jackrabbit.webdav.DavResource;
85 import org.apache.jackrabbit.webdav.DavResourceFactory;
86 import org.apache.jackrabbit.webdav.DavResourceLocator;
87 import org.apache.jackrabbit.webdav.DavServletRequest;
88 import org.apache.jackrabbit.webdav.DavServletResponse;
89 import org.apache.jackrabbit.webdav.DavSession;
90 import org.apache.jackrabbit.webdav.lock.LockManager;
91 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
92 import org.apache.maven.index.context.IndexingContext;
93 import org.codehaus.plexus.digest.ChecksumFile;
94 import org.codehaus.plexus.digest.Digester;
95 import org.codehaus.plexus.digest.DigesterException;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
98 import org.slf4j.MarkerFactory;
99 import org.springframework.context.ApplicationContext;
100 import org.springframework.stereotype.Service;
102 import javax.annotation.PostConstruct;
103 import javax.inject.Inject;
104 import javax.inject.Named;
105 import javax.servlet.http.HttpServletResponse;
106 import javax.servlet.http.HttpSession;
108 import java.io.IOException;
109 import java.util.ArrayList;
110 import java.util.Date;
111 import java.util.HashMap;
112 import java.util.HashSet;
113 import java.util.List;
114 import java.util.Map;
115 import java.util.Set;
120 @Service( "davResourceFactory#archiva" )
121 public class ArchivaDavResourceFactory
122 implements DavResourceFactory, Auditable
124 private static final String PROXIED_SUFFIX = " (proxied)";
126 private static final String HTTP_PUT_METHOD = "PUT";
128 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
131 private List<AuditListener> auditListeners = new ArrayList<>();
134 private RepositoryContentFactory repositoryFactory;
136 private RepositoryRequest repositoryRequest;
139 @Named( value = "repositoryProxyConnectors#default" )
140 private RepositoryProxyConnectors connectors;
143 private MetadataTools metadataTools;
146 private MimeTypes mimeTypes;
148 private ArchivaConfiguration archivaConfiguration;
151 private ServletAuthenticator servletAuth;
154 @Named( value = "httpAuthenticator#basic" )
155 private HttpAuthenticator httpAuth;
158 private RemoteRepositoryAdmin remoteRepositoryAdmin;
161 private ManagedRepositoryAdmin managedRepositoryAdmin;
164 private IndexMerger indexMerger;
167 private RepositorySearch repositorySearch;
170 * Lock Manager - use simple implementation from JackRabbit
172 private final LockManager lockManager = new SimpleLockManager();
174 private ChecksumFile checksum;
176 private Digester digestSha1;
178 private Digester digestMd5;
181 @Named( value = "archivaTaskScheduler#repository" )
182 private RepositoryArchivaTaskScheduler scheduler;
185 @Named( value = "fileLockManager#default" )
186 private FileLockManager fileLockManager;
188 private ApplicationContext applicationContext;
191 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
192 ArchivaConfiguration archivaConfiguration )
193 throws PlexusSisuBridgeException
195 this.archivaConfiguration = archivaConfiguration;
196 this.applicationContext = applicationContext;
197 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
199 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
200 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
202 // TODO remove this hard dependency on maven !!
203 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
207 public void initialize()
213 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
214 final DavServletResponse response )
217 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
219 RepositoryGroupConfiguration repoGroupConfig =
220 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
222 String activePrincipal = getActivePrincipal( request );
224 List<String> resourcesInAbsolutePath = new ArrayList<>();
226 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
227 DavResource resource;
228 if ( repoGroupConfig != null )
232 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
233 "Write method not allowed for repository groups." );
236 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
238 // handle browse requests for virtual repos
239 if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
243 DavResource davResource =
244 getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
247 setHeaders( response, locator, davResource );
252 catch ( RepositoryAdminException e )
254 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
259 // make a copy to avoid potential concurrent modifications (eg. by configuration)
260 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
262 List<String> repositories = new ArrayList<>( repoGroupConfig.getRepositories() );
263 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
264 resourcesInAbsolutePath, repoGroupConfig );
272 RemoteRepository remoteRepository =
273 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
275 if ( remoteRepository != null )
277 String logicalResource = getLogicalResource( archivaLocator, null, false );
278 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
279 File resourceFile = StringUtils.equals( logicalResource, "/" )
280 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
281 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
282 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
283 request.getRemoteAddr(), activePrincipal,
284 request.getDavSession(), archivaLocator, this, mimeTypes,
285 auditListeners, scheduler, fileLockManager );
286 setHeaders( response, locator, resource );
290 catch ( RepositoryAdminException e )
292 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
293 archivaLocator.getRepositoryId(), e.getMessage() );
296 ManagedRepositoryContent managedRepositoryContent = null;
300 managedRepositoryContent =
301 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
303 catch ( RepositoryNotFoundException e )
305 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
306 "Invalid repository: " + archivaLocator.getRepositoryId() );
308 catch ( RepositoryException e )
310 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
313 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
317 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
318 managedRepositoryAdmin.getManagedRepository(
319 archivaLocator.getRepositoryId() )
322 String logicalResource = getLogicalResource( archivaLocator, null, false );
323 resourcesInAbsolutePath.add(
324 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
327 catch ( RepositoryAdminException e )
329 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
333 String requestedResource = request.getRequestURI();
335 // MRM-872 : merge all available metadata
336 // merge metadata only when requested via the repo group
337 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
338 requestedResource ) ) && repoGroupConfig != null )
340 // this should only be at the project level not version level!
341 if ( isProjectReference( requestedResource ) )
344 ArchivaDavResource res = (ArchivaDavResource) resource;
346 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
348 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
350 // for MRM-872 handle checksums of the merged metadata files
351 if ( repositoryRequest.isSupportFile( requestedResource ) )
353 File metadataChecksum =
354 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
355 if ( metadataChecksum.exists() )
357 LogicalResource logicalResource =
358 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
361 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
362 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
363 archivaLocator, this, mimeTypes, auditListeners, scheduler,
369 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
371 // merge the metadata of all repos under group
372 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
373 for ( String resourceAbsPath : resourcesInAbsolutePath )
377 File metadataFile = new File( resourceAbsPath );
378 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
379 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
381 catch ( XMLException e )
383 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
384 "Error occurred while reading metadata file." );
386 catch ( RepositoryMetadataException r )
388 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
389 "Error occurred while merging metadata file." );
395 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
397 LogicalResource logicalResource =
398 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
401 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
402 request.getRemoteAddr(), activePrincipal,
403 request.getDavSession(), archivaLocator, this, mimeTypes,
404 auditListeners, scheduler, fileLockManager );
406 catch ( RepositoryMetadataException r )
408 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
409 "Error occurred while writing metadata file." );
411 catch ( IOException ie )
413 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
414 "Error occurred while generating checksum files." );
416 catch ( DigesterException de )
418 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
419 "Error occurred while generating checksum files."
427 setHeaders( response, locator, resource );
429 // compatibility with MRM-440 to ensure browsing the repository works ok
430 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
432 throw new BrowserRedirectException( resource.getHref() );
434 resource.addLockManager( lockManager );
438 private DavResource processRepositoryGroup( final DavServletRequest request,
439 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
440 String activePrincipal, List<String> resourcesInAbsolutePath,
441 RepositoryGroupConfiguration repoGroupConfig )
444 DavResource resource = null;
445 List<DavException> storedExceptions = new ArrayList<>();
447 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
449 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
451 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
453 // we are in the case of index file request
454 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
455 File temporaryIndexDirectory =
456 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
458 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
459 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
460 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
461 archivaLocator, this, mimeTypes, auditListeners, scheduler,
467 for ( String repositoryId : repositories )
469 ManagedRepositoryContent managedRepositoryContent;
472 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
474 catch ( RepositoryNotFoundException e )
476 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
478 catch ( RepositoryException e )
480 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
485 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
486 DavResource updatedResource =
487 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
489 if ( resource == null )
491 resource = updatedResource;
494 String logicalResource = getLogicalResource( archivaLocator, null, false );
495 if ( logicalResource.endsWith( "/" ) )
497 logicalResource = logicalResource.substring( 1 );
499 resourcesInAbsolutePath.add(
500 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
502 catch ( DavException e )
504 storedExceptions.add( e );
506 catch ( RepositoryAdminException e )
508 storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
512 if ( resource == null )
514 if ( !storedExceptions.isEmpty() )
517 for ( DavException e : storedExceptions )
519 if ( 401 == e.getErrorCode() )
525 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
529 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
535 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
536 boolean useOrigResourcePath )
538 // FIXME remove this hack
539 // but currently managedRepository can be null in case of group
540 String layout = managedRepository == null ? new ManagedRepository().getLayout() : managedRepository.getLayout();
541 RepositoryStorage repositoryStorage =
542 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
543 String path = repositoryStorage.getFilePath(
544 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
546 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
547 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
552 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator,
553 ManagedRepositoryContent managedRepositoryContent, String contextPath )
556 String layout = managedRepositoryContent.getRepository() == null
557 ? new ManagedRepository().getLayout()
558 : managedRepositoryContent.getRepository().getLayout();
559 RepositoryStorage repositoryStorage =
560 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
563 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(),
564 managedRepositoryContent );
566 catch ( RelocationException e )
568 String path = e.getPath();
569 log.debug( "Relocation to {}", path );
571 throw new BrowserRedirectException( contextPath + ( StringUtils.startsWith( path, "/" ) ? "" : "/" ) + path,
572 e.getRelocationType() );
574 catch ( XMLException e )
576 log.error( e.getMessage(), e );
577 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
581 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
582 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
583 ManagedRepository managedRepository )
586 DavResource resource = null;
587 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
589 // Maven Centric part ask evaluation if -SNAPSHOT
590 String path = evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() );
591 if ( path.startsWith( "/" ) )
593 path = path.substring( 1 );
595 LogicalResource logicalResource = new LogicalResource( path );
596 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
598 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
599 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
600 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
602 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
604 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
606 // force a resource not found
607 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
611 if ( !resource.isCollection() )
613 boolean previouslyExisted = resourceFile.exists();
615 // Attempt to fetch the resource from any defined proxy.
617 fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
619 // At this point the incoming request can either be in default or
620 // legacy layout format.
623 // Perform an adjustment of the resource to the managed
624 // repository expected path.
625 String localResourcePath =
626 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
627 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
629 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
630 managedRepositoryContent.getRepository(),
631 request.getRemoteAddr(), activePrincipal,
632 request.getDavSession(), archivaLocator, this, mimeTypes,
633 auditListeners, scheduler, fileLockManager );
635 catch ( LayoutException e )
637 if ( !resourceFile.exists() )
639 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
645 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
648 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
649 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
651 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
652 logicalResource.getPath(), event, activePrincipal );
655 if ( !resourceFile.exists() )
657 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
663 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
665 String resourcePath = logicalResource.getPath();
667 // check if target repo is enabled for releases
668 // we suppose that release-artifacts can be deployed only to repos enabled for releases
669 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
670 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
672 ArtifactReference artifact = null;
675 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
677 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
679 // check if artifact already exists and if artifact re-deployment to the repository is allowed
680 if ( managedRepositoryContent.hasContent( artifact )
681 && managedRepositoryContent.getRepository().isBlockRedeployments() )
683 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
684 managedRepositoryContent.getId() );
685 throw new DavException( HttpServletResponse.SC_CONFLICT,
686 "Overwriting released artifacts is not allowed." );
690 catch ( LayoutException e )
692 log.warn( "Artifact path '{}' is invalid.", resourcePath );
697 * Create parent directories that don't exist when writing a file This actually makes this
698 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
699 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
700 * create the collections themselves.
703 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
704 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
706 if ( !destDir.exists() )
709 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
711 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
714 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
715 AuditEvent.CREATE_DIR, activePrincipal );
723 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
726 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
728 ManagedRepositoryContent managedRepositoryContent;
731 managedRepositoryContent =
732 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
734 catch ( RepositoryNotFoundException e )
736 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
737 "Invalid repository: " + archivaLocator.getRepositoryId() );
739 catch ( RepositoryException e )
741 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
744 DavResource resource = null;
747 String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
748 archivaLocator.getRepositoryId() ), false );
749 if ( logicalResource.startsWith( "/" ) )
751 logicalResource = logicalResource.substring( 1 );
753 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
754 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
755 managedRepositoryContent.getRepository(), davSession, archivaLocator,
756 this, mimeTypes, auditListeners, scheduler, fileLockManager );
758 resource.addLockManager( lockManager );
760 catch ( RepositoryAdminException e )
762 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
767 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
768 LogicalResource resource )
771 String path = resource.getPath();
772 if ( repositoryRequest.isSupportFile( path ) )
774 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
776 return ( proxiedFile != null );
779 // Is it a Metadata resource?
780 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
782 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
785 // Is it an Archetype Catalog?
786 if ( repositoryRequest.isArchetypeCatalog( path ) )
788 // FIXME we must implement a merge of remote archetype catalog from remote servers.
789 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
791 return ( proxiedFile != null );
794 // Not any of the above? Then it's gotta be an artifact reference.
797 // Get the artifact reference in a layout neutral way.
798 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
800 if ( artifact != null )
802 String repositoryLayout = managedRepository.getRepository().getLayout();
804 RepositoryStorage repositoryStorage =
805 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
806 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
808 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
810 resource.setPath( managedRepository.toPath( artifact ) );
812 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
813 artifact.getVersion() );
815 return ( proxiedFile != null );
818 catch ( LayoutException e )
822 catch ( ProxyDownloadException e )
824 log.error( e.getMessage(), e );
825 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
826 "Unable to fetch artifact resource." );
833 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
836 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
837 event.setRemoteIP( remoteIP );
839 for ( AuditListener listener : auditListeners )
841 listener.auditEvent( event );
846 public void addAuditListener( AuditListener listener )
848 this.auditListeners.add( listener );
852 public void clearAuditListeners()
854 this.auditListeners.clear();
858 public void removeAuditListener( AuditListener listener )
860 this.auditListeners.remove( listener );
863 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
865 // [MRM-503] - Metadata file need Pragma:no-cache response
867 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || ( resource instanceof ArchivaDavResource
868 && ( ArchivaDavResource.class.cast( resource ).getLocalResource().isDirectory() ) ) )
870 response.setHeader( "Pragma", "no-cache" );
871 response.setHeader( "Cache-Control", "no-cache" );
872 response.setDateHeader( "Last-Modified", new Date().getTime() );
874 // if the resource is a directory don't cache it as new groupId deployed will be available
875 // without need of refreshing browser
876 else if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || (
877 resource instanceof ArchivaVirtualDavResource && ( new File(
878 ArchivaVirtualDavResource.class.cast( resource ).getLogicalResource() ).isDirectory() ) ) )
880 response.setHeader( "Pragma", "no-cache" );
881 response.setHeader( "Cache-Control", "no-cache" );
882 response.setDateHeader( "Last-Modified", new Date().getTime() );
886 // We need to specify this so connecting wagons can work correctly
887 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
889 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
892 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
895 if ( !( locator instanceof ArchivaDavResourceLocator ) )
897 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
898 "Locator does not implement RepositoryLocator" );
902 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
904 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
907 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
909 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
910 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
912 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
914 return archivaLocator;
917 private static class LogicalResource
921 public LogicalResource( String path )
926 public String getPath()
931 public void setPath( String path )
937 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
942 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
943 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
945 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
947 WebdavMethodUtil.getMethodPermission(
948 request.getMethod() )
951 catch ( AuthenticationException e )
953 // safety check for MRM-911
954 String guest = UserManager.GUEST_USERNAME;
957 if ( servletAuth.isAuthorized( guest,
958 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
959 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
964 catch ( UnauthorizedException ae )
966 throw new UnauthorizedDavException( repositoryId,
967 "You are not authenticated and authorized to access any repository." );
970 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
972 catch ( MustChangePasswordException e )
974 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
976 catch ( AccountLockedException e )
978 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
980 catch ( AuthorizationException e )
982 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
983 "Fatal Authorization Subsystem Error." );
985 catch ( UnauthorizedException e )
987 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
991 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
992 ArchivaDavResourceLocator locator,
993 RepositoryGroupConfiguration repositoryGroupConfiguration )
994 throws DavException, RepositoryAdminException
996 if ( repositoryGroupConfiguration.getRepositories() == null
997 || repositoryGroupConfiguration.getRepositories().isEmpty() )
1000 new File( System.getProperty( "appserver.base" ), "groups/" + repositoryGroupConfiguration.getId() );
1002 return new ArchivaDavResource( file.getPath(), "groups/" + repositoryGroupConfiguration.getId(), null,
1003 request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler,
1006 List<File> mergedRepositoryContents = new ArrayList<>();
1007 // multiple repo types so we guess they are all the same type
1008 // so use the first one
1009 // FIXME add a method with group in the repository storage
1010 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 0 );
1012 String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
1013 if ( path.startsWith( "/" ) )
1015 path = path.substring( 1 );
1017 LogicalResource logicalResource = new LogicalResource( path );
1020 // if the current user logged in has permission to any of the repositories, allow user to
1021 // browse the repo group but displaying only the repositories which the user has permission to access.
1022 // otherwise, prompt for authentication.
1024 String activePrincipal = getActivePrincipal( request );
1026 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1029 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1034 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1036 File mergedRepoDir =
1037 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1038 mergedRepositoryContents.add( mergedRepoDir );
1042 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1044 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1045 repositoryGroupConfiguration.getId() + "/"
1046 + repositoryGroupConfiguration.getMergedIndexPath()
1048 if ( !tmpDirectory.exists() )
1050 synchronized ( tmpDirectory.getAbsolutePath() )
1052 if ( !tmpDirectory.exists() )
1054 tmpDirectory.mkdirs();
1058 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1060 for ( String repository : repositories )
1062 ManagedRepositoryContent managedRepository = null;
1066 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1068 catch ( RepositoryNotFoundException e )
1070 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1071 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1073 catch ( RepositoryException e )
1075 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1076 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1079 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1080 if ( resourceFile.exists() )
1082 // in case of group displaying index directory doesn't have sense !!
1083 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1084 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1086 if ( !new File( repoIndexDirectory ).isAbsolute() )
1088 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1089 StringUtils.isEmpty( repoIndexDirectory )
1091 : repoIndexDirectory
1092 ).getAbsolutePath();
1095 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1097 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1098 ".indexer" ).getAbsolutePath();
1101 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1102 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1104 // for prompted authentication
1105 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1109 if ( isAuthorized( request, repository ) )
1111 mergedRepositoryContents.add( resourceFile );
1112 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1115 catch ( DavException e )
1117 // TODO: review exception handling
1119 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1120 activePrincipal, e.getMessage() );
1127 // for the current user logged in
1130 if ( servletAuth.isAuthorized( activePrincipal, repository,
1131 WebdavMethodUtil.getMethodPermission(
1132 request.getMethod() )
1135 mergedRepositoryContents.add( resourceFile );
1136 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1139 catch ( UnauthorizedException e )
1141 // TODO: review exception handling
1143 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1144 activePrincipal, e.getMessage() );
1155 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1158 ArchivaVirtualDavResource resource =
1159 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1162 // compatibility with MRM-440 to ensure browsing the repository group works ok
1163 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1165 throw new BrowserRedirectException( resource.getHref() );
1171 protected String getActivePrincipal( DavServletRequest request )
1173 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1174 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1178 * Check if the current user is authorized to access any of the repos
1181 * @param repositories
1182 * @param activePrincipal
1185 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1187 // when no repositories configured it's impossible to browse nothing !
1188 // at least make possible to see nothing :-)
1189 if ( repositories == null || repositories.isEmpty() )
1194 boolean allow = false;
1196 // if securitySession != null, it means that the user was prompted for authentication
1197 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1199 for ( String repository : repositories )
1203 if ( isAuthorized( request, repository ) )
1209 catch ( DavException e )
1217 for ( String repository : repositories )
1221 if ( servletAuth.isAuthorized( activePrincipal, repository,
1222 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1228 catch ( UnauthorizedException e )
1238 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1239 throws RepositoryMetadataException, DigesterException, IOException
1241 File outputFile = new File( outputFilename );
1242 if ( outputFile.exists() )
1244 FileUtils.deleteQuietly( outputFile );
1247 outputFile.getParentFile().mkdirs();
1248 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1250 createChecksumFile( outputFilename, digestSha1 );
1251 createChecksumFile( outputFilename, digestMd5 );
1256 private void createChecksumFile( String path, Digester digester )
1257 throws DigesterException, IOException
1259 File checksumFile = new File( path + digester.getFilenameExtension() );
1260 if ( !checksumFile.exists() )
1262 FileUtils.deleteQuietly( checksumFile );
1263 checksum.createChecksum( new File( path ), digester );
1265 else if ( !checksumFile.isFile() )
1267 log.error( "Checksum file is not a file." );
1271 private boolean isProjectReference( String requestedResource )
1275 metadataTools.toVersionedReference( requestedResource );
1278 catch ( RepositoryMetadataException re )
1284 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1285 DavServletRequest request,
1286 RepositoryGroupConfiguration repositoryGroupConfiguration )
1292 HttpSession session = request.getSession();
1294 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1295 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1296 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1297 if ( temporaryGroupIndexMap == null )
1299 temporaryGroupIndexMap = new HashMap<>();
1302 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1304 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1306 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1307 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1309 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1310 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1311 indexMerger.cleanTemporaryGroupIndex( tmp );
1315 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1316 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1317 return tmp.getDirectory();
1321 Set<String> authzRepos = new HashSet<String>();
1323 String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1325 for ( String repository : repositories )
1329 if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1331 authzRepos.add( repository );
1332 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1335 catch ( UnauthorizedException e )
1337 // TODO: review exception handling
1339 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1343 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1344 repositoryGroupConfiguration.getId(), authzRepos );
1346 File tempRepoFile = Files.createTempDir();
1347 tempRepoFile.deleteOnExit();
1349 IndexMergerRequest indexMergerRequest =
1350 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1351 repositoryGroupConfiguration.getMergedIndexPath(),
1352 repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory(
1353 tempRepoFile ).temporary( true );
1355 MergedRemoteIndexesTaskRequest taskRequest =
1356 new MergedRemoteIndexesTaskRequest( indexMergerRequest, indexMerger );
1358 MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1360 IndexingContext indexingContext = job.execute().getIndexingContext();
1362 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1363 TemporaryGroupIndex temporaryGroupIndex =
1364 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1365 repositoryGroupConfiguration.getMergedIndexTtl() ).setCreationTime(
1366 new Date().getTime() );
1367 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1368 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1369 temporaryGroupIndexMap );
1370 return mergedRepoDir;
1372 catch ( RepositoryAdminException e )
1374 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1376 catch ( IndexMergerException e )
1378 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1383 public void setServletAuth( ServletAuthenticator servletAuth )
1385 this.servletAuth = servletAuth;
1388 public void setHttpAuth( HttpAuthenticator httpAuth )
1390 this.httpAuth = httpAuth;
1393 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1395 this.scheduler = scheduler;
1398 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1400 this.archivaConfiguration = archivaConfiguration;
1403 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1405 this.repositoryFactory = repositoryFactory;
1408 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1410 this.repositoryRequest = repositoryRequest;
1413 public void setConnectors( RepositoryProxyConnectors connectors )
1415 this.connectors = connectors;
1418 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1420 return remoteRepositoryAdmin;
1423 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1425 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1428 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1430 return managedRepositoryAdmin;
1433 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1435 this.managedRepositoryAdmin = managedRepositoryAdmin;