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