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