]> source.dussan.org Git - archiva.git/blob
0884c649e558f895a4fc6b2e6a95acd2d0b9cd5e
[archiva.git] /
1 package org.apache.maven.archiva.webdav;
2
3 /*
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
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
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
19  * under the License.
20  */
21
22 import org.apache.archiva.audit.AuditEvent;
23 import org.apache.archiva.audit.AuditListener;
24 import org.apache.archiva.audit.Auditable;
25 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
26 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
27 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
28 import org.apache.commons.io.FileUtils;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.jackrabbit.webdav.DavException;
31 import org.apache.jackrabbit.webdav.DavResource;
32 import org.apache.jackrabbit.webdav.DavResourceFactory;
33 import org.apache.jackrabbit.webdav.DavResourceLocator;
34 import org.apache.jackrabbit.webdav.DavServletRequest;
35 import org.apache.jackrabbit.webdav.DavServletResponse;
36 import org.apache.jackrabbit.webdav.DavSession;
37 import org.apache.jackrabbit.webdav.lock.LockManager;
38 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
39 import org.apache.maven.archiva.common.utils.PathUtil;
40 import org.apache.maven.archiva.common.utils.VersionUtil;
41 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
42 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
43 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
44 import org.apache.maven.archiva.model.ArtifactReference;
45 import org.apache.maven.archiva.policies.ProxyDownloadException;
46 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
47 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
48 import org.apache.maven.archiva.repository.RepositoryContentFactory;
49 import org.apache.maven.archiva.repository.RepositoryException;
50 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
51 import org.apache.maven.archiva.repository.content.LegacyPathParser;
52 import org.apache.maven.archiva.repository.content.RepositoryRequest;
53 import org.apache.maven.archiva.repository.layout.LayoutException;
54 import org.apache.maven.archiva.repository.metadata.MetadataTools;
55 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
56 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
57 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
58 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
59 import org.apache.maven.archiva.security.ServletAuthenticator;
60 import org.apache.maven.archiva.webdav.util.MimeTypes;
61 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
62 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
63 import org.apache.maven.model.DistributionManagement;
64 import org.apache.maven.model.Model;
65 import org.apache.maven.model.Relocation;
66 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
67 import org.codehaus.plexus.digest.ChecksumFile;
68 import org.codehaus.plexus.digest.Digester;
69 import org.codehaus.plexus.digest.DigesterException;
70 import org.codehaus.plexus.redback.authentication.AuthenticationException;
71 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
72 import org.codehaus.plexus.redback.authorization.AuthorizationException;
73 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
74 import org.codehaus.plexus.redback.policy.AccountLockedException;
75 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
76 import org.codehaus.plexus.redback.system.SecuritySession;
77 import org.codehaus.plexus.redback.users.User;
78 import org.codehaus.plexus.redback.users.UserManager;
79 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
80 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83 import org.springframework.context.ApplicationContext;
84 import org.springframework.stereotype.Service;
85
86 import javax.annotation.PostConstruct;
87 import javax.inject.Inject;
88 import javax.inject.Named;
89 import javax.servlet.http.HttpServletResponse;
90 import java.io.File;
91 import java.io.FileNotFoundException;
92 import java.io.FileReader;
93 import java.io.IOException;
94 import java.util.ArrayList;
95 import java.util.List;
96
97 /**
98  * plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
99  */
100 @Service( "davResourceFactory#archiva" )
101 public class ArchivaDavResourceFactory
102     implements DavResourceFactory, Auditable
103 {
104     private static final String PROXIED_SUFFIX = " (proxied)";
105
106     private static final String HTTP_PUT_METHOD = "PUT";
107
108     private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
109
110     /**
111      * plexus.requirement role="org.apache.archiva.audit.AuditListener"
112      */
113     private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
114
115     /**
116      * plexus.requirement
117      */
118     @Inject
119     private RepositoryContentFactory repositoryFactory;
120
121     /**
122      * plexus.requirement
123      */
124     private RepositoryRequest repositoryRequest;
125
126     /**
127      * plexus.requirement role-hint="default"
128      */
129     @Inject
130     @Named( value = "repositoryProxyConnectors#default" )
131     private RepositoryProxyConnectors connectors;
132
133     /**
134      * plexus.requirement
135      */
136     @Inject
137     private MetadataTools metadataTools;
138
139     /**
140      * plexus.requirement
141      */
142     @Inject
143     private MimeTypes mimeTypes;
144
145     /**
146      * plexus.requirement
147      */
148     //Inject
149     private ArchivaConfiguration archivaConfiguration;
150
151     /**
152      * plexus.requirement
153      */
154     @Inject
155     private ServletAuthenticator servletAuth;
156
157     /**
158      * plexus.requirement role-hint="basic"
159      */
160     @Inject
161     @Named( value = "httpAuthenticator#basic" )
162     private HttpAuthenticator httpAuth;
163
164     /**
165      * Lock Manager - use simple implementation from JackRabbit
166      */
167     private final LockManager lockManager = new SimpleLockManager();
168
169     /**
170      * plexus.requirement
171      */
172     //Inject
173     private ChecksumFile checksum;
174
175     /**
176      * plexus.requirement role-hint="sha1"
177      */
178     //Inject
179     //Named( value = "digester#sha1" )
180     private Digester digestSha1;
181
182     /**
183      * plexus.requirement role-hint="md5";
184      */
185     //Inject
186     //Named( value = "digester#md5" )
187     private Digester digestMd5;
188
189     /**
190      * plexus.requirement role="org.apache.archiva.scheduler.ArchivaTaskScheduler" role-hint="repository"
191      */
192     @Inject
193     @Named( value = "archivaTaskScheduler#repository" )
194     private RepositoryArchivaTaskScheduler scheduler;
195
196     //Inject
197     private ApplicationContext applicationContext;
198
199     @Inject
200     public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
201                                       ArchivaConfiguration archivaConfiguration )
202         throws PlexusSisuBridgeException
203     {
204         this.archivaConfiguration = archivaConfiguration;
205         this.applicationContext = applicationContext;
206         this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
207
208         this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
209         this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
210
211         repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
212         this.auditListeners =
213             new ArrayList<AuditListener>( applicationContext.getBeansOfType( AuditListener.class ).values() );
214     }
215
216     @PostConstruct
217     public void initialize()
218     {
219
220
221     }
222
223     public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
224                                        final DavServletResponse response )
225         throws DavException
226     {
227         ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
228
229         RepositoryGroupConfiguration repoGroupConfig =
230             archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
231
232         String activePrincipal = getActivePrincipal( request );
233
234         List<String> resourcesInAbsolutePath = new ArrayList<String>();
235
236         boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
237         DavResource resource;
238         if ( repoGroupConfig != null )
239         {
240             if ( !readMethod )
241             {
242                 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
243                                         "Write method not allowed for repository groups." );
244             }
245
246             log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
247
248             // handle browse requests for virtual repos
249             if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
250             {
251                 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
252             }
253             else
254             {
255                 // make a copy to avoid potential concurrent modifications (eg. by configuration)
256                 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
257                 //  infrequent
258                 ArrayList<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
259                 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
260                                                    resourcesInAbsolutePath );
261             }
262         }
263         else
264         {
265             ManagedRepositoryContent managedRepository = null;
266
267             try
268             {
269                 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
270             }
271             catch ( RepositoryNotFoundException e )
272             {
273                 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
274                                         "Invalid repository: " + archivaLocator.getRepositoryId() );
275             }
276             catch ( RepositoryException e )
277             {
278                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
279             }
280
281             log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
282
283             resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
284
285             String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
286             resourcesInAbsolutePath.add(
287                 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
288         }
289
290         String requestedResource = request.getRequestURI();
291
292         // MRM-872 : merge all available metadata
293         // merge metadata only when requested via the repo group
294         if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
295             requestedResource ) ) && repoGroupConfig != null )
296         {
297             // this should only be at the project level not version level!
298             if ( isProjectReference( requestedResource ) )
299             {
300                 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
301                 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
302
303                 ArchivaDavResource res = (ArchivaDavResource) resource;
304                 String filePath =
305                     StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
306                                                      "/" );
307                 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
308
309                 // for MRM-872 handle checksums of the merged metadata files
310                 if ( repositoryRequest.isSupportFile( requestedResource ) )
311                 {
312                     File metadataChecksum =
313                         new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
314                     if ( metadataChecksum.exists() )
315                     {
316                         LogicalResource logicalResource =
317                             new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
318
319                         resource =
320                             new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
321                                                     request.getRemoteAddr(), activePrincipal, request.getDavSession(),
322                                                     archivaLocator, this, mimeTypes, auditListeners, scheduler );
323                     }
324                 }
325                 else
326                 {
327                     if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
328                     {
329                         // merge the metadata of all repos under group
330                         ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
331                         for ( String resourceAbsPath : resourcesInAbsolutePath )
332                         {
333                             try
334                             {
335                                 File metadataFile = new File( resourceAbsPath );
336                                 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
337                                 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
338                             }
339                             catch ( RepositoryMetadataException r )
340                             {
341                                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
342                                                         "Error occurred while reading metadata file." );
343                             }
344                         }
345
346                         try
347                         {
348                             File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
349
350                             LogicalResource logicalResource = new LogicalResource(
351                                 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
352
353                             resource =
354                                 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
355                                                         request.getRemoteAddr(), activePrincipal,
356                                                         request.getDavSession(), archivaLocator, this, mimeTypes,
357                                                         auditListeners, scheduler );
358                         }
359                         catch ( RepositoryMetadataException r )
360                         {
361                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
362                                                     "Error occurred while writing metadata file." );
363                         }
364                         catch ( IOException ie )
365                         {
366                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
367                                                     "Error occurred while generating checksum files." );
368                         }
369                         catch ( DigesterException de )
370                         {
371                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
372                                                     "Error occurred while generating checksum files." );
373                         }
374                     }
375                 }
376             }
377         }
378
379         setHeaders( response, locator, resource );
380
381         // compatibility with MRM-440 to ensure browsing the repository works ok
382         if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
383         {
384             throw new BrowserRedirectException( resource.getHref() );
385         }
386         resource.addLockManager( lockManager );
387         return resource;
388     }
389
390     private DavResource processRepositoryGroup( final DavServletRequest request,
391                                                 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
392                                                 String activePrincipal, List<String> resourcesInAbsolutePath )
393         throws DavException
394     {
395         DavResource resource = null;
396         List<DavException> storedExceptions = new ArrayList<DavException>();
397
398         for ( String repositoryId : repositories )
399         {
400             ManagedRepositoryContent managedRepository;
401             try
402             {
403                 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
404             }
405             catch ( RepositoryNotFoundException e )
406             {
407                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
408             }
409             catch ( RepositoryException e )
410             {
411                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
412             }
413
414             try
415             {
416                 DavResource updatedResource =
417                     processRepository( request, archivaLocator, activePrincipal, managedRepository );
418                 if ( resource == null )
419                 {
420                     resource = updatedResource;
421                 }
422
423                 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
424                 if ( logicalResource.endsWith( "/" ) )
425                 {
426                     logicalResource = logicalResource.substring( 1 );
427                 }
428                 resourcesInAbsolutePath.add(
429                     new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
430             }
431             catch ( DavException e )
432             {
433                 storedExceptions.add( e );
434             }
435         }
436
437         if ( resource == null )
438         {
439             if ( !storedExceptions.isEmpty() )
440             {
441                 // MRM-1232
442                 for ( DavException e : storedExceptions )
443                 {
444                     if ( 401 == e.getErrorCode() )
445                     {
446                         throw e;
447                     }
448                 }
449
450                 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
451             }
452             else
453             {
454                 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
455             }
456         }
457         return resource;
458     }
459
460     private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
461                                            String activePrincipal, ManagedRepositoryContent managedRepository )
462         throws DavException
463     {
464         DavResource resource = null;
465         if ( isAuthorized( request, managedRepository.getId() ) )
466         {
467             String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
468             if ( path.startsWith( "/" ) )
469             {
470                 path = path.substring( 1 );
471             }
472             LogicalResource logicalResource = new LogicalResource( path );
473             File resourceFile = new File( managedRepository.getRepoRoot(), path );
474             resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
475                                                request.getRemoteAddr(), activePrincipal, request.getDavSession(),
476                                                archivaLocator, this, mimeTypes, auditListeners, scheduler );
477
478             if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
479             {
480                 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
481                 {
482                     // force a resource not found
483                     throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
484                 }
485                 else
486                 {
487                     if ( !resource.isCollection() )
488                     {
489                         boolean previouslyExisted = resourceFile.exists();
490
491                         // Attempt to fetch the resource from any defined proxy.
492                         boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
493
494                         // At this point the incoming request can either be in default or
495                         // legacy layout format.
496                         try
497                         {
498                             // Perform an adjustment of the resource to the managed
499                             // repository expected path.
500                             String localResourcePath =
501                                 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
502                             resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
503                             resource =
504                                 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
505                                                         managedRepository.getRepository(), request.getRemoteAddr(),
506                                                         activePrincipal, request.getDavSession(), archivaLocator, this,
507                                                         mimeTypes, auditListeners, scheduler );
508                         }
509                         catch ( LayoutException e )
510                         {
511                             if ( !resourceFile.exists() )
512                             {
513                                 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
514                             }
515                         }
516
517                         if ( fromProxy )
518                         {
519                             String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
520                                 + PROXIED_SUFFIX;
521
522                             log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
523                                            + managedRepository.getId() + "' (current user '" + activePrincipal + "')" );
524
525                             triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
526                                                logicalResource.getPath(), event, activePrincipal );
527                         }
528
529                         if ( !resourceFile.exists() )
530                         {
531                             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
532                         }
533                     }
534                 }
535             }
536
537             if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
538             {
539                 String resourcePath = logicalResource.getPath();
540
541                 // check if target repo is enabled for releases
542                 // we suppose that release-artifacts can be deployed only to repos enabled for releases
543                 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
544                     && !repositoryRequest.isSupportFile( resourcePath ) )
545                 {
546                     ArtifactReference artifact = null;
547                     try
548                     {
549                         artifact = managedRepository.toArtifactReference( resourcePath );
550
551                         if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
552                         {
553                             // check if artifact already exists and if artifact re-deployment to the repository is allowed
554                             if ( managedRepository.hasContent( artifact )
555                                 && managedRepository.getRepository().isBlockRedeployments() )
556                             {
557                                 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
558                                               + "' is not allowed." );
559                                 throw new DavException( HttpServletResponse.SC_CONFLICT,
560                                                         "Overwriting released artifacts is not allowed." );
561                             }
562                         }
563                     }
564                     catch ( LayoutException e )
565                     {
566                         log.warn( "Artifact path '" + resourcePath + "' is invalid." );
567                     }
568                 }
569
570                 /*
571                  * Create parent directories that don't exist when writing a file This actually makes this
572                  * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
573                  * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
574                  * create the collections themselves.
575                  */
576
577                 File rootDirectory = new File( managedRepository.getRepoRoot() );
578                 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
579
580                 if ( !destDir.exists() )
581                 {
582                     destDir.mkdirs();
583                     String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
584
585                     log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
586                                activePrincipal );
587
588                     triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
589                                        AuditEvent.CREATE_DIR, activePrincipal );
590                 }
591             }
592         }
593         return resource;
594     }
595
596     public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
597         throws DavException
598     {
599         ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
600
601         ManagedRepositoryContent managedRepository;
602         try
603         {
604             managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
605         }
606         catch ( RepositoryNotFoundException e )
607         {
608             throw new DavException( HttpServletResponse.SC_NOT_FOUND,
609                                     "Invalid repository: " + archivaLocator.getRepositoryId() );
610         }
611         catch ( RepositoryException e )
612         {
613             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
614         }
615
616         String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
617         if ( logicalResource.startsWith( "/" ) )
618         {
619             logicalResource = logicalResource.substring( 1 );
620         }
621         File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
622         DavResource resource =
623             new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
624                                     davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
625
626         resource.addLockManager( lockManager );
627         return resource;
628     }
629
630     private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
631                                              LogicalResource resource )
632         throws DavException
633     {
634         String path = resource.getPath();
635         if ( repositoryRequest.isSupportFile( path ) )
636         {
637             File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
638
639             return ( proxiedFile != null );
640         }
641
642         // Is it a Metadata resource?
643         if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
644         {
645             return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
646         }
647
648         // Not any of the above? Then it's gotta be an artifact reference.
649         try
650         {
651             // Get the artifact reference in a layout neutral way.
652             ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
653
654             if ( artifact != null )
655             {
656                 applyServerSideRelocation( managedRepository, artifact );
657
658                 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
659
660                 resource.setPath( managedRepository.toPath( artifact ) );
661
662                 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
663                                + artifact.getVersion() + "'" );
664
665                 return ( proxiedFile != null );
666             }
667         }
668         catch ( LayoutException e )
669         {
670             /* eat it */
671         }
672         catch ( ProxyDownloadException e )
673         {
674             log.error( e.getMessage(), e );
675             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
676                                     "Unable to fetch artifact resource." );
677         }
678         return false;
679     }
680
681     /**
682      * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
683      * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
684      * metadatas.
685      * <p/>
686      * For such clients, archiva does server-side relocation by reading itself the &lt;relocation&gt; element in
687      * metadatas and serving the expected artifact.
688      */
689     protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
690         throws ProxyDownloadException
691     {
692         if ( "pom".equals( artifact.getType() ) )
693         {
694             return;
695         }
696
697         // Build the artifact POM reference
698         ArtifactReference pomReference = new ArtifactReference();
699         pomReference.setGroupId( artifact.getGroupId() );
700         pomReference.setArtifactId( artifact.getArtifactId() );
701         pomReference.setVersion( artifact.getVersion() );
702         pomReference.setType( "pom" );
703
704         // Get the artifact POM from proxied repositories if needed
705         connectors.fetchFromProxies( managedRepository, pomReference );
706
707         // Open and read the POM from the managed repo
708         File pom = managedRepository.toFile( pomReference );
709
710         if ( !pom.exists() )
711         {
712             return;
713         }
714
715         try
716         {
717             // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
718             FileReader reader = new FileReader( pom );
719             Model model = null;
720             try
721             {
722                 model = new MavenXpp3Reader().read( reader );
723             }
724             finally
725             {
726                 if ( reader != null )
727                 {
728                     reader.close();
729                 }
730             }
731
732             DistributionManagement dist = model.getDistributionManagement();
733             if ( dist != null )
734             {
735                 Relocation relocation = dist.getRelocation();
736                 if ( relocation != null )
737                 {
738                     // artifact is relocated : update the repositoryPath
739                     if ( relocation.getGroupId() != null )
740                     {
741                         artifact.setGroupId( relocation.getGroupId() );
742                     }
743                     if ( relocation.getArtifactId() != null )
744                     {
745                         artifact.setArtifactId( relocation.getArtifactId() );
746                     }
747                     if ( relocation.getVersion() != null )
748                     {
749                         artifact.setVersion( relocation.getVersion() );
750                     }
751                 }
752             }
753         }
754         catch ( FileNotFoundException e )
755         {
756             // Artifact has no POM in repo : ignore
757         }
758         catch ( IOException e )
759         {
760             // Unable to read POM : ignore.
761         }
762         catch ( XmlPullParserException e )
763         {
764             // Invalid POM : ignore
765         }
766     }
767
768     // TODO: remove?
769
770     private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
771                                     String principal )
772     {
773         AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
774         event.setRemoteIP( remoteIP );
775
776         for ( AuditListener listener : auditListeners )
777         {
778             listener.auditEvent( event );
779         }
780     }
781
782     public void addAuditListener( AuditListener listener )
783     {
784         this.auditListeners.add( listener );
785     }
786
787     public void clearAuditListeners()
788     {
789         this.auditListeners.clear();
790     }
791
792     public void removeAuditListener( AuditListener listener )
793     {
794         this.auditListeners.remove( listener );
795     }
796
797     private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
798     {
799         // [MRM-503] - Metadata file need Pragma:no-cache response
800         // header.
801         if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
802         {
803             response.addHeader( "Pragma", "no-cache" );
804             response.addHeader( "Cache-Control", "no-cache" );
805         }
806
807         // We need to specify this so connecting wagons can work correctly
808         response.addDateHeader( "last-modified", resource.getModificationTime() );
809
810         // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
811     }
812
813     private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
814         throws DavException
815     {
816         if ( !( locator instanceof ArchivaDavResourceLocator ) )
817         {
818             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
819                                     "Locator does not implement RepositoryLocator" );
820         }
821
822         // Hidden paths
823         if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
824         {
825             throw new DavException( HttpServletResponse.SC_NOT_FOUND );
826         }
827
828         ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
829
830         // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
831         if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
832         {
833             throw new DavException( HttpServletResponse.SC_NO_CONTENT );
834         }
835         return archivaLocator;
836     }
837
838     private static class LogicalResource
839     {
840         private String path;
841
842         public LogicalResource( String path )
843         {
844             this.path = path;
845         }
846
847         public String getPath()
848         {
849             return path;
850         }
851
852         public void setPath( String path )
853         {
854             this.path = path;
855         }
856     }
857
858     protected boolean isAuthorized( DavServletRequest request, String repositoryId )
859         throws DavException
860     {
861         try
862         {
863             AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
864             SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
865
866             return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
867                                                                                                repositoryId,
868                                                                                                WebdavMethodUtil.getMethodPermission(
869                                                                                                    request.getMethod() ) );
870         }
871         catch ( AuthenticationException e )
872         {
873             // safety check for MRM-911
874             String guest = UserManager.GUEST_USERNAME;
875             try
876             {
877                 if ( servletAuth.isAuthorized( guest,
878                                                ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
879                                                WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
880                 {
881                     return true;
882                 }
883             }
884             catch ( UnauthorizedException ae )
885             {
886                 throw new UnauthorizedDavException( repositoryId,
887                                                     "You are not authenticated and authorized to access any repository." );
888             }
889
890             throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
891         }
892         catch ( MustChangePasswordException e )
893         {
894             throw new UnauthorizedDavException( repositoryId, "You must change your password." );
895         }
896         catch ( AccountLockedException e )
897         {
898             throw new UnauthorizedDavException( repositoryId, "User account is locked." );
899         }
900         catch ( AuthorizationException e )
901         {
902             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
903                                     "Fatal Authorization Subsystem Error." );
904         }
905         catch ( UnauthorizedException e )
906         {
907             throw new UnauthorizedDavException( repositoryId, e.getMessage() );
908         }
909     }
910
911     private DavResource getResource( DavServletRequest request, List<String> repositories,
912                                      ArchivaDavResourceLocator locator )
913         throws DavException
914     {
915         List<File> mergedRepositoryContents = new ArrayList<File>();
916         String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
917         if ( path.startsWith( "/" ) )
918         {
919             path = path.substring( 1 );
920         }
921         LogicalResource logicalResource = new LogicalResource( path );
922
923         // flow:
924         // if the current user logged in has permission to any of the repositories, allow user to
925         // browse the repo group but displaying only the repositories which the user has permission to access.
926         // otherwise, prompt for authentication.
927
928         String activePrincipal = getActivePrincipal( request );
929
930         boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
931
932         if ( allow )
933         {
934             for ( String repository : repositories )
935             {
936                 ManagedRepositoryContent managedRepository = null;
937
938                 try
939                 {
940                     managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
941                 }
942                 catch ( RepositoryNotFoundException e )
943                 {
944                     throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
945                                             "Invalid managed repository <" + repository + ">: " + e.getMessage() );
946                 }
947                 catch ( RepositoryException e )
948                 {
949                     throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
950                                             "Invalid managed repository <" + repository + ">: " + e.getMessage() );
951                 }
952
953                 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
954                 if ( resourceFile.exists() )
955                 {
956                     // for prompted authentication
957                     if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
958                     {
959                         try
960                         {
961                             if ( isAuthorized( request, repository ) )
962                             {
963                                 mergedRepositoryContents.add( resourceFile );
964                                 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
965                             }
966                         }
967                         catch ( DavException e )
968                         {
969                             // TODO: review exception handling
970                             log.debug(
971                                 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': "
972                                     + e.getMessage() );
973                         }
974                     }
975                     else
976                     {
977                         // for the current user logged in
978                         try
979                         {
980                             if ( servletAuth.isAuthorized( activePrincipal, repository,
981                                                            WebdavMethodUtil.getMethodPermission(
982                                                                request.getMethod() ) ) )
983                             {
984                                 mergedRepositoryContents.add( resourceFile );
985                                 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
986                             }
987                         }
988                         catch ( UnauthorizedException e )
989                         {
990                             // TODO: review exception handling
991                             log.debug(
992                                 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': "
993                                     + e.getMessage() );
994                         }
995                     }
996                 }
997             }
998         }
999         else
1000         {
1001             throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1002         }
1003
1004         ArchivaVirtualDavResource resource =
1005             new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1006                                            this );
1007
1008         // compatibility with MRM-440 to ensure browsing the repository group works ok
1009         if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1010         {
1011             throw new BrowserRedirectException( resource.getHref() );
1012         }
1013
1014         return resource;
1015     }
1016
1017     protected String getActivePrincipal( DavServletRequest request )
1018     {
1019         User sessionUser = httpAuth.getSessionUser( request.getSession() );
1020         return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1021     }
1022
1023     /**
1024      * Check if the current user is authorized to access any of the repos
1025      *
1026      * @param request
1027      * @param repositories
1028      * @param activePrincipal
1029      * @return
1030      */
1031     private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1032     {
1033         boolean allow = false;
1034
1035         // if securitySession != null, it means that the user was prompted for authentication
1036         if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1037         {
1038             for ( String repository : repositories )
1039             {
1040                 try
1041                 {
1042                     if ( isAuthorized( request, repository ) )
1043                     {
1044                         allow = true;
1045                         break;
1046                     }
1047                 }
1048                 catch ( DavException e )
1049                 {
1050                     continue;
1051                 }
1052             }
1053         }
1054         else
1055         {
1056             for ( String repository : repositories )
1057             {
1058                 try
1059                 {
1060                     if ( servletAuth.isAuthorized( activePrincipal, repository,
1061                                                    WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1062                     {
1063                         allow = true;
1064                         break;
1065                     }
1066                 }
1067                 catch ( UnauthorizedException e )
1068                 {
1069                     continue;
1070                 }
1071             }
1072         }
1073
1074         return allow;
1075     }
1076
1077     private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1078         throws RepositoryMetadataException, DigesterException, IOException
1079     {
1080         File outputFile = new File( outputFilename );
1081         if ( outputFile.exists() )
1082         {
1083             FileUtils.deleteQuietly( outputFile );
1084         }
1085
1086         outputFile.getParentFile().mkdirs();
1087         RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1088
1089         createChecksumFile( outputFilename, digestSha1 );
1090         createChecksumFile( outputFilename, digestMd5 );
1091
1092         return outputFile;
1093     }
1094
1095     private void createChecksumFile( String path, Digester digester )
1096         throws DigesterException, IOException
1097     {
1098         File checksumFile = new File( path + digester.getFilenameExtension() );
1099         if ( !checksumFile.exists() )
1100         {
1101             FileUtils.deleteQuietly( checksumFile );
1102             checksum.createChecksum( new File( path ), digester );
1103         }
1104         else if ( !checksumFile.isFile() )
1105         {
1106             log.error( "Checksum file is not a file." );
1107         }
1108     }
1109
1110     private boolean isProjectReference( String requestedResource )
1111     {
1112         try
1113         {
1114             metadataTools.toVersionedReference( requestedResource );
1115             return false;
1116         }
1117         catch ( RepositoryMetadataException re )
1118         {
1119             return true;
1120         }
1121     }
1122
1123     public void setServletAuth( ServletAuthenticator servletAuth )
1124     {
1125         this.servletAuth = servletAuth;
1126     }
1127
1128     public void setHttpAuth( HttpAuthenticator httpAuth )
1129     {
1130         this.httpAuth = httpAuth;
1131     }
1132
1133     public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1134     {
1135         this.scheduler = scheduler;
1136     }
1137
1138     public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1139     {
1140         this.archivaConfiguration = archivaConfiguration;
1141     }
1142
1143     public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1144     {
1145         this.repositoryFactory = repositoryFactory;
1146     }
1147
1148     public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1149     {
1150         this.repositoryRequest = repositoryRequest;
1151     }
1152
1153     public void setConnectors( RepositoryProxyConnectors connectors )
1154     {
1155         this.connectors = connectors;
1156     }
1157 }