1 package org.apache.maven.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
23 import java.io.FileNotFoundException;
24 import java.io.FileReader;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
31 import javax.servlet.http.HttpServletResponse;
33 import org.apache.commons.lang.StringUtils;
34 import org.apache.jackrabbit.webdav.DavException;
35 import org.apache.jackrabbit.webdav.DavResource;
36 import org.apache.jackrabbit.webdav.DavResourceFactory;
37 import org.apache.jackrabbit.webdav.DavResourceLocator;
38 import org.apache.jackrabbit.webdav.DavServletRequest;
39 import org.apache.jackrabbit.webdav.DavServletResponse;
40 import org.apache.jackrabbit.webdav.DavSession;
41 import org.apache.jackrabbit.webdav.lock.LockManager;
42 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
43 import org.apache.maven.archiva.common.utils.PathUtil;
44 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
45 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
46 import org.apache.maven.archiva.model.ArtifactReference;
47 import org.apache.maven.archiva.model.ProjectReference;
48 import org.apache.maven.archiva.model.VersionedReference;
49 import org.apache.maven.archiva.policies.ProxyDownloadException;
50 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
51 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
52 import org.apache.maven.archiva.repository.RepositoryContentFactory;
53 import org.apache.maven.archiva.repository.RepositoryException;
54 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
55 import org.apache.maven.archiva.repository.audit.AuditEvent;
56 import org.apache.maven.archiva.repository.audit.AuditListener;
57 import org.apache.maven.archiva.repository.audit.Auditable;
58 import org.apache.maven.archiva.repository.content.RepositoryRequest;
59 import org.apache.maven.archiva.repository.layout.LayoutException;
60 import org.apache.maven.archiva.repository.metadata.MetadataTools;
61 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
62 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
63 import org.apache.maven.archiva.security.ArchivaXworkUser;
64 import org.apache.maven.archiva.security.ServletAuthenticator;
65 import org.apache.maven.archiva.webdav.util.MimeTypes;
66 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
67 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
68 import org.apache.maven.model.DistributionManagement;
69 import org.apache.maven.model.Model;
70 import org.apache.maven.model.Relocation;
71 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
72 import org.codehaus.plexus.redback.authentication.AuthenticationException;
73 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
74 import org.codehaus.plexus.redback.authorization.AuthorizationException;
75 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
76 import org.codehaus.plexus.redback.policy.AccountLockedException;
77 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
78 import org.codehaus.plexus.redback.system.SecuritySession;
79 import org.codehaus.plexus.redback.system.SecuritySystemConstants;
80 import org.codehaus.plexus.redback.xwork.filter.authentication.HttpAuthenticator;
81 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
85 import com.opensymphony.xwork.ActionContext;
88 * @author <a href="mailto:james@atlassian.com">James William Dumay</a>
89 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
91 public class ArchivaDavResourceFactory
92 implements DavResourceFactory, Auditable
94 private static final String PROXIED_SUFFIX = " (proxied)";
96 private static final String HTTP_PUT_METHOD = "PUT";
98 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
101 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
103 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
106 * @plexus.requirement
108 private RepositoryContentFactory repositoryFactory;
111 * @plexus.requirement
113 private RepositoryRequest repositoryRequest;
116 * @plexus.requirement role-hint="default"
118 private RepositoryProxyConnectors connectors;
121 * @plexus.requirement
123 private MetadataTools metadataTools;
126 * @plexus.requirement
128 private MimeTypes mimeTypes;
131 * @plexus.requirement
133 private ArchivaConfiguration archivaConfiguration;
136 * @plexus.requirement
138 private ServletAuthenticator servletAuth;
141 * @plexus.requirement role-hint="basic"
143 private HttpAuthenticator httpAuth;
147 * Lock Manager - use simple implementation from JackRabbit
149 private final LockManager lockManager = new SimpleLockManager();
151 /** @plexus.requirement */
152 private RepositoryContentConsumers consumers;
154 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
155 final DavServletResponse response )
158 checkLocatorIsInstanceOfRepositoryLocator( locator );
159 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
161 RepositoryGroupConfiguration repoGroupConfig =
162 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
163 List<String> repositories = new ArrayList<String>();
165 boolean isGet = WebdavMethodUtil.isReadMethod( request.getMethod() );
166 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
168 if ( repoGroupConfig != null )
170 if( WebdavMethodUtil.isWriteMethod( request.getMethod() ) )
172 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
173 "Write method not allowed for repository groups." );
175 repositories.addAll( repoGroupConfig.getRepositories() );
177 // handle browse requests for virtual repos
178 if ( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ).endsWith( "/" ) )
180 return getResource( request, repositories, archivaLocator );
185 repositories.add( archivaLocator.getRepositoryId() );
188 //MRM-419 - Windows Webdav support. Should not 404 if there is no content.
189 if (StringUtils.isEmpty(archivaLocator.getRepositoryId()))
191 throw new DavException(HttpServletResponse.SC_NO_CONTENT);
194 List<DavResource> availableResources = new ArrayList<DavResource>();
195 DavException e = null;
197 for ( String repositoryId : repositories )
199 ManagedRepositoryContent managedRepository = null;
203 managedRepository = getManagedRepository( repositoryId );
205 catch ( DavException de )
207 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
208 repositoryId + ">" );
211 DavResource resource = null;
212 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
214 if ( managedRepository != null )
218 if( isAuthorized( request, repositoryId ) )
220 LogicalResource logicalResource =
221 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
225 resource = doGet( managedRepository, request, archivaLocator, logicalResource );
230 resource = doPut( managedRepository, request, archivaLocator, logicalResource );
234 catch ( DavException de )
240 if( resource == null )
242 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
246 availableResources.add( resource );
251 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Repository does not exist" );
256 if (availableResources.isEmpty())
261 if ( request.getRequestURI().endsWith( "metadata.xml" ) )
263 // TODO MRM-872 : must merge all available metadatas
264 // use RepositoryMetadataMerge for the merging of the versions
266 // Deng: I'll continue this tomorrow, everything is getting blurry now
269 DavResource resource = availableResources.get( 0 );
270 setHeaders(response, locator, resource );
272 // compatibility with MRM-440 to ensure browsing the repository works ok
273 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
275 throw new BrowserRedirectException( resource.getHref() );
277 resource.addLockManager(lockManager);
281 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
284 checkLocatorIsInstanceOfRepositoryLocator( locator );
285 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
287 DavResource resource = null;
288 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
290 ManagedRepositoryContent managedRepository = getManagedRepository( archivaLocator.getRepositoryId() );
291 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
292 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
294 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
295 managedRepository.getRepository(), davSession, archivaLocator, this, mimeTypes,
296 auditListeners, consumers );
298 resource.addLockManager(lockManager);
302 private DavResource doGet( ManagedRepositoryContent managedRepository, DavServletRequest request,
303 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
306 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
307 ArchivaDavResource resource =
308 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
309 managedRepository.getRepository(), request.getRemoteAddr(),
310 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
312 if ( !resource.isCollection() )
314 boolean previouslyExisted = resourceFile.exists();
316 // At this point the incoming request can either be in default or
317 // legacy layout format.
318 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
322 // Perform an adjustment of the resource to the managed
323 // repository expected path.
324 String localResourcePath =
325 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
326 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
328 catch ( LayoutException e )
330 if ( previouslyExisted )
334 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
337 // Attempt to fetch the resource from any defined proxy.
340 String repositoryId = locator.getRepositoryId();
341 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) + PROXIED_SUFFIX;
342 triggerAuditEvent( request.getRemoteAddr(), repositoryId, logicalResource.getPath(), event );
345 if ( !resourceFile.exists() )
352 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
353 managedRepository.getRepository(), request.getRemoteAddr(),
354 request.getDavSession(), locator, this, mimeTypes, auditListeners,
361 private DavResource doPut( ManagedRepositoryContent managedRepository, DavServletRequest request,
362 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
366 * Create parent directories that don't exist when writing a file This actually makes this implementation not
367 * compliant to the WebDAV RFC - but we have enough knowledge about how the collection is being used to do this
368 * reasonably and some versions of Maven's WebDAV don't correctly create the collections themselves.
371 File rootDirectory = new File( managedRepository.getRepoRoot() );
372 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
373 if ( request.getMethod().equals(HTTP_PUT_METHOD) && !destDir.exists() )
376 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
377 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath, AuditEvent.CREATE_DIR );
380 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
382 return new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
383 managedRepository.getRepository(), request.getRemoteAddr(),
384 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
387 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
388 LogicalResource resource )
391 if ( repositoryRequest.isSupportFile( resource.getPath() ) )
393 // Checksums are fetched with artifact / metadata.
395 // Need to adjust the path for the checksum resource.
399 // Is it a Metadata resource?
400 if ( repositoryRequest.isDefault( resource.getPath() ) && repositoryRequest.isMetadata( resource.getPath() ) )
402 return fetchMetadataFromProxies( managedRepository, request, resource );
405 // Not any of the above? Then it's gotta be an artifact reference.
408 // Get the artifact reference in a layout neutral way.
409 ArtifactReference artifact = repositoryRequest.toArtifactReference( resource.getPath() );
411 if ( artifact != null )
413 applyServerSideRelocation( managedRepository, artifact );
415 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
417 resource.setPath( managedRepository.toPath( artifact ) );
419 return ( proxiedFile != null );
422 catch ( LayoutException e )
426 catch ( ProxyDownloadException e )
428 log.error( e.getMessage(), e );
429 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
434 private boolean fetchMetadataFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
435 LogicalResource resource )
438 ProjectReference project;
439 VersionedReference versioned;
444 versioned = metadataTools.toVersionedReference( resource.getPath() );
445 if ( versioned != null )
447 connectors.fetchFromProxies( managedRepository, versioned );
451 catch ( RepositoryMetadataException e )
458 project = metadataTools.toProjectReference( resource.getPath() );
459 if ( project != null )
461 connectors.fetchFromProxies( managedRepository, project );
465 catch ( RepositoryMetadataException e )
474 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
475 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
478 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
479 * metadatas and serving the expected artifact.
481 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
482 throws ProxyDownloadException
484 if ( "pom".equals( artifact.getType() ) )
489 // Build the artifact POM reference
490 ArtifactReference pomReference = new ArtifactReference();
491 pomReference.setGroupId( artifact.getGroupId() );
492 pomReference.setArtifactId( artifact.getArtifactId() );
493 pomReference.setVersion( artifact.getVersion() );
494 pomReference.setType( "pom" );
496 // Get the artifact POM from proxied repositories if needed
497 connectors.fetchFromProxies( managedRepository, pomReference );
499 // Open and read the POM from the managed repo
500 File pom = managedRepository.toFile( pomReference );
509 Model model = new MavenXpp3Reader().read( new FileReader( pom ) );
510 DistributionManagement dist = model.getDistributionManagement();
513 Relocation relocation = dist.getRelocation();
514 if ( relocation != null )
516 // artifact is relocated : update the repositoryPath
517 if ( relocation.getGroupId() != null )
519 artifact.setGroupId( relocation.getGroupId() );
521 if ( relocation.getArtifactId() != null )
523 artifact.setArtifactId( relocation.getArtifactId() );
525 if ( relocation.getVersion() != null )
527 artifact.setVersion( relocation.getVersion() );
532 catch ( FileNotFoundException e )
534 // Artifact has no POM in repo : ignore
536 catch ( IOException e )
538 // Unable to read POM : ignore.
540 catch ( XmlPullParserException e )
542 // Invalid POM : ignore
547 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
549 String activePrincipal = ArchivaXworkUser.getActivePrincipal( ActionContext.getContext().getSession() );
550 AuditEvent event = new AuditEvent( repositoryId, activePrincipal, resource, action );
551 event.setRemoteIP( remoteIP );
553 for ( AuditListener listener : auditListeners )
555 listener.auditEvent( event );
559 public void addAuditListener( AuditListener listener )
561 this.auditListeners.add( listener );
564 public void clearAuditListeners()
566 this.auditListeners.clear();
569 public void removeAuditListener( AuditListener listener )
571 this.auditListeners.remove( listener );
574 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
576 // [MRM-503] - Metadata file need Pragma:no-cache response
578 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
580 response.addHeader( "Pragma", "no-cache" );
581 response.addHeader( "Cache-Control", "no-cache" );
584 //We need to specify this so connecting wagons can work correctly
585 response.addDateHeader("last-modified", resource.getModificationTime());
587 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
590 private ManagedRepositoryContent getManagedRepository( String respositoryId )
593 if ( respositoryId != null )
597 return repositoryFactory.getManagedRepositoryContent( respositoryId );
599 catch ( RepositoryNotFoundException e )
601 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
603 catch ( RepositoryException e )
605 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
611 private void checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
614 if ( !( locator instanceof RepositoryLocator ) )
616 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
617 "Locator does not implement RepositoryLocator" );
621 class LogicalResource
625 public LogicalResource( String path )
630 public String getPath()
635 public void setPath( String path )
641 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
646 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
647 SecuritySession securitySession = httpAuth.getSecuritySession();
649 return servletAuth.isAuthenticated( request, result ) &&
650 servletAuth.isAuthorized( request, securitySession, repositoryId,
651 WebdavMethodUtil.isWriteMethod( request.getMethod() ) );
653 catch ( AuthenticationException e )
655 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
657 catch ( MustChangePasswordException e )
659 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
661 catch ( AccountLockedException e )
663 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
665 catch ( AuthorizationException e )
667 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
668 "Fatal Authorization Subsystem Error." );
670 catch ( UnauthorizedException e )
672 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
676 private DavResource getResource( DavServletRequest request, List<String> repositories, ArchivaDavResourceLocator locator )
679 List<File> mergedRepositoryContents = new ArrayList<File>();
680 LogicalResource logicalResource =
681 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
684 // if the current user logged in has permission to any of the repositories, allow user to
685 // browse the repo group but displaying only the repositories which the user has permission to access.
686 // otherwise, prompt for authentication.
688 // put the current session in the session map which will be passed to ArchivaXworkUser
689 Map<String, Object> sessionMap = new HashMap<String, Object>();
690 if( request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) != null )
692 sessionMap.put( SecuritySystemConstants.SECURITY_SESSION_KEY,
693 request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) );
696 String activePrincipal = ArchivaXworkUser.getActivePrincipal( sessionMap );
697 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
701 for( String repository : repositories )
703 // for prompted authentication
704 if( httpAuth.getSecuritySession() != null )
708 if( isAuthorized( request, repository ) )
710 getResource( locator, mergedRepositoryContents, logicalResource, repository );
713 catch ( DavException e )
720 // for the current user logged in
723 if( servletAuth.isAuthorizedToAccessVirtualRepository( activePrincipal, repository ) )
725 getResource( locator, mergedRepositoryContents, logicalResource, repository );
728 catch ( UnauthorizedException e )
737 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
740 ArchivaVirtualDavResource resource =
741 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this );
743 // compatibility with MRM-440 to ensure browsing the repository group works ok
744 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
746 throw new BrowserRedirectException( resource.getHref() );
752 private void getResource( ArchivaDavResourceLocator locator, List<File> mergedRepositoryContents,
753 LogicalResource logicalResource, String repository )
756 ManagedRepositoryContent managedRepository = null;
760 managedRepository = getManagedRepository( repository );
762 catch ( DavException de )
764 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
768 if ( !locator.getResourcePath().startsWith( ArchivaVirtualDavResource.HIDDEN_PATH_PREFIX ) )
770 if( managedRepository != null )
772 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
773 if( resourceFile.exists() )
775 mergedRepositoryContents.add( resourceFile );
782 * Check if the current user is authorized to access any of the repos
785 * @param repositories
786 * @param activePrincipal
789 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
791 boolean allow = false;
794 // if securitySession != null, it means that the user was prompted for authentication
795 if( httpAuth.getSecuritySession() != null )
797 for( String repository : repositories )
801 if( isAuthorized( request, repository ) )
807 catch( DavException e )
815 for( String repository : repositories )
819 if( servletAuth.isAuthorizedToAccessVirtualRepository( activePrincipal, repository ) )
825 catch ( UnauthorizedException e )