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