You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ArchivaDavResourceFactory.java 64KB

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