View Javadoc
1   /*
2    * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.internal.transport.sshd;
44  
45  import static java.text.MessageFormat.format;
46  
47  import java.io.IOException;
48  import java.nio.file.Path;
49  import java.security.GeneralSecurityException;
50  import java.security.KeyPair;
51  import java.util.ArrayList;
52  import java.util.Collection;
53  import java.util.Collections;
54  import java.util.Iterator;
55  import java.util.List;
56  import java.util.NoSuchElementException;
57  import java.util.concurrent.CancellationException;
58  
59  import org.eclipse.jgit.transport.sshd.KeyCache;
60  
61  /**
62   * A {@link EncryptedFileKeyPairProvider} that uses an external
63   * {@link KeyCache}.
64   */
65  public class CachingKeyPairProvider extends EncryptedFileKeyPairProvider {
66  
67  	private final KeyCache cache;
68  
69  	/**
70  	 * Creates a new {@link CachingKeyPairProvider} using the given
71  	 * {@link KeyCache}. If the cache is {@code null}, this is a simple
72  	 * {@link EncryptedFileKeyPairProvider}.
73  	 *
74  	 * @param paths
75  	 *            to load keys from
76  	 * @param cache
77  	 *            to use, may be {@code null} if no external caching is desired
78  	 */
79  	public CachingKeyPairProvider(List<Path> paths, KeyCache cache) {
80  		super(paths);
81  		this.cache = cache;
82  	}
83  
84  	@Override
85  	protected Iterable<KeyPair> loadKeys(Collection<? extends Path> resources) {
86  		if (resources.isEmpty()) {
87  			return Collections.emptyList();
88  		}
89  		return () -> new CancellingKeyPairIterator(resources);
90  	}
91  
92  	@Override
93  	protected KeyPair doLoadKey(Path resource)
94  			throws IOException, GeneralSecurityException {
95  		// By calling doLoadKey(String, Path, FilePasswordProvider) instead of
96  		// super.doLoadKey(Path) we can bypass the key caching in
97  		// AbstractResourceKeyPairProvider, over which we have no real control.
98  		String resourceId = resource.toString();
99  		if (cache == null) {
100 			return doLoadKey(resourceId, resource, getPasswordFinder());
101 		}
102 		Throwable t[] = { null };
103 		KeyPair key = cache.get(resource, p -> {
104 			try {
105 				return doLoadKey(resourceId, p, getPasswordFinder());
106 			} catch (IOException | GeneralSecurityException e) {
107 				t[0] = e;
108 				return null;
109 			}
110 		});
111 		if (t[0] != null) {
112 			if (t[0] instanceof CancellationException) {
113 				throw (CancellationException) t[0];
114 			}
115 			throw new IOException(
116 					format(SshdText.get().keyLoadFailed, resource), t[0]);
117 		}
118 		return key;
119 	}
120 
121 	private class CancellingKeyPairIterator implements Iterator<KeyPair> {
122 
123 		private final Iterator<Path> paths;
124 
125 		private KeyPair nextItem;
126 
127 		private boolean nextSet;
128 
129 		public CancellingKeyPairIterator(Collection<? extends Path> resources) {
130 			List<Path> copy = new ArrayList<>(resources.size());
131 			copy.addAll(resources);
132 			paths = copy.iterator();
133 		}
134 
135 		@Override
136 		public boolean hasNext() {
137 			if (nextSet) {
138 				return nextItem != null;
139 			}
140 			nextSet = true;
141 			while (nextItem == null && paths.hasNext()) {
142 				try {
143 					nextItem = doLoadKey(paths.next());
144 				} catch (CancellationException cancelled) {
145 					throw cancelled;
146 				} catch (Exception other) {
147 					log.warn(other.toString());
148 				}
149 			}
150 			return nextItem != null;
151 		}
152 
153 		@Override
154 		public KeyPair next() {
155 			if (!nextSet && !hasNext()) {
156 				throw new NoSuchElementException();
157 			}
158 			KeyPair result = nextItem;
159 			nextItem = null;
160 			nextSet = false;
161 			if (result == null) {
162 				throw new NoSuchElementException();
163 			}
164 			return result;
165 		}
166 
167 	}
168 }