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