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