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