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