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 org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.beans.ManagedRepository;
24 import org.apache.archiva.admin.model.beans.RemoteRepository;
25 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
26 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
27 import org.apache.archiva.audit.Auditable;
28 import org.apache.archiva.common.filelock.FileLockManager;
29 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
30 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
31 import org.apache.archiva.common.utils.PathUtil;
32 import org.apache.archiva.common.utils.VersionUtil;
33 import org.apache.archiva.configuration.ArchivaConfiguration;
34 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
35 import org.apache.archiva.indexer.merger.IndexMerger;
36 import org.apache.archiva.indexer.merger.IndexMergerException;
37 import org.apache.archiva.indexer.merger.IndexMergerRequest;
38 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTask;
39 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTaskRequest;
40 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
41 import org.apache.archiva.indexer.search.RepositorySearch;
42 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
43 import org.apache.archiva.metadata.model.facets.AuditEvent;
44 import org.apache.archiva.metadata.repository.storage.RelocationException;
45 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
46 import org.apache.archiva.model.ArchivaRepositoryMetadata;
47 import org.apache.archiva.model.ArtifactReference;
48 import org.apache.archiva.policies.ProxyDownloadException;
49 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
50 import org.apache.archiva.proxy.model.ProxyFetchResult;
51 import org.apache.archiva.redback.authentication.AuthenticationException;
52 import org.apache.archiva.redback.authentication.AuthenticationResult;
53 import org.apache.archiva.redback.authorization.AuthorizationException;
54 import org.apache.archiva.redback.authorization.UnauthorizedException;
55 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
56 import org.apache.archiva.redback.policy.AccountLockedException;
57 import org.apache.archiva.redback.policy.MustChangePasswordException;
58 import org.apache.archiva.redback.system.SecuritySession;
59 import org.apache.archiva.redback.users.User;
60 import org.apache.archiva.redback.users.UserManager;
61 import org.apache.archiva.repository.ManagedRepositoryContent;
62 import org.apache.archiva.repository.RepositoryContentFactory;
63 import org.apache.archiva.repository.RepositoryException;
64 import org.apache.archiva.repository.RepositoryNotFoundException;
65 import org.apache.archiva.repository.content.legacy.LegacyPathParser;
66 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
67 import org.apache.archiva.repository.events.AuditListener;
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.nio.file.Files;
110 import java.util.ArrayList;
111 import java.util.Date;
112 import java.util.HashMap;
113 import java.util.HashSet;
114 import java.util.List;
115 import java.util.Map;
116 import java.util.Set;
121 @Service( "davResourceFactory#archiva" )
122 public class ArchivaDavResourceFactory
123 implements DavResourceFactory, Auditable
125 private static final String PROXIED_SUFFIX = " (proxied)";
127 private static final String HTTP_PUT_METHOD = "PUT";
129 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
132 private List<AuditListener> auditListeners = new ArrayList<>();
135 private RepositoryContentFactory repositoryFactory;
137 private RepositoryRequest repositoryRequest;
140 @Named( value = "repositoryProxyConnectors#default" )
141 private RepositoryProxyConnectors connectors;
144 private MetadataTools metadataTools;
147 private MimeTypes mimeTypes;
149 private ArchivaConfiguration archivaConfiguration;
152 private ServletAuthenticator servletAuth;
155 @Named( value = "httpAuthenticator#basic" )
156 private HttpAuthenticator httpAuth;
159 private RemoteRepositoryAdmin remoteRepositoryAdmin;
162 private ManagedRepositoryAdmin managedRepositoryAdmin;
165 private IndexMerger indexMerger;
168 private RepositorySearch repositorySearch;
171 * Lock Manager - use simple implementation from JackRabbit
173 private final LockManager lockManager = new SimpleLockManager();
175 private ChecksumFile checksum;
177 private Digester digestSha1;
179 private Digester digestMd5;
182 @Named( value = "archivaTaskScheduler#repository" )
183 private RepositoryArchivaTaskScheduler scheduler;
186 @Named( value = "fileLockManager#default" )
187 private FileLockManager fileLockManager;
189 private ApplicationContext applicationContext;
192 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
193 ArchivaConfiguration archivaConfiguration )
194 throws PlexusSisuBridgeException
196 this.archivaConfiguration = archivaConfiguration;
197 this.applicationContext = applicationContext;
198 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
200 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
201 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
203 // TODO remove this hard dependency on maven !!
204 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
208 public void initialize()
214 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
215 final DavServletResponse response )
218 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
220 RepositoryGroupConfiguration repoGroupConfig =
221 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
223 String activePrincipal = getActivePrincipal( request );
225 List<String> resourcesInAbsolutePath = new ArrayList<>();
227 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
228 DavResource resource;
229 if ( repoGroupConfig != null )
233 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
234 "Write method not allowed for repository groups." );
237 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
239 // handle browse requests for virtual repos
240 if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
244 DavResource davResource =
245 getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
248 setHeaders( response, locator, davResource, true );
253 catch ( RepositoryAdminException e )
255 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
260 // make a copy to avoid potential concurrent modifications (eg. by configuration)
261 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
263 List<String> repositories = new ArrayList<>( repoGroupConfig.getRepositories() );
264 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
265 resourcesInAbsolutePath, repoGroupConfig );
273 RemoteRepository remoteRepository =
274 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
276 if ( remoteRepository != null )
278 String logicalResource = getLogicalResource( archivaLocator, null, false );
279 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
280 File resourceFile = StringUtils.equals( logicalResource, "/" )
281 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
282 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
283 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), //
284 locator.getResourcePath(), //
286 request.getRemoteAddr(), //
288 request.getDavSession(), //
295 setHeaders( response, locator, resource, false );
299 catch ( RepositoryAdminException e )
301 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
302 archivaLocator.getRepositoryId(), e.getMessage() );
305 ManagedRepositoryContent managedRepositoryContent = null;
309 managedRepositoryContent =
310 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
312 catch ( RepositoryNotFoundException e )
314 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
315 "Invalid repository: " + archivaLocator.getRepositoryId() );
317 catch ( RepositoryException e )
319 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
322 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
326 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
327 managedRepositoryAdmin.getManagedRepository(
328 archivaLocator.getRepositoryId() ) );
330 String logicalResource = getLogicalResource( archivaLocator, null, false );
331 resourcesInAbsolutePath.add(
332 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
335 catch ( RepositoryAdminException e )
337 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
341 String requestedResource = request.getRequestURI();
343 // MRM-872 : merge all available metadata
344 // merge metadata only when requested via the repo group
345 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
346 requestedResource ) ) && repoGroupConfig != null )
348 // this should only be at the project level not version level!
349 if ( isProjectReference( requestedResource ) )
352 ArchivaDavResource res = (ArchivaDavResource) resource;
354 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
356 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
358 // for MRM-872 handle checksums of the merged metadata files
359 if ( repositoryRequest.isSupportFile( requestedResource ) )
361 File metadataChecksum =
362 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
364 if ( metadataChecksum.exists() )
366 LogicalResource logicalResource =
367 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
370 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
371 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
372 archivaLocator, this, mimeTypes, auditListeners, scheduler,
378 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
380 // merge the metadata of all repos under group
381 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
382 for ( String resourceAbsPath : resourcesInAbsolutePath )
386 File metadataFile = new File( resourceAbsPath );
387 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
388 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
390 catch ( XMLException e )
392 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
393 "Error occurred while reading metadata file." );
395 catch ( RepositoryMetadataException r )
397 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
398 "Error occurred while merging metadata file." );
404 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
406 LogicalResource logicalResource =
407 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
410 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
411 request.getRemoteAddr(), activePrincipal,
412 request.getDavSession(), archivaLocator, this, mimeTypes,
413 auditListeners, scheduler, fileLockManager );
415 catch ( RepositoryMetadataException r )
417 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
418 "Error occurred while writing metadata file." );
420 catch ( IOException ie )
422 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
423 "Error occurred while generating checksum files." );
425 catch ( DigesterException de )
427 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
428 "Error occurred while generating checksum files."
436 setHeaders( response, locator, resource, false );
438 // compatibility with MRM-440 to ensure browsing the repository works ok
439 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
441 throw new BrowserRedirectException( resource.getHref() );
443 resource.addLockManager( lockManager );
447 private DavResource processRepositoryGroup( final DavServletRequest request,
448 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
449 String activePrincipal, List<String> resourcesInAbsolutePath,
450 RepositoryGroupConfiguration repoGroupConfig )
453 DavResource resource = null;
454 List<DavException> storedExceptions = new ArrayList<>();
456 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
458 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
460 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
462 // we are in the case of index file request
463 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
464 File temporaryIndexDirectory =
465 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
467 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
468 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
469 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
470 archivaLocator, this, mimeTypes, auditListeners, scheduler,
476 for ( String repositoryId : repositories )
478 ManagedRepositoryContent managedRepositoryContent;
481 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
483 catch ( RepositoryNotFoundException e )
485 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
487 catch ( RepositoryException e )
489 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
494 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
495 DavResource updatedResource =
496 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
498 if ( resource == null )
500 resource = updatedResource;
503 String logicalResource = getLogicalResource( archivaLocator, null, false );
504 if ( logicalResource.endsWith( "/" ) )
506 logicalResource = logicalResource.substring( 1 );
508 resourcesInAbsolutePath.add(
509 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
511 catch ( DavException e )
513 storedExceptions.add( e );
515 catch ( RepositoryAdminException e )
517 storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
521 if ( resource == null )
523 if ( !storedExceptions.isEmpty() )
526 for ( DavException e : storedExceptions )
528 if ( 401 == e.getErrorCode() )
534 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
538 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
544 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
545 boolean useOrigResourcePath )
547 // FIXME remove this hack
548 // but currently managedRepository can be null in case of group
549 String layout = managedRepository == null ? new ManagedRepository().getLayout() : managedRepository.getLayout();
550 RepositoryStorage repositoryStorage =
551 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
552 String path = repositoryStorage.getFilePath(
553 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
555 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
556 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
561 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator, //
562 ManagedRepositoryContent managedRepositoryContent, //
566 String layout = managedRepositoryContent.getRepository() == null
567 ? new ManagedRepository().getLayout()
568 : managedRepositoryContent.getRepository().getLayout();
569 RepositoryStorage repositoryStorage =
570 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
573 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(), //
574 managedRepositoryContent );
576 catch ( RelocationException e )
578 String path = e.getPath();
579 log.debug( "Relocation to {}", path );
581 throw new BrowserRedirectException( contextPath + ( StringUtils.startsWith( path, "/" ) ? "" : "/" ) + path,
582 e.getRelocationType() );
584 catch ( XMLException e )
586 log.error( e.getMessage(), e );
587 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
591 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
592 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
593 ManagedRepository managedRepository )
596 DavResource resource = null;
597 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
599 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
600 // Maven Centric part ask evaluation if -SNAPSHOT
601 // MRM-1846 test if read method to prevent issue with maven 2.2.1 and uniqueVersion false
603 String path = readMethod
604 ? evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() )
605 : getLogicalResource( archivaLocator, managedRepository, false );
606 if ( path.startsWith( "/" ) )
608 path = path.substring( 1 );
610 LogicalResource logicalResource = new LogicalResource( path );
611 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
613 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
614 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
615 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
617 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
619 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
621 // force a resource not found
622 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
626 if ( !resource.isCollection() )
628 boolean previouslyExisted = resourceFile.exists();
630 boolean fromProxy = fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
632 // At this point the incoming request can either be in default or
633 // legacy layout format.
636 // Perform an adjustment of the resource to the managed
637 // repository expected path.
638 String localResourcePath =
639 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
640 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
642 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
643 managedRepositoryContent.getRepository(),
644 request.getRemoteAddr(), activePrincipal,
645 request.getDavSession(), archivaLocator, this, mimeTypes,
646 auditListeners, scheduler, fileLockManager );
648 catch ( LayoutException e )
650 if ( !resourceFile.exists() )
652 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
658 String action = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
661 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
662 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
664 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
665 logicalResource.getPath(), action, activePrincipal );
668 if ( !resourceFile.exists() )
670 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
676 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
678 String resourcePath = logicalResource.getPath();
680 // check if target repo is enabled for releases
681 // we suppose that release-artifacts can be deployed only to repos enabled for releases
682 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
683 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
685 ArtifactReference artifact = null;
688 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
690 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
692 // check if artifact already exists and if artifact re-deployment to the repository is allowed
693 if ( managedRepositoryContent.hasContent( artifact )
694 && managedRepositoryContent.getRepository().isBlockRedeployments() )
696 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
697 managedRepositoryContent.getId() );
698 throw new DavException( HttpServletResponse.SC_CONFLICT,
699 "Overwriting released artifacts is not allowed." );
703 catch ( LayoutException e )
705 log.warn( "Artifact path '{}' is invalid.", resourcePath );
710 * Create parent directories that don't exist when writing a file This actually makes this
711 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
712 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
713 * create the collections themselves.
716 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
717 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
719 if ( !destDir.exists() )
722 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
724 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
727 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
728 AuditEvent.CREATE_DIR, activePrincipal );
736 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
739 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
741 ManagedRepositoryContent managedRepositoryContent;
744 managedRepositoryContent =
745 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
747 catch ( RepositoryNotFoundException e )
749 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
750 "Invalid repository: " + archivaLocator.getRepositoryId() );
752 catch ( RepositoryException e )
754 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
757 DavResource resource = null;
760 String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
761 archivaLocator.getRepositoryId() ), false );
762 if ( logicalResource.startsWith( "/" ) )
764 logicalResource = logicalResource.substring( 1 );
766 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
767 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
768 managedRepositoryContent.getRepository(), davSession, archivaLocator,
769 this, mimeTypes, auditListeners, scheduler, fileLockManager );
771 resource.addLockManager( lockManager );
773 catch ( RepositoryAdminException e )
775 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
780 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
781 LogicalResource resource )
784 String path = resource.getPath();
785 if ( repositoryRequest.isSupportFile( path ) )
787 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
789 return ( proxiedFile != null );
792 // Is it a Metadata resource?
793 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
795 return connectors.fetchMetadataFromProxies( managedRepository, path ).isModified();
798 // Is it an Archetype Catalog?
799 if ( repositoryRequest.isArchetypeCatalog( path ) )
801 // FIXME we must implement a merge of remote archetype catalog from remote servers.
802 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
804 return ( proxiedFile != null );
807 // Not any of the above? Then it's gotta be an artifact reference.
810 // Get the artifact reference in a layout neutral way.
811 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
813 if ( artifact != null )
815 String repositoryLayout = managedRepository.getRepository().getLayout();
817 RepositoryStorage repositoryStorage =
818 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
819 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
821 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
823 resource.setPath( managedRepository.toPath( artifact ) );
825 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
826 artifact.getVersion() );
828 return ( proxiedFile != null );
831 catch ( LayoutException e )
835 catch ( ProxyDownloadException e )
837 log.error( e.getMessage(), e );
838 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
839 "Unable to fetch artifact resource." );
846 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
849 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
850 event.setRemoteIP( remoteIP );
852 for ( AuditListener listener : auditListeners )
854 listener.auditEvent( event );
859 public void addAuditListener( AuditListener listener )
861 this.auditListeners.add( listener );
865 public void clearAuditListeners()
867 this.auditListeners.clear();
871 public void removeAuditListener( AuditListener listener )
873 this.auditListeners.remove( listener );
876 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource,
879 // [MRM-503] - Metadata file need Pragma:no-cache response
881 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || ( resource instanceof ArchivaDavResource
882 && ( ArchivaDavResource.class.cast( resource ).getLocalResource().isDirectory() ) ) )
884 response.setHeader( "Pragma", "no-cache" );
885 response.setHeader( "Cache-Control", "no-cache" );
886 response.setDateHeader( "Last-Modified", new Date().getTime() );
888 // if the resource is a directory don't cache it as new groupId deployed will be available
889 // without need of refreshing browser
890 else if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || (
891 resource instanceof ArchivaVirtualDavResource && ( new File(
892 ArchivaVirtualDavResource.class.cast( resource ).getLogicalResource() ).isDirectory() ) ) )
894 response.setHeader( "Pragma", "no-cache" );
895 response.setHeader( "Cache-Control", "no-cache" );
896 response.setDateHeader( "Last-Modified", new Date().getTime() );
900 if ( resource instanceof ArchivaVirtualDavResource )
902 //MRM-1854 here we have a directory so force "Last-Modified"
903 response.setDateHeader( "Last-Modified", new Date().getTime() );
908 // We need to specify this so connecting wagons can work correctly
909 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
911 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
914 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
917 if ( !( locator instanceof ArchivaDavResourceLocator ) )
919 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
920 "Locator does not implement RepositoryLocator" );
924 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
926 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
929 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
931 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
932 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
934 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
936 return archivaLocator;
939 private static class LogicalResource
943 public LogicalResource( String path )
948 public String getPath()
953 public void setPath( String path )
959 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
964 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
965 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
967 return servletAuth.isAuthenticated( request, result ) //
968 && servletAuth.isAuthorized( request, securitySession, repositoryId, //
969 WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
971 catch ( AuthenticationException e )
973 // safety check for MRM-911
974 String guest = UserManager.GUEST_USERNAME;
977 if ( servletAuth.isAuthorized( guest,
978 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
979 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
984 catch ( UnauthorizedException ae )
986 throw new UnauthorizedDavException( repositoryId,
987 "You are not authenticated and authorized to access any repository." );
990 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
992 catch ( MustChangePasswordException e )
994 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
996 catch ( AccountLockedException e )
998 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
1000 catch ( AuthorizationException e )
1002 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1003 "Fatal Authorization Subsystem Error." );
1005 catch ( UnauthorizedException e )
1007 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
1011 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
1012 ArchivaDavResourceLocator locator,
1013 RepositoryGroupConfiguration repositoryGroupConfiguration )
1014 throws DavException, RepositoryAdminException
1016 if ( repositoryGroupConfiguration.getRepositories() == null
1017 || repositoryGroupConfiguration.getRepositories().isEmpty() )
1020 new File( System.getProperty( "appserver.base" ), "groups/" + repositoryGroupConfiguration.getId() );
1022 return new ArchivaDavResource( file.getPath(), "groups/" + repositoryGroupConfiguration.getId(), null,
1023 request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler,
1026 List<File> mergedRepositoryContents = new ArrayList<>();
1027 // multiple repo types so we guess they are all the same type
1028 // so use the first one
1029 // FIXME add a method with group in the repository storage
1030 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 0 );
1032 String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
1033 if ( path.startsWith( "/" ) )
1035 path = path.substring( 1 );
1037 LogicalResource logicalResource = new LogicalResource( path );
1040 // if the current user logged in has permission to any of the repositories, allow user to
1041 // browse the repo group but displaying only the repositories which the user has permission to access.
1042 // otherwise, prompt for authentication.
1044 String activePrincipal = getActivePrincipal( request );
1046 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1049 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1054 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1056 File mergedRepoDir =
1057 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1058 mergedRepositoryContents.add( mergedRepoDir );
1062 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1064 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1065 repositoryGroupConfiguration.getId() + "/"
1066 + repositoryGroupConfiguration.getMergedIndexPath() );
1067 if ( !tmpDirectory.exists() )
1069 synchronized ( tmpDirectory.getAbsolutePath() )
1071 if ( !tmpDirectory.exists() )
1073 tmpDirectory.mkdirs();
1077 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1079 for ( String repository : repositories )
1081 ManagedRepositoryContent managedRepository = null;
1085 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1087 catch ( RepositoryNotFoundException e )
1089 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1090 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1092 catch ( RepositoryException e )
1094 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1095 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1098 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1099 if ( resourceFile.exists() )
1101 // in case of group displaying index directory doesn't have sense !!
1102 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1103 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1105 if ( !new File( repoIndexDirectory ).isAbsolute() )
1107 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1108 StringUtils.isEmpty( repoIndexDirectory )
1110 : repoIndexDirectory ).getAbsolutePath();
1113 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1115 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1116 ".indexer" ).getAbsolutePath();
1119 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1120 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1122 // for prompted authentication
1123 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1127 if ( isAuthorized( request, repository ) )
1129 mergedRepositoryContents.add( resourceFile );
1130 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1133 catch ( DavException e )
1135 // TODO: review exception handling
1137 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1138 activePrincipal, e.getMessage() );
1145 // for the current user logged in
1148 if ( servletAuth.isAuthorized( activePrincipal, repository,
1149 WebdavMethodUtil.getMethodPermission(
1150 request.getMethod() ) ) )
1152 mergedRepositoryContents.add( resourceFile );
1153 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1156 catch ( UnauthorizedException e )
1158 // TODO: review exception handling
1160 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1161 activePrincipal, e.getMessage() );
1172 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1175 ArchivaVirtualDavResource resource =
1176 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1179 // compatibility with MRM-440 to ensure browsing the repository group works ok
1180 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1182 throw new BrowserRedirectException( resource.getHref() );
1188 protected String getActivePrincipal( DavServletRequest request )
1190 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1191 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1195 * Check if the current user is authorized to access any of the repos
1198 * @param repositories
1199 * @param activePrincipal
1202 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1204 // when no repositories configured it's impossible to browse nothing !
1205 // at least make possible to see nothing :-)
1206 if ( repositories == null || repositories.isEmpty() )
1211 boolean allow = false;
1213 // if securitySession != null, it means that the user was prompted for authentication
1214 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1216 for ( String repository : repositories )
1220 if ( isAuthorized( request, repository ) )
1226 catch ( DavException e )
1234 for ( String repository : repositories )
1238 if ( servletAuth.isAuthorized( activePrincipal, repository,
1239 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1245 catch ( UnauthorizedException e )
1255 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1256 throws RepositoryMetadataException, DigesterException, IOException
1258 File outputFile = new File( outputFilename );
1259 if ( outputFile.exists() )
1261 FileUtils.deleteQuietly( outputFile );
1264 outputFile.getParentFile().mkdirs();
1265 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1267 createChecksumFile( outputFilename, digestSha1 );
1268 createChecksumFile( outputFilename, digestMd5 );
1273 private void createChecksumFile( String path, Digester digester )
1274 throws DigesterException, IOException
1276 File checksumFile = new File( path + digester.getFilenameExtension() );
1277 if ( !checksumFile.exists() )
1279 FileUtils.deleteQuietly( checksumFile );
1280 checksum.createChecksum( new File( path ), digester );
1282 else if ( !checksumFile.isFile() )
1284 log.error( "Checksum file is not a file." );
1288 private boolean isProjectReference( String requestedResource )
1292 metadataTools.toVersionedReference( requestedResource );
1295 catch ( RepositoryMetadataException re )
1301 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1302 DavServletRequest request,
1303 RepositoryGroupConfiguration repositoryGroupConfiguration )
1309 HttpSession session = request.getSession();
1311 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1312 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1313 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1314 if ( temporaryGroupIndexMap == null )
1316 temporaryGroupIndexMap = new HashMap<>();
1319 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1321 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1323 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1324 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1326 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1327 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1328 indexMerger.cleanTemporaryGroupIndex( tmp );
1332 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1333 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1334 return tmp.getDirectory();
1338 Set<String> authzRepos = new HashSet<String>();
1340 String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1342 for ( String repository : repositories )
1346 if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1348 authzRepos.add( repository );
1349 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1352 catch ( UnauthorizedException e )
1354 // TODO: review exception handling
1356 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1360 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1361 repositoryGroupConfiguration.getId(), authzRepos );
1363 File tempRepoFile = Files.createTempDirectory( "temp" ).toFile();
1364 tempRepoFile.deleteOnExit();
1366 IndexMergerRequest indexMergerRequest =
1367 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1368 repositoryGroupConfiguration.getMergedIndexPath(),
1369 repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory(
1370 tempRepoFile ).temporary( true );
1372 MergedRemoteIndexesTaskRequest taskRequest =
1373 new MergedRemoteIndexesTaskRequest( indexMergerRequest, indexMerger );
1375 MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1377 IndexingContext indexingContext = job.execute().getIndexingContext();
1379 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1380 TemporaryGroupIndex temporaryGroupIndex =
1381 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1382 repositoryGroupConfiguration.getMergedIndexTtl() ) //
1383 .setCreationTime( new Date().getTime() );
1384 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1385 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1386 temporaryGroupIndexMap );
1387 return mergedRepoDir;
1389 catch ( RepositoryAdminException e )
1391 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1393 catch ( IndexMergerException e )
1395 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1397 catch ( IOException e )
1399 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1404 public void setServletAuth( ServletAuthenticator servletAuth )
1406 this.servletAuth = servletAuth;
1409 public void setHttpAuth( HttpAuthenticator httpAuth )
1411 this.httpAuth = httpAuth;
1414 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1416 this.scheduler = scheduler;
1419 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1421 this.archivaConfiguration = archivaConfiguration;
1424 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1426 this.repositoryFactory = repositoryFactory;
1429 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1431 this.repositoryRequest = repositoryRequest;
1434 public void setConnectors( RepositoryProxyConnectors connectors )
1436 this.connectors = connectors;
1439 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1441 return remoteRepositoryAdmin;
1444 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1446 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1449 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1451 return managedRepositoryAdmin;
1454 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1456 this.managedRepositoryAdmin = managedRepositoryAdmin;