]> source.dussan.org Git - archiva.git/blob
d6d3244809e4470739064b0c70deeeba92830432
[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.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  *
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     @Inject
114     private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
115
116     /**
117      * plexus.requirement
118      */
119     @Inject
120     private RepositoryContentFactory repositoryFactory;
121
122     /**
123      * plexus.requirement
124      */
125     private RepositoryRequest repositoryRequest;
126
127     /**
128      * plexus.requirement role-hint="default"
129      */
130     @Inject
131     @Named( value = "repositoryProxyConnectors#default" )
132     private RepositoryProxyConnectors connectors;
133
134     /**
135      * plexus.requirement
136      */
137     @Inject
138     private MetadataTools metadataTools;
139
140     /**
141      * plexus.requirement
142      */
143     @Inject
144     private MimeTypes mimeTypes;
145
146     /**
147      * plexus.requirement
148      */
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     private ChecksumFile checksum;
173
174     /**
175      * plexus.requirement role-hint="sha1"
176      */
177     private Digester digestSha1;
178
179     /**
180      * plexus.requirement role-hint="md5";
181      */
182     private Digester digestMd5;
183
184     /**
185      * plexus.requirement role="org.apache.archiva.scheduler.ArchivaTaskScheduler" role-hint="repository"
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                             log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
514                                            + managedRepository.getId() + "' (current user '" + activePrincipal + "')" );
515
516                             triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
517                                                logicalResource.getPath(), event, activePrincipal );
518                         }
519
520                         if ( !resourceFile.exists() )
521                         {
522                             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
523                         }
524                     }
525                 }
526             }
527
528             if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
529             {
530                 String resourcePath = logicalResource.getPath();
531
532                 // check if target repo is enabled for releases
533                 // we suppose that release-artifacts can be deployed only to repos enabled for releases
534                 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
535                     && !repositoryRequest.isSupportFile( resourcePath ) )
536                 {
537                     ArtifactReference artifact = null;
538                     try
539                     {
540                         artifact = managedRepository.toArtifactReference( resourcePath );
541
542                         if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
543                         {
544                             // check if artifact already exists and if artifact re-deployment to the repository is allowed
545                             if ( managedRepository.hasContent( artifact )
546                                 && managedRepository.getRepository().isBlockRedeployments() )
547                             {
548                                 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
549                                               + "' is not allowed." );
550                                 throw new DavException( HttpServletResponse.SC_CONFLICT,
551                                                         "Overwriting released artifacts is not allowed." );
552                             }
553                         }
554                     }
555                     catch ( LayoutException e )
556                     {
557                         log.warn( "Artifact path '" + resourcePath + "' is invalid." );
558                     }
559                 }
560
561                 /*
562                  * Create parent directories that don't exist when writing a file This actually makes this
563                  * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
564                  * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
565                  * create the collections themselves.
566                  */
567
568                 File rootDirectory = new File( managedRepository.getRepoRoot() );
569                 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
570
571                 if ( !destDir.exists() )
572                 {
573                     destDir.mkdirs();
574                     String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
575
576                     log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
577                                activePrincipal );
578
579                     triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
580                                        AuditEvent.CREATE_DIR, activePrincipal );
581                 }
582             }
583         }
584         return resource;
585     }
586
587     public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
588         throws DavException
589     {
590         ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
591
592         ManagedRepositoryContent managedRepository;
593         try
594         {
595             managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
596         }
597         catch ( RepositoryNotFoundException e )
598         {
599             throw new DavException( HttpServletResponse.SC_NOT_FOUND,
600                                     "Invalid repository: " + archivaLocator.getRepositoryId() );
601         }
602         catch ( RepositoryException e )
603         {
604             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
605         }
606
607         String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
608         if ( logicalResource.startsWith( "/" ) )
609         {
610             logicalResource = logicalResource.substring( 1 );
611         }
612         File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
613         DavResource resource =
614             new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
615                                     davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
616
617         resource.addLockManager( lockManager );
618         return resource;
619     }
620
621     private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
622                                              LogicalResource resource )
623         throws DavException
624     {
625         String path = resource.getPath();
626         if ( repositoryRequest.isSupportFile( path ) )
627         {
628             File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
629
630             return ( proxiedFile != null );
631         }
632
633         // Is it a Metadata resource?
634         if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
635         {
636             return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
637         }
638
639         // Not any of the above? Then it's gotta be an artifact reference.
640         try
641         {
642             // Get the artifact reference in a layout neutral way.
643             ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
644
645             if ( artifact != null )
646             {
647                 applyServerSideRelocation( managedRepository, artifact );
648
649                 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
650
651                 resource.setPath( managedRepository.toPath( artifact ) );
652
653                 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
654                                + artifact.getVersion() + "'" );
655
656                 return ( proxiedFile != null );
657             }
658         }
659         catch ( LayoutException e )
660         {
661             /* eat it */
662         }
663         catch ( ProxyDownloadException e )
664         {
665             log.error( e.getMessage(), e );
666             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
667                                     "Unable to fetch artifact resource." );
668         }
669         return false;
670     }
671
672     /**
673      * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
674      * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
675      * metadatas.
676      * <p/>
677      * For such clients, archiva does server-side relocation by reading itself the &lt;relocation&gt; element in
678      * metadatas and serving the expected artifact.
679      */
680     protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
681         throws ProxyDownloadException
682     {
683         if ( "pom".equals( artifact.getType() ) )
684         {
685             return;
686         }
687
688         // Build the artifact POM reference
689         ArtifactReference pomReference = new ArtifactReference();
690         pomReference.setGroupId( artifact.getGroupId() );
691         pomReference.setArtifactId( artifact.getArtifactId() );
692         pomReference.setVersion( artifact.getVersion() );
693         pomReference.setType( "pom" );
694
695         // Get the artifact POM from proxied repositories if needed
696         connectors.fetchFromProxies( managedRepository, pomReference );
697
698         // Open and read the POM from the managed repo
699         File pom = managedRepository.toFile( pomReference );
700
701         if ( !pom.exists() )
702         {
703             return;
704         }
705
706         try
707         {
708             // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
709             FileReader reader = new FileReader( pom );
710             Model model = null;
711             try
712             {
713                 model = new MavenXpp3Reader().read( reader );
714             }
715             finally
716             {
717                 if ( reader != null )
718                 {
719                     reader.close();
720                 }
721             }
722
723             DistributionManagement dist = model.getDistributionManagement();
724             if ( dist != null )
725             {
726                 Relocation relocation = dist.getRelocation();
727                 if ( relocation != null )
728                 {
729                     // artifact is relocated : update the repositoryPath
730                     if ( relocation.getGroupId() != null )
731                     {
732                         artifact.setGroupId( relocation.getGroupId() );
733                     }
734                     if ( relocation.getArtifactId() != null )
735                     {
736                         artifact.setArtifactId( relocation.getArtifactId() );
737                     }
738                     if ( relocation.getVersion() != null )
739                     {
740                         artifact.setVersion( relocation.getVersion() );
741                     }
742                 }
743             }
744         }
745         catch ( FileNotFoundException e )
746         {
747             // Artifact has no POM in repo : ignore
748         }
749         catch ( IOException e )
750         {
751             // Unable to read POM : ignore.
752         }
753         catch ( XmlPullParserException e )
754         {
755             // Invalid POM : ignore
756         }
757     }
758
759     // TODO: remove?
760
761     private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
762                                     String principal )
763     {
764         AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
765         event.setRemoteIP( remoteIP );
766
767         for ( AuditListener listener : auditListeners )
768         {
769             listener.auditEvent( event );
770         }
771     }
772
773     public void addAuditListener( AuditListener listener )
774     {
775         this.auditListeners.add( listener );
776     }
777
778     public void clearAuditListeners()
779     {
780         this.auditListeners.clear();
781     }
782
783     public void removeAuditListener( AuditListener listener )
784     {
785         this.auditListeners.remove( listener );
786     }
787
788     private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
789     {
790         // [MRM-503] - Metadata file need Pragma:no-cache response
791         // header.
792         if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
793         {
794             response.addHeader( "Pragma", "no-cache" );
795             response.addHeader( "Cache-Control", "no-cache" );
796         }
797
798         // We need to specify this so connecting wagons can work correctly
799         response.addDateHeader( "last-modified", resource.getModificationTime() );
800
801         // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
802     }
803
804     private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
805         throws DavException
806     {
807         if ( !( locator instanceof ArchivaDavResourceLocator ) )
808         {
809             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
810                                     "Locator does not implement RepositoryLocator" );
811         }
812
813         // Hidden paths
814         if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
815         {
816             throw new DavException( HttpServletResponse.SC_NOT_FOUND );
817         }
818
819         ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
820
821         // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
822         if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
823         {
824             throw new DavException( HttpServletResponse.SC_NO_CONTENT );
825         }
826         return archivaLocator;
827     }
828
829     private static class LogicalResource
830     {
831         private String path;
832
833         public LogicalResource( String path )
834         {
835             this.path = path;
836         }
837
838         public String getPath()
839         {
840             return path;
841         }
842
843         public void setPath( String path )
844         {
845             this.path = path;
846         }
847     }
848
849     protected boolean isAuthorized( DavServletRequest request, String repositoryId )
850         throws DavException
851     {
852         try
853         {
854             AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
855             SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
856
857             return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
858                                                                                                repositoryId,
859                                                                                                WebdavMethodUtil.getMethodPermission(
860                                                                                                    request.getMethod() ) );
861         }
862         catch ( AuthenticationException e )
863         {
864             // safety check for MRM-911
865             String guest = UserManager.GUEST_USERNAME;
866             try
867             {
868                 if ( servletAuth.isAuthorized( guest,
869                                                ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
870                                                WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
871                 {
872                     return true;
873                 }
874             }
875             catch ( UnauthorizedException ae )
876             {
877                 throw new UnauthorizedDavException( repositoryId,
878                                                     "You are not authenticated and authorized to access any repository." );
879             }
880
881             throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
882         }
883         catch ( MustChangePasswordException e )
884         {
885             throw new UnauthorizedDavException( repositoryId, "You must change your password." );
886         }
887         catch ( AccountLockedException e )
888         {
889             throw new UnauthorizedDavException( repositoryId, "User account is locked." );
890         }
891         catch ( AuthorizationException e )
892         {
893             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
894                                     "Fatal Authorization Subsystem Error." );
895         }
896         catch ( UnauthorizedException e )
897         {
898             throw new UnauthorizedDavException( repositoryId, e.getMessage() );
899         }
900     }
901
902     private DavResource getResource( DavServletRequest request, List<String> repositories,
903                                      ArchivaDavResourceLocator locator )
904         throws DavException
905     {
906         List<File> mergedRepositoryContents = new ArrayList<File>();
907         String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
908         if ( path.startsWith( "/" ) )
909         {
910             path = path.substring( 1 );
911         }
912         LogicalResource logicalResource = new LogicalResource( path );
913
914         // flow:
915         // if the current user logged in has permission to any of the repositories, allow user to
916         // browse the repo group but displaying only the repositories which the user has permission to access.
917         // otherwise, prompt for authentication.
918
919         String activePrincipal = getActivePrincipal( request );
920
921         boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
922
923         if ( allow )
924         {
925             for ( String repository : repositories )
926             {
927                 ManagedRepositoryContent managedRepository = null;
928
929                 try
930                 {
931                     managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
932                 }
933                 catch ( RepositoryNotFoundException e )
934                 {
935                     throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
936                                             "Invalid managed repository <" + repository + ">: " + e.getMessage() );
937                 }
938                 catch ( RepositoryException e )
939                 {
940                     throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
941                                             "Invalid managed repository <" + repository + ">: " + e.getMessage() );
942                 }
943
944                 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
945                 if ( resourceFile.exists() )
946                 {
947                     // for prompted authentication
948                     if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
949                     {
950                         try
951                         {
952                             if ( isAuthorized( request, repository ) )
953                             {
954                                 mergedRepositoryContents.add( resourceFile );
955                                 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
956                             }
957                         }
958                         catch ( DavException e )
959                         {
960                             // TODO: review exception handling
961                             log.debug(
962                                 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': "
963                                     + e.getMessage() );
964                         }
965                     }
966                     else
967                     {
968                         // for the current user logged in
969                         try
970                         {
971                             if ( servletAuth.isAuthorized( activePrincipal, repository,
972                                                            WebdavMethodUtil.getMethodPermission(
973                                                                request.getMethod() ) ) )
974                             {
975                                 mergedRepositoryContents.add( resourceFile );
976                                 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
977                             }
978                         }
979                         catch ( UnauthorizedException e )
980                         {
981                             // TODO: review exception handling
982                             log.debug(
983                                 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': "
984                                     + e.getMessage() );
985                         }
986                     }
987                 }
988             }
989         }
990         else
991         {
992             throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
993         }
994
995         ArchivaVirtualDavResource resource =
996             new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
997                                            this );
998
999         // compatibility with MRM-440 to ensure browsing the repository group works ok
1000         if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1001         {
1002             throw new BrowserRedirectException( resource.getHref() );
1003         }
1004
1005         return resource;
1006     }
1007
1008     protected String getActivePrincipal( DavServletRequest request )
1009     {
1010         User sessionUser = httpAuth.getSessionUser( request.getSession() );
1011         return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1012     }
1013
1014     /**
1015      * Check if the current user is authorized to access any of the repos
1016      *
1017      * @param request
1018      * @param repositories
1019      * @param activePrincipal
1020      * @return
1021      */
1022     private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1023     {
1024         boolean allow = false;
1025
1026         // if securitySession != null, it means that the user was prompted for authentication
1027         if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1028         {
1029             for ( String repository : repositories )
1030             {
1031                 try
1032                 {
1033                     if ( isAuthorized( request, repository ) )
1034                     {
1035                         allow = true;
1036                         break;
1037                     }
1038                 }
1039                 catch ( DavException e )
1040                 {
1041                     continue;
1042                 }
1043             }
1044         }
1045         else
1046         {
1047             for ( String repository : repositories )
1048             {
1049                 try
1050                 {
1051                     if ( servletAuth.isAuthorized( activePrincipal, repository,
1052                                                    WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1053                     {
1054                         allow = true;
1055                         break;
1056                     }
1057                 }
1058                 catch ( UnauthorizedException e )
1059                 {
1060                     continue;
1061                 }
1062             }
1063         }
1064
1065         return allow;
1066     }
1067
1068     private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1069         throws RepositoryMetadataException, DigesterException, IOException
1070     {
1071         File outputFile = new File( outputFilename );
1072         if ( outputFile.exists() )
1073         {
1074             FileUtils.deleteQuietly( outputFile );
1075         }
1076
1077         outputFile.getParentFile().mkdirs();
1078         RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1079
1080         createChecksumFile( outputFilename, digestSha1 );
1081         createChecksumFile( outputFilename, digestMd5 );
1082
1083         return outputFile;
1084     }
1085
1086     private void createChecksumFile( String path, Digester digester )
1087         throws DigesterException, IOException
1088     {
1089         File checksumFile = new File( path + digester.getFilenameExtension() );
1090         if ( !checksumFile.exists() )
1091         {
1092             FileUtils.deleteQuietly( checksumFile );
1093             checksum.createChecksum( new File( path ), digester );
1094         }
1095         else if ( !checksumFile.isFile() )
1096         {
1097             log.error( "Checksum file is not a file." );
1098         }
1099     }
1100
1101     private boolean isProjectReference( String requestedResource )
1102     {
1103         try
1104         {
1105             metadataTools.toVersionedReference( requestedResource );
1106             return false;
1107         }
1108         catch ( RepositoryMetadataException re )
1109         {
1110             return true;
1111         }
1112     }
1113
1114     public void setServletAuth( ServletAuthenticator servletAuth )
1115     {
1116         this.servletAuth = servletAuth;
1117     }
1118
1119     public void setHttpAuth( HttpAuthenticator httpAuth )
1120     {
1121         this.httpAuth = httpAuth;
1122     }
1123
1124     public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1125     {
1126         this.scheduler = scheduler;
1127     }
1128
1129     public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1130     {
1131         this.archivaConfiguration = archivaConfiguration;
1132     }
1133
1134     public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1135     {
1136         this.repositoryFactory = repositoryFactory;
1137     }
1138
1139     public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1140     {
1141         this.repositoryRequest = repositoryRequest;
1142     }
1143
1144     public void setConnectors( RepositoryProxyConnectors connectors )
1145     {
1146         this.connectors = connectors;
1147     }
1148 }