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.RemoteRepository;
24 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
25 import org.apache.archiva.audit.AuditEvent;
26 import org.apache.archiva.audit.AuditListener;
27 import org.apache.archiva.audit.Auditable;
28 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
29 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
30 import org.apache.archiva.common.utils.PathUtil;
31 import org.apache.archiva.common.utils.VersionUtil;
32 import org.apache.archiva.configuration.ArchivaConfiguration;
33 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
34 import org.apache.archiva.indexer.merger.IndexMerger;
35 import org.apache.archiva.indexer.merger.IndexMergerException;
36 import org.apache.archiva.indexer.merger.IndexMergerRequest;
37 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
38 import org.apache.archiva.indexer.search.RepositorySearch;
39 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
40 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
41 import org.apache.archiva.model.ArchivaRepositoryMetadata;
42 import org.apache.archiva.model.ArtifactReference;
43 import org.apache.archiva.policies.ProxyDownloadException;
44 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
45 import org.apache.archiva.redback.authentication.AuthenticationException;
46 import org.apache.archiva.redback.authentication.AuthenticationResult;
47 import org.apache.archiva.redback.authorization.AuthorizationException;
48 import org.apache.archiva.redback.authorization.UnauthorizedException;
49 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
50 import org.apache.archiva.redback.policy.AccountLockedException;
51 import org.apache.archiva.redback.policy.MustChangePasswordException;
52 import org.apache.archiva.redback.system.SecuritySession;
53 import org.apache.archiva.redback.users.User;
54 import org.apache.archiva.redback.users.UserManager;
55 import org.apache.archiva.repository.ManagedRepositoryContent;
56 import org.apache.archiva.repository.RepositoryContentFactory;
57 import org.apache.archiva.repository.RepositoryException;
58 import org.apache.archiva.repository.RepositoryNotFoundException;
59 import org.apache.archiva.repository.content.legacy.LegacyPathParser;
60 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
61 import org.apache.archiva.repository.layout.LayoutException;
62 import org.apache.archiva.repository.metadata.MetadataTools;
63 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
64 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
65 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
66 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
67 import org.apache.archiva.security.ServletAuthenticator;
68 import org.apache.archiva.webdav.util.MimeTypes;
69 import org.apache.archiva.webdav.util.RepositoryPathUtil;
70 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
71 import org.apache.archiva.webdav.util.WebdavMethodUtil;
72 import org.apache.archiva.xml.XMLException;
73 import org.apache.commons.io.FileUtils;
74 import org.apache.commons.io.FilenameUtils;
75 import org.apache.commons.lang.StringUtils;
76 import org.apache.jackrabbit.webdav.DavException;
77 import org.apache.jackrabbit.webdav.DavResource;
78 import org.apache.jackrabbit.webdav.DavResourceFactory;
79 import org.apache.jackrabbit.webdav.DavResourceLocator;
80 import org.apache.jackrabbit.webdav.DavServletRequest;
81 import org.apache.jackrabbit.webdav.DavServletResponse;
82 import org.apache.jackrabbit.webdav.DavSession;
83 import org.apache.jackrabbit.webdav.lock.LockManager;
84 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
85 import org.apache.maven.index.context.IndexingContext;
86 import org.codehaus.plexus.digest.ChecksumFile;
87 import org.codehaus.plexus.digest.Digester;
88 import org.codehaus.plexus.digest.DigesterException;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
91 import org.slf4j.MarkerFactory;
92 import org.springframework.context.ApplicationContext;
93 import org.springframework.stereotype.Service;
95 import javax.annotation.PostConstruct;
96 import javax.inject.Inject;
97 import javax.inject.Named;
98 import javax.servlet.http.HttpServletResponse;
99 import javax.servlet.http.HttpSession;
101 import java.io.IOException;
102 import java.util.ArrayList;
103 import java.util.Date;
104 import java.util.HashMap;
105 import java.util.HashSet;
106 import java.util.List;
107 import java.util.Map;
108 import java.util.Set;
113 @Service( "davResourceFactory#archiva" )
114 public class ArchivaDavResourceFactory
115 implements DavResourceFactory, Auditable
117 private static final String PROXIED_SUFFIX = " (proxied)";
119 private static final String HTTP_PUT_METHOD = "PUT";
121 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
127 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
133 private RepositoryContentFactory repositoryFactory;
138 private RepositoryRequest repositoryRequest;
144 @Named( value = "repositoryProxyConnectors#default" )
145 private RepositoryProxyConnectors connectors;
151 private MetadataTools metadataTools;
157 private MimeTypes mimeTypes;
162 private ArchivaConfiguration archivaConfiguration;
168 private ServletAuthenticator servletAuth;
174 @Named( value = "httpAuthenticator#basic" )
175 private HttpAuthenticator httpAuth;
178 private RemoteRepositoryAdmin remoteRepositoryAdmin;
181 private IndexMerger indexMerger;
184 private RepositorySearch repositorySearch;
187 * Lock Manager - use simple implementation from JackRabbit
189 private final LockManager lockManager = new SimpleLockManager();
194 private ChecksumFile checksum;
199 private Digester digestSha1;
204 private Digester digestMd5;
210 @Named( value = "archivaTaskScheduler#repository" )
211 private RepositoryArchivaTaskScheduler scheduler;
213 private ApplicationContext applicationContext;
216 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
217 ArchivaConfiguration archivaConfiguration )
218 throws PlexusSisuBridgeException
220 this.archivaConfiguration = archivaConfiguration;
221 this.applicationContext = applicationContext;
222 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
224 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
225 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
227 // TODO remove this hard dependency on maven !!
228 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
232 public void initialize()
237 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
238 final DavServletResponse response )
241 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
243 RepositoryGroupConfiguration repoGroupConfig =
244 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
246 String activePrincipal = getActivePrincipal( request );
248 List<String> resourcesInAbsolutePath = new ArrayList<String>();
250 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
251 DavResource resource;
252 if ( repoGroupConfig != null )
256 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
257 "Write method not allowed for repository groups." );
260 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
262 // handle browse requests for virtual repos
263 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
265 return getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
270 // make a copy to avoid potential concurrent modifications (eg. by configuration)
271 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
273 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
274 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
275 resourcesInAbsolutePath, archivaLocator.getRepositoryId() );
283 RemoteRepository remoteRepository =
284 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
286 if ( remoteRepository != null )
288 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
289 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
290 File resourceFile = StringUtils.equals( logicalResource, "/" )
291 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
292 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
293 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
294 request.getRemoteAddr(), activePrincipal,
295 request.getDavSession(), archivaLocator, this, mimeTypes,
296 auditListeners, scheduler );
297 setHeaders( response, locator, resource );
301 catch ( RepositoryAdminException e )
303 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
304 archivaLocator.getRepositoryId(), e.getMessage() );
307 ManagedRepositoryContent managedRepository = null;
311 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
313 catch ( RepositoryNotFoundException e )
315 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
316 "Invalid repository: " + archivaLocator.getRepositoryId() );
318 catch ( RepositoryException e )
320 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
323 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
325 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
327 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
328 resourcesInAbsolutePath.add(
329 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
332 String requestedResource = request.getRequestURI();
334 // MRM-872 : merge all available metadata
335 // merge metadata only when requested via the repo group
336 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
337 requestedResource ) ) && repoGroupConfig != null )
339 // this should only be at the project level not version level!
340 if ( isProjectReference( requestedResource ) )
343 ArchivaDavResource res = (ArchivaDavResource) resource;
345 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
347 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
349 // for MRM-872 handle checksums of the merged metadata files
350 if ( repositoryRequest.isSupportFile( requestedResource ) )
352 File metadataChecksum =
353 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
354 if ( metadataChecksum.exists() )
356 LogicalResource logicalResource =
357 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
360 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
361 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
362 archivaLocator, this, mimeTypes, auditListeners, scheduler );
367 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
369 // merge the metadata of all repos under group
370 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
371 for ( String resourceAbsPath : resourcesInAbsolutePath )
375 File metadataFile = new File( resourceAbsPath );
376 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
377 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
379 catch ( XMLException e )
381 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
382 "Error occurred while reading metadata file." );
384 catch ( RepositoryMetadataException r )
386 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
387 "Error occurred while merging metadata file." );
393 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
395 LogicalResource logicalResource = new LogicalResource(
396 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
399 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
400 request.getRemoteAddr(), activePrincipal,
401 request.getDavSession(), archivaLocator, this, mimeTypes,
402 auditListeners, scheduler );
404 catch ( RepositoryMetadataException r )
406 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
407 "Error occurred while writing metadata file." );
409 catch ( IOException ie )
411 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
412 "Error occurred while generating checksum files." );
414 catch ( DigesterException de )
416 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
417 "Error occurred while generating checksum files." );
424 setHeaders( response, locator, resource );
426 // compatibility with MRM-440 to ensure browsing the repository works ok
427 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
429 throw new BrowserRedirectException( resource.getHref() );
431 resource.addLockManager( lockManager );
435 private DavResource processRepositoryGroup( final DavServletRequest request,
436 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
437 String activePrincipal, List<String> resourcesInAbsolutePath,
438 String repositoryGroupId )
441 DavResource resource = null;
442 List<DavException> storedExceptions = new ArrayList<DavException>();
444 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
446 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
448 if ( StringUtils.endsWith( rootPath, "/.indexer" ) )
450 // we are in the case of index file request
451 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
452 File temporaryIndexDirectory =
453 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupId );
455 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
456 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
457 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
458 archivaLocator, this, mimeTypes, auditListeners, scheduler );
463 for ( String repositoryId : repositories )
465 ManagedRepositoryContent managedRepository;
468 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
470 catch ( RepositoryNotFoundException e )
472 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
474 catch ( RepositoryException e )
476 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
481 DavResource updatedResource =
482 processRepository( request, archivaLocator, activePrincipal, managedRepository );
483 if ( resource == null )
485 resource = updatedResource;
488 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
489 if ( logicalResource.endsWith( "/" ) )
491 logicalResource = logicalResource.substring( 1 );
493 resourcesInAbsolutePath.add(
494 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
496 catch ( DavException e )
498 storedExceptions.add( e );
502 if ( resource == null )
504 if ( !storedExceptions.isEmpty() )
507 for ( DavException e : storedExceptions )
509 if ( 401 == e.getErrorCode() )
515 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
519 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
525 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
526 String activePrincipal, ManagedRepositoryContent managedRepository )
529 DavResource resource = null;
530 if ( isAuthorized( request, managedRepository.getId() ) )
532 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
533 if ( path.startsWith( "/" ) )
535 path = path.substring( 1 );
537 LogicalResource logicalResource = new LogicalResource( path );
538 File resourceFile = new File( managedRepository.getRepoRoot(), path );
539 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
540 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
541 archivaLocator, this, mimeTypes, auditListeners, scheduler );
543 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
545 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
547 // force a resource not found
548 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
552 if ( !resource.isCollection() )
554 boolean previouslyExisted = resourceFile.exists();
556 // Attempt to fetch the resource from any defined proxy.
557 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
559 // At this point the incoming request can either be in default or
560 // legacy layout format.
563 // Perform an adjustment of the resource to the managed
564 // repository expected path.
565 String localResourcePath =
566 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
567 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
569 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
570 managedRepository.getRepository(), request.getRemoteAddr(),
571 activePrincipal, request.getDavSession(), archivaLocator, this,
572 mimeTypes, auditListeners, scheduler );
574 catch ( LayoutException e )
576 if ( !resourceFile.exists() )
578 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
584 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
587 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
588 resourceFile.getName(), managedRepository.getId(), activePrincipal );
590 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
591 logicalResource.getPath(), event, activePrincipal );
594 if ( !resourceFile.exists() )
596 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
602 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
604 String resourcePath = logicalResource.getPath();
606 // check if target repo is enabled for releases
607 // we suppose that release-artifacts can be deployed only to repos enabled for releases
608 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
609 && !repositoryRequest.isSupportFile( resourcePath ) )
611 ArtifactReference artifact = null;
614 artifact = managedRepository.toArtifactReference( resourcePath );
616 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
618 // check if artifact already exists and if artifact re-deployment to the repository is allowed
619 if ( managedRepository.hasContent( artifact )
620 && managedRepository.getRepository().isBlockRedeployments() )
622 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
623 managedRepository.getId() );
624 throw new DavException( HttpServletResponse.SC_CONFLICT,
625 "Overwriting released artifacts is not allowed." );
629 catch ( LayoutException e )
631 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
636 * Create parent directories that don't exist when writing a file This actually makes this
637 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
638 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
639 * create the collections themselves.
642 File rootDirectory = new File( managedRepository.getRepoRoot() );
643 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
645 if ( !destDir.exists() )
648 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
650 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
653 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
654 AuditEvent.CREATE_DIR, activePrincipal );
661 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
664 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
666 ManagedRepositoryContent managedRepository;
669 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
671 catch ( RepositoryNotFoundException e )
673 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
674 "Invalid repository: " + archivaLocator.getRepositoryId() );
676 catch ( RepositoryException e )
678 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
681 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
682 if ( logicalResource.startsWith( "/" ) )
684 logicalResource = logicalResource.substring( 1 );
686 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
687 DavResource resource =
688 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
689 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
691 resource.addLockManager( lockManager );
695 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
696 LogicalResource resource )
699 String path = resource.getPath();
700 if ( repositoryRequest.isSupportFile( path ) )
702 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
704 return ( proxiedFile != null );
707 // Is it a Metadata resource?
708 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
710 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
713 // Is it an Archetype Catalog?
714 if ( repositoryRequest.isArchetypeCatalog( path ) )
716 // FIXME we must implement a merge of remote archetype catalog from remote servers.
717 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
719 return ( proxiedFile != null );
722 // Not any of the above? Then it's gotta be an artifact reference.
725 // Get the artifact reference in a layout neutral way.
726 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
728 if ( artifact != null )
730 String repositoryLayout = managedRepository.getRepository().getLayout();
732 RepositoryStorage repositoryStorage =
733 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
734 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
736 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
738 resource.setPath( managedRepository.toPath( artifact ) );
740 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
741 artifact.getVersion() );
743 return ( proxiedFile != null );
746 catch ( LayoutException e )
750 catch ( ProxyDownloadException e )
752 log.error( e.getMessage(), e );
753 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
754 "Unable to fetch artifact resource." );
761 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
764 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
765 event.setRemoteIP( remoteIP );
767 for ( AuditListener listener : auditListeners )
769 listener.auditEvent( event );
773 public void addAuditListener( AuditListener listener )
775 this.auditListeners.add( listener );
778 public void clearAuditListeners()
780 this.auditListeners.clear();
783 public void removeAuditListener( AuditListener listener )
785 this.auditListeners.remove( listener );
788 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
790 // [MRM-503] - Metadata file need Pragma:no-cache response
792 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
793 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
795 response.setHeader( "Pragma", "no-cache" );
796 response.setHeader( "Cache-Control", "no-cache" );
797 response.setDateHeader( "Last-Modified", new Date().getTime() );
799 // if the resource is a directory don't cache it as new groupId deployed will be available
800 // without need of refreshing browser
803 // We need to specify this so connecting wagons can work correctly
804 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
806 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
809 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
812 if ( !( locator instanceof ArchivaDavResourceLocator ) )
814 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
815 "Locator does not implement RepositoryLocator" );
819 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
821 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
824 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
826 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
827 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
829 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
831 return archivaLocator;
834 private static class LogicalResource
838 public LogicalResource( String path )
843 public String getPath()
848 public void setPath( String path )
854 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
859 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
860 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
862 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
864 WebdavMethodUtil.getMethodPermission(
865 request.getMethod() ) );
867 catch ( AuthenticationException e )
869 // safety check for MRM-911
870 String guest = UserManager.GUEST_USERNAME;
873 if ( servletAuth.isAuthorized( guest,
874 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
875 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
880 catch ( UnauthorizedException ae )
882 throw new UnauthorizedDavException( repositoryId,
883 "You are not authenticated and authorized to access any repository." );
886 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
888 catch ( MustChangePasswordException e )
890 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
892 catch ( AccountLockedException e )
894 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
896 catch ( AuthorizationException e )
898 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
899 "Fatal Authorization Subsystem Error." );
901 catch ( UnauthorizedException e )
903 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
907 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
908 ArchivaDavResourceLocator locator,
909 RepositoryGroupConfiguration repositoryGroupConfiguration )
912 List<File> mergedRepositoryContents = new ArrayList<File>();
913 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
914 if ( path.startsWith( "/" ) )
916 path = path.substring( 1 );
918 LogicalResource logicalResource = new LogicalResource( path );
921 // if the current user logged in has permission to any of the repositories, allow user to
922 // browse the repo group but displaying only the repositories which the user has permission to access.
923 // otherwise, prompt for authentication.
925 String activePrincipal = getActivePrincipal( request );
927 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
933 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
934 if ( StringUtils.endsWith( pathInfo, "/" + repositoryGroupConfiguration.getMergedIndexPath() )
935 || StringUtils.endsWith( pathInfo, "/" + repositoryGroupConfiguration.getMergedIndexPath() + "/" ) )
937 File mergedRepoDir = buildMergedIndexDirectory( repositories, activePrincipal, request,
938 repositoryGroupConfiguration.getId() );
939 mergedRepositoryContents.add( mergedRepoDir );
943 for ( String repository : repositories )
945 ManagedRepositoryContent managedRepository = null;
949 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
951 catch ( RepositoryNotFoundException e )
953 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
954 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
956 catch ( RepositoryException e )
958 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
959 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
962 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
963 if ( resourceFile.exists() )
965 // in case of group displaying index directory doesn't have sense !!
966 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
967 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
969 if ( !new File( repoIndexDirectory ).isAbsolute() )
971 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
972 StringUtils.isEmpty( repoIndexDirectory )
974 : repoIndexDirectory ).getAbsolutePath();
977 if ( StringUtils.isEmpty( repoIndexDirectory ) )
979 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
980 ".indexer" ).getAbsolutePath();
983 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
984 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
986 // for prompted authentication
987 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
991 if ( isAuthorized( request, repository ) )
993 mergedRepositoryContents.add( resourceFile );
994 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
997 catch ( DavException e )
999 // TODO: review exception handling
1001 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1002 activePrincipal, e.getMessage() );
1009 // for the current user logged in
1012 if ( servletAuth.isAuthorized( activePrincipal, repository,
1013 WebdavMethodUtil.getMethodPermission(
1014 request.getMethod() ) ) )
1016 mergedRepositoryContents.add( resourceFile );
1017 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1020 catch ( UnauthorizedException e )
1022 // TODO: review exception handling
1024 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1025 activePrincipal, e.getMessage() );
1036 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1039 ArchivaVirtualDavResource resource =
1040 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1043 // compatibility with MRM-440 to ensure browsing the repository group works ok
1044 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1046 throw new BrowserRedirectException( resource.getHref() );
1052 protected String getActivePrincipal( DavServletRequest request )
1054 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1055 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1059 * Check if the current user is authorized to access any of the repos
1062 * @param repositories
1063 * @param activePrincipal
1066 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1068 // when no repositories configured it's impossible to browse nothing !
1069 // at least make possible to see nothing :-)
1070 if ( repositories == null || repositories.isEmpty() )
1075 boolean allow = false;
1077 // if securitySession != null, it means that the user was prompted for authentication
1078 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1080 for ( String repository : repositories )
1084 if ( isAuthorized( request, repository ) )
1090 catch ( DavException e )
1098 for ( String repository : repositories )
1102 if ( servletAuth.isAuthorized( activePrincipal, repository,
1103 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1109 catch ( UnauthorizedException e )
1119 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1120 throws RepositoryMetadataException, DigesterException, IOException
1122 File outputFile = new File( outputFilename );
1123 if ( outputFile.exists() )
1125 FileUtils.deleteQuietly( outputFile );
1128 outputFile.getParentFile().mkdirs();
1129 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1131 createChecksumFile( outputFilename, digestSha1 );
1132 createChecksumFile( outputFilename, digestMd5 );
1137 private void createChecksumFile( String path, Digester digester )
1138 throws DigesterException, IOException
1140 File checksumFile = new File( path + digester.getFilenameExtension() );
1141 if ( !checksumFile.exists() )
1143 FileUtils.deleteQuietly( checksumFile );
1144 checksum.createChecksum( new File( path ), digester );
1146 else if ( !checksumFile.isFile() )
1148 log.error( "Checksum file is not a file." );
1152 private boolean isProjectReference( String requestedResource )
1156 metadataTools.toVersionedReference( requestedResource );
1159 catch ( RepositoryMetadataException re )
1165 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1166 DavServletRequest request, String groupId )
1172 HttpSession session = request.getSession();
1174 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1175 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1176 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1177 if ( temporaryGroupIndexMap == null )
1179 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1182 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( groupId );
1184 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1186 if ( System.currentTimeMillis() - tmp.getCreationTime() > ( indexMerger.getGroupMergedIndexTtl() * 60
1189 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1190 "tmp group index '{}' is too old so delete it", groupId );
1191 indexMerger.cleanTemporaryGroupIndex( tmp );
1195 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1196 "merged index for group '{}' found in cache", groupId );
1197 return tmp.getDirectory();
1201 Set<String> authzRepos = new HashSet<String>();
1202 for ( String repository : repositories )
1206 if ( servletAuth.isAuthorized( activePrincipal, repository,
1207 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1209 authzRepos.add( repository );
1210 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1213 catch ( UnauthorizedException e )
1215 // TODO: review exception handling
1217 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1221 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'", groupId,
1223 IndexingContext indexingContext =
1224 indexMerger.buildMergedIndex( new IndexMergerRequest( authzRepos, true, groupId ) );
1225 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1226 TemporaryGroupIndex temporaryGroupIndex =
1227 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), groupId ).setCreationTime(
1228 new Date().getTime() );
1229 temporaryGroupIndexMap.put( groupId, temporaryGroupIndex );
1230 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1231 temporaryGroupIndexMap );
1232 return mergedRepoDir;
1234 catch ( RepositoryAdminException e )
1236 throw new DavException( 500, e );
1238 catch ( IndexMergerException e )
1240 throw new DavException( 500, e );
1245 public void setServletAuth( ServletAuthenticator servletAuth )
1247 this.servletAuth = servletAuth;
1250 public void setHttpAuth( HttpAuthenticator httpAuth )
1252 this.httpAuth = httpAuth;
1255 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1257 this.scheduler = scheduler;
1260 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1262 this.archivaConfiguration = archivaConfiguration;
1265 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1267 this.repositoryFactory = repositoryFactory;
1270 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1272 this.repositoryRequest = repositoryRequest;
1275 public void setConnectors( RepositoryProxyConnectors connectors )
1277 this.connectors = connectors;
1280 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1282 return remoteRepositoryAdmin;
1285 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1287 this.remoteRepositoryAdmin = remoteRepositoryAdmin;