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<AuditListener>();
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()
212 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
213 final DavServletResponse response )
216 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
218 RepositoryGroupConfiguration repoGroupConfig =
219 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
221 String activePrincipal = getActivePrincipal( request );
223 List<String> resourcesInAbsolutePath = new ArrayList<String>();
225 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
226 DavResource resource;
227 if ( repoGroupConfig != null )
231 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
232 "Write method not allowed for repository groups." );
235 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
237 // handle browse requests for virtual repos
238 if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
242 return getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
245 catch ( RepositoryAdminException e )
247 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
252 // make a copy to avoid potential concurrent modifications (eg. by configuration)
253 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
255 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
256 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
257 resourcesInAbsolutePath, repoGroupConfig );
265 RemoteRepository remoteRepository =
266 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
268 if ( remoteRepository != null )
270 String logicalResource = getLogicalResource( archivaLocator, null, false );
271 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
272 File resourceFile = StringUtils.equals( logicalResource, "/" )
273 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
274 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
275 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
276 request.getRemoteAddr(), activePrincipal,
277 request.getDavSession(), archivaLocator, this, mimeTypes,
278 auditListeners, scheduler, fileLockManager );
279 setHeaders( response, locator, resource );
283 catch ( RepositoryAdminException e )
285 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
286 archivaLocator.getRepositoryId(), e.getMessage() );
289 ManagedRepositoryContent managedRepositoryContent = null;
293 managedRepositoryContent =
294 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
296 catch ( RepositoryNotFoundException e )
298 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
299 "Invalid repository: " + archivaLocator.getRepositoryId() );
301 catch ( RepositoryException e )
303 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
306 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
310 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
311 managedRepositoryAdmin.getManagedRepository(
312 archivaLocator.getRepositoryId() )
315 String logicalResource = getLogicalResource( archivaLocator, null, false );
316 resourcesInAbsolutePath.add(
317 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
320 catch ( RepositoryAdminException e )
322 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
326 String requestedResource = request.getRequestURI();
328 // MRM-872 : merge all available metadata
329 // merge metadata only when requested via the repo group
330 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
331 requestedResource ) ) && repoGroupConfig != null )
333 // this should only be at the project level not version level!
334 if ( isProjectReference( requestedResource ) )
337 ArchivaDavResource res = (ArchivaDavResource) resource;
339 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
341 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
343 // for MRM-872 handle checksums of the merged metadata files
344 if ( repositoryRequest.isSupportFile( requestedResource ) )
346 File metadataChecksum =
347 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
348 if ( metadataChecksum.exists() )
350 LogicalResource logicalResource =
351 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
354 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
355 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
356 archivaLocator, this, mimeTypes, auditListeners, scheduler,
362 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
364 // merge the metadata of all repos under group
365 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
366 for ( String resourceAbsPath : resourcesInAbsolutePath )
370 File metadataFile = new File( resourceAbsPath );
371 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
372 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
374 catch ( XMLException e )
376 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
377 "Error occurred while reading metadata file." );
379 catch ( RepositoryMetadataException r )
381 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
382 "Error occurred while merging metadata file." );
388 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
390 LogicalResource logicalResource =
391 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
394 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
395 request.getRemoteAddr(), activePrincipal,
396 request.getDavSession(), archivaLocator, this, mimeTypes,
397 auditListeners, scheduler, fileLockManager );
399 catch ( RepositoryMetadataException r )
401 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
402 "Error occurred while writing metadata file." );
404 catch ( IOException ie )
406 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
407 "Error occurred while generating checksum files." );
409 catch ( DigesterException de )
411 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
412 "Error occurred while generating checksum files." + de.getMessage()
420 setHeaders( response, locator, resource );
422 // compatibility with MRM-440 to ensure browsing the repository works ok
423 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
425 throw new BrowserRedirectException( resource.getHref() );
427 resource.addLockManager( lockManager );
431 private DavResource processRepositoryGroup( final DavServletRequest request,
432 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
433 String activePrincipal, List<String> resourcesInAbsolutePath,
434 RepositoryGroupConfiguration repoGroupConfig )
437 DavResource resource = null;
438 List<DavException> storedExceptions = new ArrayList<DavException>();
440 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
442 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
444 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
446 // we are in the case of index file request
447 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
448 File temporaryIndexDirectory =
449 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
451 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
452 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
453 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
454 archivaLocator, this, mimeTypes, auditListeners, scheduler,
460 for ( String repositoryId : repositories )
462 ManagedRepositoryContent managedRepositoryContent;
465 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
467 catch ( RepositoryNotFoundException e )
469 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
471 catch ( RepositoryException e )
473 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
478 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
479 DavResource updatedResource =
480 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
482 if ( resource == null )
484 resource = updatedResource;
487 String logicalResource = getLogicalResource( archivaLocator, null, false );
488 if ( logicalResource.endsWith( "/" ) )
490 logicalResource = logicalResource.substring( 1 );
492 resourcesInAbsolutePath.add(
493 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
495 catch ( DavException e )
497 storedExceptions.add( e );
499 catch ( RepositoryAdminException e )
501 storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
505 if ( resource == null )
507 if ( !storedExceptions.isEmpty() )
510 for ( DavException e : storedExceptions )
512 if ( 401 == e.getErrorCode() )
518 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
522 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
528 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
529 boolean useOrigResourcePath )
531 // FIXME remove this hack
532 // but currently managedRepository can be null in case of group
533 String layout = managedRepository == null ? new ManagedRepository().getLayout() : managedRepository.getLayout();
534 RepositoryStorage repositoryStorage =
535 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
536 String path = repositoryStorage.getFilePath(
537 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
539 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
540 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
545 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator,
546 ManagedRepositoryContent managedRepositoryContent, String contextPath )
549 String layout = managedRepositoryContent.getRepository() == null
550 ? new ManagedRepository().getLayout()
551 : managedRepositoryContent.getRepository().getLayout();
552 RepositoryStorage repositoryStorage =
553 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
556 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(),
557 managedRepositoryContent );
559 catch ( RelocationException e )
561 String path = e.getPath();
562 log.debug( "Relocation to {}", path );
564 throw new BrowserRedirectException( contextPath + ( StringUtils.startsWith( path, "/" ) ? "" : "/" ) + path,
565 e.getRelocationType() );
567 catch ( XMLException e )
569 log.error( e.getMessage(), e );
570 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
574 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
575 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
576 ManagedRepository managedRepository )
579 DavResource resource = null;
580 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
582 // Maven Centric part ask evaluation if -SNAPSHOT
583 String path = evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() );
584 if ( path.startsWith( "/" ) )
586 path = path.substring( 1 );
588 LogicalResource logicalResource = new LogicalResource( path );
589 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
591 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
592 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
593 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
595 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
597 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
599 // force a resource not found
600 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
604 if ( !resource.isCollection() )
606 boolean previouslyExisted = resourceFile.exists();
608 // Attempt to fetch the resource from any defined proxy.
610 fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
612 // At this point the incoming request can either be in default or
613 // legacy layout format.
616 // Perform an adjustment of the resource to the managed
617 // repository expected path.
618 String localResourcePath =
619 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
620 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
622 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
623 managedRepositoryContent.getRepository(),
624 request.getRemoteAddr(), activePrincipal,
625 request.getDavSession(), archivaLocator, this, mimeTypes,
626 auditListeners, scheduler, fileLockManager );
628 catch ( LayoutException e )
630 if ( !resourceFile.exists() )
632 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
638 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
641 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
642 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
644 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
645 logicalResource.getPath(), event, activePrincipal );
648 if ( !resourceFile.exists() )
650 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
656 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
658 String resourcePath = logicalResource.getPath();
660 // check if target repo is enabled for releases
661 // we suppose that release-artifacts can be deployed only to repos enabled for releases
662 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
663 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
665 ArtifactReference artifact = null;
668 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
670 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
672 // check if artifact already exists and if artifact re-deployment to the repository is allowed
673 if ( managedRepositoryContent.hasContent( artifact )
674 && managedRepositoryContent.getRepository().isBlockRedeployments() )
676 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
677 managedRepositoryContent.getId() );
678 throw new DavException( HttpServletResponse.SC_CONFLICT,
679 "Overwriting released artifacts is not allowed." );
683 catch ( LayoutException e )
685 log.warn( "Artifact path '{}' is invalid.", resourcePath );
690 * Create parent directories that don't exist when writing a file This actually makes this
691 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
692 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
693 * create the collections themselves.
696 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
697 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
699 if ( !destDir.exists() )
702 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
704 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
707 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
708 AuditEvent.CREATE_DIR, activePrincipal );
715 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
718 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
720 ManagedRepositoryContent managedRepositoryContent;
723 managedRepositoryContent =
724 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
726 catch ( RepositoryNotFoundException e )
728 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
729 "Invalid repository: " + archivaLocator.getRepositoryId() );
731 catch ( RepositoryException e )
733 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
736 DavResource resource = null;
739 String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
740 archivaLocator.getRepositoryId() ), false );
741 if ( logicalResource.startsWith( "/" ) )
743 logicalResource = logicalResource.substring( 1 );
745 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
746 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
747 managedRepositoryContent.getRepository(), davSession, archivaLocator,
748 this, mimeTypes, auditListeners, scheduler, fileLockManager );
750 resource.addLockManager( lockManager );
752 catch ( RepositoryAdminException e )
754 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
759 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
760 LogicalResource resource )
763 String path = resource.getPath();
764 if ( repositoryRequest.isSupportFile( path ) )
766 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
768 return ( proxiedFile != null );
771 // Is it a Metadata resource?
772 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
774 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
777 // Is it an Archetype Catalog?
778 if ( repositoryRequest.isArchetypeCatalog( path ) )
780 // FIXME we must implement a merge of remote archetype catalog from remote servers.
781 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
783 return ( proxiedFile != null );
786 // Not any of the above? Then it's gotta be an artifact reference.
789 // Get the artifact reference in a layout neutral way.
790 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
792 if ( artifact != null )
794 String repositoryLayout = managedRepository.getRepository().getLayout();
796 RepositoryStorage repositoryStorage =
797 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
798 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
800 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
802 resource.setPath( managedRepository.toPath( artifact ) );
804 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
805 artifact.getVersion() );
807 return ( proxiedFile != null );
810 catch ( LayoutException e )
814 catch ( ProxyDownloadException e )
816 log.error( e.getMessage(), e );
817 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
818 "Unable to fetch artifact resource." );
825 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
828 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
829 event.setRemoteIP( remoteIP );
831 for ( AuditListener listener : auditListeners )
833 listener.auditEvent( event );
837 public void addAuditListener( AuditListener listener )
839 this.auditListeners.add( listener );
842 public void clearAuditListeners()
844 this.auditListeners.clear();
847 public void removeAuditListener( AuditListener listener )
849 this.auditListeners.remove( listener );
852 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
854 // [MRM-503] - Metadata file need Pragma:no-cache response
856 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
857 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
859 response.setHeader( "Pragma", "no-cache" );
860 response.setHeader( "Cache-Control", "no-cache" );
861 response.setDateHeader( "Last-Modified", new Date().getTime() );
863 // if the resource is a directory don't cache it as new groupId deployed will be available
864 // without need of refreshing browser
867 // We need to specify this so connecting wagons can work correctly
868 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
870 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
873 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
876 if ( !( locator instanceof ArchivaDavResourceLocator ) )
878 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
879 "Locator does not implement RepositoryLocator" );
883 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
885 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
888 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
890 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
891 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
893 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
895 return archivaLocator;
898 private static class LogicalResource
902 public LogicalResource( String path )
907 public String getPath()
912 public void setPath( String path )
918 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
923 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
924 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
926 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
928 WebdavMethodUtil.getMethodPermission(
929 request.getMethod() )
932 catch ( AuthenticationException e )
934 // safety check for MRM-911
935 String guest = UserManager.GUEST_USERNAME;
938 if ( servletAuth.isAuthorized( guest,
939 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
940 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
945 catch ( UnauthorizedException ae )
947 throw new UnauthorizedDavException( repositoryId,
948 "You are not authenticated and authorized to access any repository." );
951 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
953 catch ( MustChangePasswordException e )
955 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
957 catch ( AccountLockedException e )
959 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
961 catch ( AuthorizationException e )
963 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
964 "Fatal Authorization Subsystem Error." );
966 catch ( UnauthorizedException e )
968 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
972 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
973 ArchivaDavResourceLocator locator,
974 RepositoryGroupConfiguration repositoryGroupConfiguration )
975 throws DavException, RepositoryAdminException
977 if ( repositoryGroupConfiguration.getRepositories() == null
978 || repositoryGroupConfiguration.getRepositories().isEmpty() )
981 return new ArchivaVirtualDavResource( new ArrayList<File>(), //
982 new File( System.getProperty( "appserver.base" ) + "/groups/"
983 + repositoryGroupConfiguration.getId() ).getPath(), //
989 List<File> mergedRepositoryContents = new ArrayList<File>();
990 // multiple repo types so we guess they are all the same type
991 // so use the first one
992 // FIXME add a method with group in the repository storage
993 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 0 );
995 String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
996 if ( path.startsWith( "/" ) )
998 path = path.substring( 1 );
1000 LogicalResource logicalResource = new LogicalResource( path );
1003 // if the current user logged in has permission to any of the repositories, allow user to
1004 // browse the repo group but displaying only the repositories which the user has permission to access.
1005 // otherwise, prompt for authentication.
1007 String activePrincipal = getActivePrincipal( request );
1009 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1012 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1017 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1019 File mergedRepoDir =
1020 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1021 mergedRepositoryContents.add( mergedRepoDir );
1025 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1027 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1028 repositoryGroupConfiguration.getId() + "/"
1029 + repositoryGroupConfiguration.getMergedIndexPath()
1031 if ( !tmpDirectory.exists() )
1033 synchronized ( tmpDirectory.getAbsolutePath() )
1035 if ( !tmpDirectory.exists() )
1037 tmpDirectory.mkdirs();
1041 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1043 for ( String repository : repositories )
1045 ManagedRepositoryContent managedRepository = null;
1049 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1051 catch ( RepositoryNotFoundException e )
1053 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1054 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1056 catch ( RepositoryException e )
1058 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1059 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1062 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1063 if ( resourceFile.exists() )
1065 // in case of group displaying index directory doesn't have sense !!
1066 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1067 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1069 if ( !new File( repoIndexDirectory ).isAbsolute() )
1071 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1072 StringUtils.isEmpty( repoIndexDirectory )
1074 : repoIndexDirectory
1075 ).getAbsolutePath();
1078 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1080 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1081 ".indexer" ).getAbsolutePath();
1084 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1085 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1087 // for prompted authentication
1088 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1092 if ( isAuthorized( request, repository ) )
1094 mergedRepositoryContents.add( resourceFile );
1095 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1098 catch ( DavException e )
1100 // TODO: review exception handling
1102 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1103 activePrincipal, e.getMessage() );
1110 // for the current user logged in
1113 if ( servletAuth.isAuthorized( activePrincipal, repository,
1114 WebdavMethodUtil.getMethodPermission(
1115 request.getMethod() )
1118 mergedRepositoryContents.add( resourceFile );
1119 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1122 catch ( UnauthorizedException e )
1124 // TODO: review exception handling
1126 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1127 activePrincipal, e.getMessage() );
1138 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1141 ArchivaVirtualDavResource resource =
1142 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1145 // compatibility with MRM-440 to ensure browsing the repository group works ok
1146 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1148 throw new BrowserRedirectException( resource.getHref() );
1154 protected String getActivePrincipal( DavServletRequest request )
1156 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1157 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1161 * Check if the current user is authorized to access any of the repos
1164 * @param repositories
1165 * @param activePrincipal
1168 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1170 // when no repositories configured it's impossible to browse nothing !
1171 // at least make possible to see nothing :-)
1172 if ( repositories == null || repositories.isEmpty() )
1177 boolean allow = false;
1179 // if securitySession != null, it means that the user was prompted for authentication
1180 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1182 for ( String repository : repositories )
1186 if ( isAuthorized( request, repository ) )
1192 catch ( DavException e )
1200 for ( String repository : repositories )
1204 if ( servletAuth.isAuthorized( activePrincipal, repository,
1205 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1211 catch ( UnauthorizedException e )
1221 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1222 throws RepositoryMetadataException, DigesterException, IOException
1224 File outputFile = new File( outputFilename );
1225 if ( outputFile.exists() )
1227 FileUtils.deleteQuietly( outputFile );
1230 outputFile.getParentFile().mkdirs();
1231 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1233 createChecksumFile( outputFilename, digestSha1 );
1234 createChecksumFile( outputFilename, digestMd5 );
1239 private void createChecksumFile( String path, Digester digester )
1240 throws DigesterException, IOException
1242 File checksumFile = new File( path + digester.getFilenameExtension() );
1243 if ( !checksumFile.exists() )
1245 FileUtils.deleteQuietly( checksumFile );
1246 checksum.createChecksum( new File( path ), digester );
1248 else if ( !checksumFile.isFile() )
1250 log.error( "Checksum file is not a file." );
1254 private boolean isProjectReference( String requestedResource )
1258 metadataTools.toVersionedReference( requestedResource );
1261 catch ( RepositoryMetadataException re )
1267 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1268 DavServletRequest request,
1269 RepositoryGroupConfiguration repositoryGroupConfiguration )
1275 HttpSession session = request.getSession();
1277 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1278 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1279 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1280 if ( temporaryGroupIndexMap == null )
1282 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1285 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1287 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1289 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1290 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1292 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1293 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1294 indexMerger.cleanTemporaryGroupIndex( tmp );
1298 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1299 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1300 return tmp.getDirectory();
1304 Set<String> authzRepos = new HashSet<String>();
1306 String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1308 for ( String repository : repositories )
1312 if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1314 authzRepos.add( repository );
1315 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1318 catch ( UnauthorizedException e )
1320 // TODO: review exception handling
1322 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1326 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1327 repositoryGroupConfiguration.getId(), authzRepos );
1329 File tempRepoFile = Files.createTempDir();
1330 tempRepoFile.deleteOnExit();
1332 IndexMergerRequest indexMergerRequest =
1333 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1334 repositoryGroupConfiguration.getMergedIndexPath(),
1335 repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory(
1336 tempRepoFile ).temporary( true );
1338 MergedRemoteIndexesTaskRequest taskRequest =
1339 new MergedRemoteIndexesTaskRequest( indexMergerRequest, indexMerger );
1341 MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1343 IndexingContext indexingContext = job.execute().getIndexingContext();
1345 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1346 TemporaryGroupIndex temporaryGroupIndex =
1347 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1348 repositoryGroupConfiguration.getMergedIndexTtl() ).setCreationTime(
1349 new Date().getTime() );
1350 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1351 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1352 temporaryGroupIndexMap );
1353 return mergedRepoDir;
1355 catch ( RepositoryAdminException e )
1357 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1359 catch ( IndexMergerException e )
1361 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1366 public void setServletAuth( ServletAuthenticator servletAuth )
1368 this.servletAuth = servletAuth;
1371 public void setHttpAuth( HttpAuthenticator httpAuth )
1373 this.httpAuth = httpAuth;
1376 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1378 this.scheduler = scheduler;
1381 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1383 this.archivaConfiguration = archivaConfiguration;
1386 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1388 this.repositoryFactory = repositoryFactory;
1391 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1393 this.repositoryRequest = repositoryRequest;
1396 public void setConnectors( RepositoryProxyConnectors connectors )
1398 this.connectors = connectors;
1401 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1403 return remoteRepositoryAdmin;
1406 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1408 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1411 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1413 return managedRepositoryAdmin;
1416 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1418 this.managedRepositoryAdmin = managedRepositoryAdmin;