HttpUtil .java

net.minecraft.util.HttpUtil (class): members: DownloadProgressListener, getAvailablePort, isPortAvailable, requestedHash, downloadFile, targetDir, headers.

net.minecraft.utilclass229 linescommon6.9 KB

API Surface (3)

Path downloadFile(final Path targetDir, final URL url, final Map<String, String> headers, final HashFunction hashFunction, final @Nullable HashCode requestedHash, final int maxSize, final Proxy proxy, final HttpUtil.DownloadProgressListener listener)
int getAvailablePort()
boolean isPortAvailable(final int port)

Fields & Constants (9)

LOGGER
targetDir
url
headers
hashFunction
requestedHash
maxSize
proxy
input

String literals (11)

"Failed to remove existing file "
", limit is "
"Hash of downloaded file ("
") did not match requested ("
"download"
".tmp"
"Failed to read response from server"
"Failed to download file "
", limit was "
"INTERRUPTED"
"Download interrupted"

Code Graph: Dependencies (2)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

HttpUtil.java229 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.util;
2
3
import com.google.common.hash.Funnels;
4
import com.google.common.hash.HashCode;
5
import com.google.common.hash.HashFunction;
6
import com.google.common.hash.Hasher;
7
import com.mojang.logging.LogUtils;
8
import java.io.IOException;
9
import java.io.InputStream;
10
import java.io.OutputStream;
11
import java.io.UncheckedIOException;
12
import java.net.HttpURLConnection;
13
import java.net.Proxy;
14
import java.net.ServerSocket;
15
import java.net.URL;
16
import java.nio.charset.StandardCharsets;
17
import java.nio.file.Files;
18
import java.nio.file.Path;
19
import java.nio.file.StandardCopyOption;
20
import java.nio.file.StandardOpenOption;
21
import java.nio.file.attribute.FileTime;
22
import java.time.Instant;
23
import java.util.Map;
24
import java.util.OptionalLong;
25
import org.apache.commons.io.IOUtils;
26
import org.jspecify.annotations.Nullable;
27
import org.slf4j.Logger;
28
29
public class HttpUtil {
30
	private static final Logger LOGGER = LogUtils.getLogger();
31
32
	private HttpUtil() {
33
	}
34
35
	public static Path downloadFile(
36
		final Path targetDir,
37
		final URL url,
38
		final Map<String, String> headers,
39
		final HashFunction hashFunction,
40
		final @Nullable HashCode requestedHash,
41
		final int maxSize,
42
		final Proxy proxy,
43
		final HttpUtil.DownloadProgressListener listener
44
	) {
45
		HttpURLConnection connection = null;
46
		InputStream input = null;
47
		listener.requestStart();
48
		Path targetFile;
49
		if (requestedHash != null) {
50
			targetFile = cachedFilePath(targetDir, requestedHash);
51
52
			try {
53
				if (checkExistingFile(targetFile, hashFunction, requestedHash)) {
54
					LOGGER.info("Returning cached file since actual hash matches requested");
55
					listener.requestFinished(true);
56
					updateModificationTime(targetFile);
57
					return targetFile;
58
				}
59
			} catch (IOException e) {
60
				LOGGER.warn("Failed to check cached file {}", targetFile, e);
61
			}
62
63
			try {
64
				LOGGER.warn("Existing file {} not found or had mismatched hash", targetFile);
65
				Files.deleteIfExists(targetFile);
66
			} catch (IOException e) {
67
				listener.requestFinished(false);
68
				throw new UncheckedIOException("Failed to remove existing file " + targetFile, e);
69
			}
70
		} else {
71
			targetFile = null;
72
		}
73
74
		try {
75
			connection = (HttpURLConnection)url.openConnection(proxy);
76
			connection.setInstanceFollowRedirects(true);
77
			headers.forEach(connection::setRequestProperty);
78
			input = connection.getInputStream();
79
			long contentLength = connection.getContentLengthLong();
80
			OptionalLong size = contentLength != -1L ? OptionalLong.of(contentLength) : OptionalLong.empty();
81
			FileUtil.createDirectoriesSafe(targetDir);
82
			listener.downloadStart(size);
83
			if (size.isPresent() && size.getAsLong() > maxSize) {
84
				throw new IOException("Filesize is bigger than maximum allowed (file is " + size + ", limit is " + maxSize + ")");
85
			}
86
87
			if (targetFile != null) {
88
				HashCode actualHash = downloadAndHash(hashFunction, maxSize, listener, input, targetFile);
89
				if (!actualHash.equals(requestedHash)) {
90
					throw new IOException("Hash of downloaded file (" + actualHash + ") did not match requested (" + requestedHash + ")");
91
				}
92
93
				listener.requestFinished(true);
94
				return targetFile;
95
			} else {
96
				Path tmpPath = Files.createTempFile(targetDir, "download", ".tmp");
97
98
				try {
99
					HashCode actualHash = downloadAndHash(hashFunction, maxSize, listener, input, tmpPath);
100
					Path actualPath = cachedFilePath(targetDir, actualHash);
101
					if (!checkExistingFile(actualPath, hashFunction, actualHash)) {
102
						Files.move(tmpPath, actualPath, StandardCopyOption.REPLACE_EXISTING);
103
					} else {
104
						updateModificationTime(actualPath);
105
					}
106
107
					listener.requestFinished(true);
108
					return actualPath;
109
				} finally {
110
					Files.deleteIfExists(tmpPath);
111
				}
112
			}
113
		} catch (Throwable t) {
114
			if (connection != null) {
115
				InputStream error = connection.getErrorStream();
116
				if (error != null) {
117
					try {
118
						LOGGER.error("HTTP response error: {}", IOUtils.toString(error, StandardCharsets.UTF_8));
119
					} catch (Exception e) {
120
						LOGGER.error("Failed to read response from server");
121
					}
122
				}
123
			}
124
125
			listener.requestFinished(false);
126
			throw new IllegalStateException("Failed to download file " + url, t);
127
		} finally {
128
			IOUtils.closeQuietly(input);
129
		}
130
	}
131
132
	private static void updateModificationTime(final Path targetFile) {
133
		try {
134
			Files.setLastModifiedTime(targetFile, FileTime.from(Instant.now()));
135
		} catch (IOException e) {
136
			LOGGER.warn("Failed to update modification time of {}", targetFile, e);
137
		}
138
	}
139
140
	private static HashCode hashFile(final Path file, final HashFunction hashFunction) throws IOException {
141
		Hasher hasher = hashFunction.newHasher();
142
143
		try (
144
			OutputStream outputStream = Funnels.asOutputStream(hasher);
145
			InputStream fileInput = Files.newInputStream(file);
146
		) {
147
			fileInput.transferTo(outputStream);
148
		}
149
150
		return hasher.hash();
151
	}
152
153
	private static boolean checkExistingFile(final Path file, final HashFunction hashFunction, final HashCode expectedHash) throws IOException {
154
		if (Files.exists(file)) {
155
			HashCode actualHash = hashFile(file, hashFunction);
156
			if (actualHash.equals(expectedHash)) {
157
				return true;
158
			}
159
160
			LOGGER.warn("Mismatched hash of file {}, expected {} but found {}", file, expectedHash, actualHash);
161
		}
162
163
		return false;
164
	}
165
166
	private static Path cachedFilePath(final Path targetDir, final HashCode requestedHash) {
167
		return targetDir.resolve(requestedHash.toString());
168
	}
169
170
	private static HashCode downloadAndHash(
171
		final HashFunction hashFunction, final int maxSize, final HttpUtil.DownloadProgressListener listener, final InputStream input, final Path downloadFile
172
	) throws IOException {
173
		try (OutputStream output = Files.newOutputStream(downloadFile, StandardOpenOption.CREATE)) {
174
			Hasher hasher = hashFunction.newHasher();
175
			byte[] buffer = new byte[8196];
176
			long readSoFar = 0L;
177
178
			int read;
179
			while ((read = input.read(buffer)) >= 0) {
180
				readSoFar += read;
181
				listener.downloadedBytes(readSoFar);
182
				if (readSoFar > maxSize) {
183
					throw new IOException("Filesize was bigger than maximum allowed (got >= " + readSoFar + ", limit was " + maxSize + ")");
184
				}
185
186
				if (Thread.interrupted()) {
187
					LOGGER.error("INTERRUPTED");
188
					throw new IOException("Download interrupted");
189
				}
190
191
				output.write(buffer, 0, read);
192
				hasher.putBytes(buffer, 0, read);
193
			}
194
195
			return hasher.hash();
196
		}
197
	}
198
199
	public static int getAvailablePort() {
200
		try (ServerSocket server = new ServerSocket(0)) {
201
			return server.getLocalPort();
202
		} catch (IOException ignored) {
203
			return 25564;
204
		}
205
	}
206
207
	public static boolean isPortAvailable(final int port) {
208
		if (port >= 0 && port <= 65535) {
209
			try (ServerSocket server = new ServerSocket(port)) {
210
				return server.getLocalPort() == port;
211
			} catch (IOException ignored) {
212
				return false;
213
			}
214
		} else {
215
			return false;
216
		}
217
	}
218
219
	public interface DownloadProgressListener {
220
		void requestStart();
221
222
		void downloadStart(OptionalLong sizeBytes);
223
224
		void downloadedBytes(long bytesSoFar);
225
226
		void requestFinished(boolean success);
227
	}
228
}
229

Decompiled Minecraft 26.3 source of HttpUtil (net/minecraft/util/HttpUtil.java) with Mojang official mappings, stored verbatim on the site.