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