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