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