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