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.commons.lang.SystemUtils;
77 import org.apache.jackrabbit.webdav.DavException;
78 import org.apache.jackrabbit.webdav.DavResource;
79 import org.apache.jackrabbit.webdav.DavResourceFactory;
80 import org.apache.jackrabbit.webdav.DavResourceLocator;
81 import org.apache.jackrabbit.webdav.DavServletRequest;
82 import org.apache.jackrabbit.webdav.DavServletResponse;
83 import org.apache.jackrabbit.webdav.DavSession;
84 import org.apache.jackrabbit.webdav.lock.LockManager;
85 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
86 import org.apache.maven.index.context.IndexingContext;
87 import org.codehaus.plexus.digest.ChecksumFile;
88 import org.codehaus.plexus.digest.Digester;
89 import org.codehaus.plexus.digest.DigesterException;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
92 import org.slf4j.MarkerFactory;
93 import org.springframework.context.ApplicationContext;
94 import org.springframework.stereotype.Service;
96 import javax.annotation.PostConstruct;
97 import javax.inject.Inject;
98 import javax.inject.Named;
99 import javax.servlet.http.HttpServletResponse;
100 import javax.servlet.http.HttpSession;
102 import java.io.IOException;
103 import java.util.ArrayList;
104 import java.util.Date;
105 import java.util.HashMap;
106 import java.util.HashSet;
107 import java.util.List;
108 import java.util.Map;
109 import java.util.Set;
114 @Service("davResourceFactory#archiva")
115 public class ArchivaDavResourceFactory
116 implements DavResourceFactory, Auditable
118 private static final String PROXIED_SUFFIX = " (proxied)";
120 private static final String HTTP_PUT_METHOD = "PUT";
122 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
128 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
134 private RepositoryContentFactory repositoryFactory;
139 private RepositoryRequest repositoryRequest;
145 @Named(value = "repositoryProxyConnectors#default")
146 private RepositoryProxyConnectors connectors;
152 private MetadataTools metadataTools;
158 private MimeTypes mimeTypes;
163 private ArchivaConfiguration archivaConfiguration;
169 private ServletAuthenticator servletAuth;
175 @Named(value = "httpAuthenticator#basic")
176 private HttpAuthenticator httpAuth;
179 private RemoteRepositoryAdmin remoteRepositoryAdmin;
182 private IndexMerger indexMerger;
185 private RepositorySearch repositorySearch;
188 * Lock Manager - use simple implementation from JackRabbit
190 private final LockManager lockManager = new SimpleLockManager();
195 private ChecksumFile checksum;
200 private Digester digestSha1;
205 private Digester digestMd5;
211 @Named(value = "archivaTaskScheduler#repository")
212 private RepositoryArchivaTaskScheduler scheduler;
214 private ApplicationContext applicationContext;
217 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
218 ArchivaConfiguration archivaConfiguration )
219 throws PlexusSisuBridgeException
221 this.archivaConfiguration = archivaConfiguration;
222 this.applicationContext = applicationContext;
223 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
225 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
226 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
228 // TODO remove this hard dependency on maven !!
229 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
233 public void initialize()
238 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
239 final DavServletResponse response )
242 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
244 RepositoryGroupConfiguration repoGroupConfig =
245 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
247 String activePrincipal = getActivePrincipal( request );
249 List<String> resourcesInAbsolutePath = new ArrayList<String>();
251 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
252 DavResource resource;
253 if ( repoGroupConfig != null )
257 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
258 "Write method not allowed for repository groups." );
261 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
263 // handle browse requests for virtual repos
264 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
266 return getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
271 // make a copy to avoid potential concurrent modifications (eg. by configuration)
272 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
274 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
275 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
276 resourcesInAbsolutePath, repoGroupConfig );
284 RemoteRepository remoteRepository =
285 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
287 if ( remoteRepository != null )
289 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
290 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
291 File resourceFile = StringUtils.equals( logicalResource, "/" )
292 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
293 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
294 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
295 request.getRemoteAddr(), activePrincipal,
296 request.getDavSession(), archivaLocator, this, mimeTypes,
297 auditListeners, scheduler );
298 setHeaders( response, locator, resource );
302 catch ( RepositoryAdminException e )
304 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
305 archivaLocator.getRepositoryId(), e.getMessage() );
308 ManagedRepositoryContent managedRepository = null;
312 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
314 catch ( RepositoryNotFoundException e )
316 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
317 "Invalid repository: " + archivaLocator.getRepositoryId() );
319 catch ( RepositoryException e )
321 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
324 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
326 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
328 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
329 resourcesInAbsolutePath.add(
330 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
333 String requestedResource = request.getRequestURI();
335 // MRM-872 : merge all available metadata
336 // merge metadata only when requested via the repo group
337 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
338 requestedResource ) ) && repoGroupConfig != null )
340 // this should only be at the project level not version level!
341 if ( isProjectReference( requestedResource ) )
344 ArchivaDavResource res = (ArchivaDavResource) resource;
346 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
348 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
350 // for MRM-872 handle checksums of the merged metadata files
351 if ( repositoryRequest.isSupportFile( requestedResource ) )
353 File metadataChecksum =
354 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
355 if ( metadataChecksum.exists() )
357 LogicalResource logicalResource =
358 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
361 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
362 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
363 archivaLocator, this, mimeTypes, auditListeners, scheduler );
368 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
370 // merge the metadata of all repos under group
371 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
372 for ( String resourceAbsPath : resourcesInAbsolutePath )
376 File metadataFile = new File( resourceAbsPath );
377 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
378 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
380 catch ( XMLException e )
382 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
383 "Error occurred while reading metadata file." );
385 catch ( RepositoryMetadataException r )
387 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
388 "Error occurred while merging metadata file." );
394 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
396 LogicalResource logicalResource = new LogicalResource(
397 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
400 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
401 request.getRemoteAddr(), activePrincipal,
402 request.getDavSession(), archivaLocator, this, mimeTypes,
403 auditListeners, scheduler );
405 catch ( RepositoryMetadataException r )
407 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
408 "Error occurred while writing metadata file." );
410 catch ( IOException ie )
412 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
413 "Error occurred while generating checksum files." );
415 catch ( DigesterException de )
417 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
418 "Error occurred while generating checksum files." );
425 setHeaders( response, locator, resource );
427 // compatibility with MRM-440 to ensure browsing the repository works ok
428 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
430 throw new BrowserRedirectException( resource.getHref() );
432 resource.addLockManager( lockManager );
436 private DavResource processRepositoryGroup( final DavServletRequest request,
437 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
438 String activePrincipal, List<String> resourcesInAbsolutePath,
439 RepositoryGroupConfiguration repoGroupConfig )
442 DavResource resource = null;
443 List<DavException> storedExceptions = new ArrayList<DavException>();
445 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
447 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
449 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
451 // we are in the case of index file request
452 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
453 File temporaryIndexDirectory =
454 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
456 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
457 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
458 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
459 archivaLocator, this, mimeTypes, auditListeners, scheduler );
464 for ( String repositoryId : repositories )
466 ManagedRepositoryContent managedRepository;
469 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
471 catch ( RepositoryNotFoundException e )
473 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
475 catch ( RepositoryException e )
477 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
482 DavResource updatedResource =
483 processRepository( request, archivaLocator, activePrincipal, managedRepository );
484 if ( resource == null )
486 resource = updatedResource;
489 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
490 if ( logicalResource.endsWith( "/" ) )
492 logicalResource = logicalResource.substring( 1 );
494 resourcesInAbsolutePath.add(
495 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
497 catch ( DavException e )
499 storedExceptions.add( e );
503 if ( resource == null )
505 if ( !storedExceptions.isEmpty() )
508 for ( DavException e : storedExceptions )
510 if ( 401 == e.getErrorCode() )
516 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
520 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
526 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
527 String activePrincipal, ManagedRepositoryContent managedRepository )
530 DavResource resource = null;
531 if ( isAuthorized( request, managedRepository.getId() ) )
533 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
534 if ( path.startsWith( "/" ) )
536 path = path.substring( 1 );
538 LogicalResource logicalResource = new LogicalResource( path );
539 File resourceFile = new File( managedRepository.getRepoRoot(), path );
540 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
541 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
542 archivaLocator, this, mimeTypes, auditListeners, scheduler );
544 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
546 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
548 // force a resource not found
549 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
553 if ( !resource.isCollection() )
555 boolean previouslyExisted = resourceFile.exists();
557 // Attempt to fetch the resource from any defined proxy.
558 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
560 // At this point the incoming request can either be in default or
561 // legacy layout format.
564 // Perform an adjustment of the resource to the managed
565 // repository expected path.
566 String localResourcePath =
567 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
568 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
570 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
571 managedRepository.getRepository(), request.getRemoteAddr(),
572 activePrincipal, request.getDavSession(), archivaLocator, this,
573 mimeTypes, auditListeners, scheduler );
575 catch ( LayoutException e )
577 if ( !resourceFile.exists() )
579 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
585 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
588 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
589 resourceFile.getName(), managedRepository.getId(), activePrincipal );
591 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
592 logicalResource.getPath(), event, activePrincipal );
595 if ( !resourceFile.exists() )
597 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
603 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
605 String resourcePath = logicalResource.getPath();
607 // check if target repo is enabled for releases
608 // we suppose that release-artifacts can be deployed only to repos enabled for releases
609 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
610 && !repositoryRequest.isSupportFile( resourcePath ) )
612 ArtifactReference artifact = null;
615 artifact = managedRepository.toArtifactReference( resourcePath );
617 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
619 // check if artifact already exists and if artifact re-deployment to the repository is allowed
620 if ( managedRepository.hasContent( artifact )
621 && managedRepository.getRepository().isBlockRedeployments() )
623 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
624 managedRepository.getId() );
625 throw new DavException( HttpServletResponse.SC_CONFLICT,
626 "Overwriting released artifacts is not allowed." );
630 catch ( LayoutException e )
632 log.warn( "Artifact path '{}' is invalid." ,resourcePath );
637 * Create parent directories that don't exist when writing a file This actually makes this
638 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
639 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
640 * create the collections themselves.
643 File rootDirectory = new File( managedRepository.getRepoRoot() );
644 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
646 if ( !destDir.exists() )
649 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
651 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
654 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
655 AuditEvent.CREATE_DIR, activePrincipal );
662 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
665 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
667 ManagedRepositoryContent managedRepository;
670 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
672 catch ( RepositoryNotFoundException e )
674 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
675 "Invalid repository: " + archivaLocator.getRepositoryId() );
677 catch ( RepositoryException e )
679 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
682 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
683 if ( logicalResource.startsWith( "/" ) )
685 logicalResource = logicalResource.substring( 1 );
687 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
688 DavResource resource =
689 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
690 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
692 resource.addLockManager( lockManager );
696 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
697 LogicalResource resource )
700 String path = resource.getPath();
701 if ( repositoryRequest.isSupportFile( path ) )
703 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
705 return ( proxiedFile != null );
708 // Is it a Metadata resource?
709 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
711 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
714 // Is it an Archetype Catalog?
715 if ( repositoryRequest.isArchetypeCatalog( path ) )
717 // FIXME we must implement a merge of remote archetype catalog from remote servers.
718 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
720 return ( proxiedFile != null );
723 // Not any of the above? Then it's gotta be an artifact reference.
726 // Get the artifact reference in a layout neutral way.
727 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
729 if ( artifact != null )
731 String repositoryLayout = managedRepository.getRepository().getLayout();
733 RepositoryStorage repositoryStorage =
734 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
735 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
737 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
739 resource.setPath( managedRepository.toPath( artifact ) );
741 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
742 artifact.getVersion() );
744 return ( proxiedFile != null );
747 catch ( LayoutException e )
751 catch ( ProxyDownloadException e )
753 log.error( e.getMessage(), e );
754 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
755 "Unable to fetch artifact resource." );
762 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
765 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
766 event.setRemoteIP( remoteIP );
768 for ( AuditListener listener : auditListeners )
770 listener.auditEvent( event );
774 public void addAuditListener( AuditListener listener )
776 this.auditListeners.add( listener );
779 public void clearAuditListeners()
781 this.auditListeners.clear();
784 public void removeAuditListener( AuditListener listener )
786 this.auditListeners.remove( listener );
789 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
791 // [MRM-503] - Metadata file need Pragma:no-cache response
793 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
794 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
796 response.setHeader( "Pragma", "no-cache" );
797 response.setHeader( "Cache-Control", "no-cache" );
798 response.setDateHeader( "Last-Modified", new Date().getTime() );
800 // if the resource is a directory don't cache it as new groupId deployed will be available
801 // without need of refreshing browser
804 // We need to specify this so connecting wagons can work correctly
805 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
807 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
810 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
813 if ( !( locator instanceof ArchivaDavResourceLocator ) )
815 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
816 "Locator does not implement RepositoryLocator" );
820 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
822 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
825 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
827 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
828 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
830 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
832 return archivaLocator;
835 private static class LogicalResource
839 public LogicalResource( String path )
844 public String getPath()
849 public void setPath( String path )
855 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
860 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
861 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
863 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
865 WebdavMethodUtil.getMethodPermission(
866 request.getMethod() ) );
868 catch ( AuthenticationException e )
870 // safety check for MRM-911
871 String guest = UserManager.GUEST_USERNAME;
874 if ( servletAuth.isAuthorized( guest,
875 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
876 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
881 catch ( UnauthorizedException ae )
883 throw new UnauthorizedDavException( repositoryId,
884 "You are not authenticated and authorized to access any repository." );
887 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
889 catch ( MustChangePasswordException e )
891 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
893 catch ( AccountLockedException e )
895 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
897 catch ( AuthorizationException e )
899 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
900 "Fatal Authorization Subsystem Error." );
902 catch ( UnauthorizedException e )
904 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
908 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
909 ArchivaDavResourceLocator locator,
910 RepositoryGroupConfiguration repositoryGroupConfiguration )
913 List<File> mergedRepositoryContents = new ArrayList<File>();
914 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
915 if ( path.startsWith( "/" ) )
917 path = path.substring( 1 );
919 LogicalResource logicalResource = new LogicalResource( path );
922 // if the current user logged in has permission to any of the repositories, allow user to
923 // browse the repo group but displaying only the repositories which the user has permission to access.
924 // otherwise, prompt for authentication.
926 String activePrincipal = getActivePrincipal( request );
928 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
931 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
936 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
939 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
940 mergedRepositoryContents.add( mergedRepoDir );
944 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
946 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
947 repositoryGroupConfiguration.getId() + "/"
948 + repositoryGroupConfiguration.getMergedIndexPath() );
949 if ( !tmpDirectory.exists() )
951 synchronized ( tmpDirectory.getAbsolutePath() )
953 if ( !tmpDirectory.exists() )
955 tmpDirectory.mkdirs();
959 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
961 for ( String repository : repositories )
963 ManagedRepositoryContent managedRepository = null;
967 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
969 catch ( RepositoryNotFoundException e )
971 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
972 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
974 catch ( RepositoryException e )
976 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
977 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
980 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
981 if ( resourceFile.exists() )
983 // in case of group displaying index directory doesn't have sense !!
984 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
985 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
987 if ( !new File( repoIndexDirectory ).isAbsolute() )
989 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
990 StringUtils.isEmpty( repoIndexDirectory )
992 : repoIndexDirectory ).getAbsolutePath();
995 if ( StringUtils.isEmpty( repoIndexDirectory ) )
997 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
998 ".indexer" ).getAbsolutePath();
1001 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1002 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1004 // for prompted authentication
1005 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1009 if ( isAuthorized( request, repository ) )
1011 mergedRepositoryContents.add( resourceFile );
1012 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1015 catch ( DavException e )
1017 // TODO: review exception handling
1019 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1020 activePrincipal, e.getMessage() );
1027 // for the current user logged in
1030 if ( servletAuth.isAuthorized( activePrincipal, repository,
1031 WebdavMethodUtil.getMethodPermission(
1032 request.getMethod() ) ) )
1034 mergedRepositoryContents.add( resourceFile );
1035 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1038 catch ( UnauthorizedException e )
1040 // TODO: review exception handling
1042 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1043 activePrincipal, e.getMessage() );
1054 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1057 ArchivaVirtualDavResource resource =
1058 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1061 // compatibility with MRM-440 to ensure browsing the repository group works ok
1062 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1064 throw new BrowserRedirectException( resource.getHref() );
1070 protected String getActivePrincipal( DavServletRequest request )
1072 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1073 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1077 * Check if the current user is authorized to access any of the repos
1080 * @param repositories
1081 * @param activePrincipal
1084 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1086 // when no repositories configured it's impossible to browse nothing !
1087 // at least make possible to see nothing :-)
1088 if ( repositories == null || repositories.isEmpty() )
1093 boolean allow = false;
1095 // if securitySession != null, it means that the user was prompted for authentication
1096 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1098 for ( String repository : repositories )
1102 if ( isAuthorized( request, repository ) )
1108 catch ( DavException e )
1116 for ( String repository : repositories )
1120 if ( servletAuth.isAuthorized( activePrincipal, repository,
1121 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1127 catch ( UnauthorizedException e )
1137 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1138 throws RepositoryMetadataException, DigesterException, IOException
1140 File outputFile = new File( outputFilename );
1141 if ( outputFile.exists() )
1143 FileUtils.deleteQuietly( outputFile );
1146 outputFile.getParentFile().mkdirs();
1147 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1149 createChecksumFile( outputFilename, digestSha1 );
1150 createChecksumFile( outputFilename, digestMd5 );
1155 private void createChecksumFile( String path, Digester digester )
1156 throws DigesterException, IOException
1158 File checksumFile = new File( path + digester.getFilenameExtension() );
1159 if ( !checksumFile.exists() )
1161 FileUtils.deleteQuietly( checksumFile );
1162 checksum.createChecksum( new File( path ), digester );
1164 else if ( !checksumFile.isFile() )
1166 log.error( "Checksum file is not a file." );
1170 private boolean isProjectReference( String requestedResource )
1174 metadataTools.toVersionedReference( requestedResource );
1177 catch ( RepositoryMetadataException re )
1183 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1184 DavServletRequest request,
1185 RepositoryGroupConfiguration repositoryGroupConfiguration )
1191 HttpSession session = request.getSession();
1193 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1194 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1195 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1196 if ( temporaryGroupIndexMap == null )
1198 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1201 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1203 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1205 if ( System.currentTimeMillis() - tmp.getCreationTime() > ( repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1207 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1208 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1209 indexMerger.cleanTemporaryGroupIndex( tmp );
1213 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1214 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1215 return tmp.getDirectory();
1219 Set<String> authzRepos = new HashSet<String>();
1220 for ( String repository : repositories )
1224 if ( servletAuth.isAuthorized( activePrincipal, repository,
1225 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1227 authzRepos.add( repository );
1228 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1231 catch ( UnauthorizedException e )
1233 // TODO: review exception handling
1235 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1239 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1240 repositoryGroupConfiguration.getId(), authzRepos );
1241 IndexingContext indexingContext = indexMerger.buildMergedIndex(
1242 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1243 repositoryGroupConfiguration.getMergedIndexPath(), repositoryGroupConfiguration.getMergedIndexTtl() ) );
1244 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1245 TemporaryGroupIndex temporaryGroupIndex = new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(),
1246 repositoryGroupConfiguration.getId(),repositoryGroupConfiguration.getMergedIndexTtl() )
1247 .setCreationTime(new Date().getTime() );
1248 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1249 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1250 temporaryGroupIndexMap );
1251 return mergedRepoDir;
1253 catch ( RepositoryAdminException e )
1255 throw new DavException( 500, e );
1257 catch ( IndexMergerException e )
1259 throw new DavException( 500, e );
1264 public void setServletAuth( ServletAuthenticator servletAuth )
1266 this.servletAuth = servletAuth;
1269 public void setHttpAuth( HttpAuthenticator httpAuth )
1271 this.httpAuth = httpAuth;
1274 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1276 this.scheduler = scheduler;
1279 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1281 this.archivaConfiguration = archivaConfiguration;
1284 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1286 this.repositoryFactory = repositoryFactory;
1289 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1291 this.repositoryRequest = repositoryRequest;
1294 public void setConnectors( RepositoryProxyConnectors connectors )
1296 this.connectors = connectors;
1299 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1301 return remoteRepositoryAdmin;
1304 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1306 this.remoteRepositoryAdmin = remoteRepositoryAdmin;