Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JENKINS-72203] Revert jenkinsci/jenkins#8565 #8637

Merged
merged 1 commit into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 1 addition & 8 deletions core/src/main/java/hudson/FilePath.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
Expand Down Expand Up @@ -3339,13 +3338,7 @@
@Restricted(NoExternalUse.class)
static class UrlFactory {
public URL newURL(String location) throws MalformedURLException {
try {
return new URI(location).toURL();
} catch (URISyntaxException e) {
MalformedURLException mex = new MalformedURLException(e.getMessage());
mex.initCause(e);
throw mex;
}
return new URL(location);

Check warning on line 3341 in core/src/main/java/hudson/FilePath.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 3341 is not covered by tests
}
}

Expand Down
5 changes: 3 additions & 2 deletions core/src/main/java/hudson/Functions.java
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -1938,11 +1939,11 @@
String url = Jenkins.get().getRootUrl();
try {
if (url != null) {
String host = new URI(url).toURL().getHost();
String host = new URL(url).getHost();
if (host != null)
return host;
}
} catch (MalformedURLException | URISyntaxException e) {
} catch (MalformedURLException e) {

Check warning on line 1946 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 1942-1946 are not covered by tests
// fall back to HTTP request
}
return Stapler.getCurrentRequest().getServerName();
Expand Down
13 changes: 6 additions & 7 deletions core/src/main/java/hudson/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
import java.io.Writer;
import java.net.HttpRetryException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -100,101 +99,101 @@
if (!home.endsWith("/")) home = home + '/'; // make sure it ends with '/'

// check for authentication info
String auth = new URI(home).toURL().getUserInfo();
String auth = new URL(home).getUserInfo();
if (auth != null) auth = "Basic " + new Base64Encoder().encode(auth.getBytes(StandardCharsets.UTF_8));

{ // check if the home is set correctly
HttpURLConnection con = open(new URI(home).toURL());
HttpURLConnection con = open(new URL(home));
if (auth != null) con.setRequestProperty("Authorization", auth);
con.connect();
if (con.getResponseCode() != 200
|| con.getHeaderField("X-Hudson") == null) {
System.err.println(home + " is not Hudson (" + con.getResponseMessage() + ")");
return -1;
}
}

URL jobURL = new URI(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/").toURL();
URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");

{ // check if the job name is correct
HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
if (auth != null) con.setRequestProperty("Authorization", auth);
con.connect();
if (con.getResponseCode() != 200) {
System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " " + con.getResponseMessage() + ")");
return -1;
}
}

// get a crumb to pass the csrf check
String crumbField = null, crumbValue = null;
try {
HttpURLConnection con = open(new URI(home +
"crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'").toURL());
HttpURLConnection con = open(new URL(home +
"crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
if (auth != null) con.setRequestProperty("Authorization", auth);
String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8");
String[] components = line.split(":");
if (components.length == 2) {
crumbField = components[0];
crumbValue = components[1];
}
} catch (IOException e) {
// presumably this Hudson doesn't use CSRF protection
}

// write the output to a temporary file first.
File tmpFile = File.createTempFile("jenkins", "log");
try {
int ret;
try (OutputStream os = Files.newOutputStream(tmpFile.toPath());
Writer w = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
w.write("<?xml version='1.1' encoding='UTF-8'?>");
w.write("<run><log encoding='hexBinary' content-encoding='" + Charset.defaultCharset().name() + "'>");
w.flush();

// run the command
long start = System.currentTimeMillis();

List<String> cmd = new ArrayList<>(Arrays.asList(args).subList(1, args.length));
Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]), (String[]) null, System.in,
new DualOutputStream(System.out, new EncodingStream(os)));

ret = proc.join();

w.write("</log><result>" + ret + "</result><duration>" + (System.currentTimeMillis() - start) + "</duration></run>");
} catch (InvalidPathException e) {
throw new IOException(e);
}

URL location = new URL(jobURL, "postBuildResult");
while (true) {
try {
// start a remote connection
HttpURLConnection con = open(location);
if (auth != null) con.setRequestProperty("Authorization", auth);
if (crumbField != null && crumbValue != null) {
con.setRequestProperty(crumbField, crumbValue);
}
con.setDoOutput(true);
// this tells HttpURLConnection not to buffer the whole thing
con.setFixedLengthStreamingMode((int) tmpFile.length());
con.connect();
// send the data
try (InputStream in = Files.newInputStream(tmpFile.toPath())) {
org.apache.commons.io.IOUtils.copy(in, con.getOutputStream());
} catch (InvalidPathException e) {
throw new IOException(e);
}

if (con.getResponseCode() != 200) {
org.apache.commons.io.IOUtils.copy(con.getErrorStream(), System.err);
}

return ret;
} catch (HttpRetryException e) {
if (e.getLocation() != null) {
// retry with the new location
location = new URI(e.getLocation()).toURL();
location = new URL(e.getLocation());

Check warning on line 196 in core/src/main/java/hudson/Main.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 102-196 are not covered by tests
continue;
}
// otherwise failed for reasons beyond us.
Expand Down
6 changes: 3 additions & 3 deletions core/src/main/java/hudson/PluginManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -1846,7 +1846,7 @@

@Override
public void copy(File target) throws Exception {
try (InputStream input = ProxyConfiguration.getInputStream(new URI(url).toURL())) {
try (InputStream input = ProxyConfiguration.getInputStream(new URL(url))) {
Files.copy(input, target.toPath());
}
}
Expand Down Expand Up @@ -1948,15 +1948,15 @@
@RequirePOST public FormValidation doCheckPluginUrl(StaplerRequest request, @QueryParameter String value) throws IOException {
if (StringUtils.isNotBlank(value)) {
try {
URL url = new URI(value).toURL();
URL url = new URL(value);
if (!url.getProtocol().startsWith("http")) {
return FormValidation.error(Messages.PluginManager_invalidUrl());
}

if (!url.getProtocol().equals("https")) {
return FormValidation.warning(Messages.PluginManager_insecureUrl());
}
} catch (MalformedURLException | URISyntaxException e) {
} catch (MalformedURLException e) {

Check warning on line 1959 in core/src/main/java/hudson/PluginManager.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 1951-1959 are not covered by tests
return FormValidation.error(e.getMessage());
}
}
Expand Down
27 changes: 12 additions & 15 deletions core/src/main/java/hudson/TcpSlaveAgentListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@
import java.io.SequenceInputStream;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.ServerSocketChannel;
import java.nio.charset.StandardCharsets;
import java.security.interfaces.RSAPublicKey;
Expand Down Expand Up @@ -85,7 +85,8 @@
public final int configuredPort;

/**
* @param port Use 0 to choose a random port.
* @param port
* Use 0 to choose a random port.
*/
public TcpSlaveAgentListener(int port) throws IOException {
super("TCP agent listener port=" + port);
Expand Down Expand Up @@ -119,7 +120,6 @@

/**
* Gets the TCP port number in which we are advertising.
*
* @since 1.656
*/
public int getAdvertisedPort() {
Expand All @@ -128,23 +128,21 @@

/**
* Gets the host name that we advertise protocol clients to connect to.
*
* @since 2.198
*/
public String getAdvertisedHost() {
if (CLI_HOST_NAME != null) {
return CLI_HOST_NAME;
return CLI_HOST_NAME;
}
try {
return new URI(Jenkins.get().getRootUrl()).getHost();
} catch (URISyntaxException e) {
return new URL(Jenkins.get().getRootUrl()).getHost();
} catch (MalformedURLException e) {

Check warning on line 139 in core/src/main/java/hudson/TcpSlaveAgentListener.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 138-139 are not covered by tests
throw new IllegalStateException("Could not get TcpSlaveAgentListener host name", e);
}
}

/**
* Gets the Base64 encoded public key that forms part of this instance's identity keypair.
*
* @return the Base64 encoded public key
* @since 2.16
*/
Expand All @@ -167,7 +165,6 @@

/**
* Gets Remoting minimum supported version to prevent unsupported agents from connecting
*
* @since 2.171
*/
public VersionNumber getRemotingMinimumVersion() {
Expand Down Expand Up @@ -231,9 +228,9 @@

private final class ConnectionHandler extends Thread {
private static final String DEFAULT_RESPONSE_404 = "HTTP/1.0 404 Not Found\r\n" +
"Content-Type: text/plain;charset=UTF-8\r\n" +
"\r\n" +
"Not Found\r\n";
"Content-Type: text/plain;charset=UTF-8\r\n" +
"\r\n" +
"Not Found\r\n";
private final Socket s;
/**
* Unique number to identify this connection. Used in the log.
Expand Down Expand Up @@ -410,8 +407,8 @@
socket.getRemoteSocketAddress(),
new String(ping, StandardCharsets.UTF_8),
responseLength > 0 && responseLength <= response.length ?
new String(response, 0, responseLength, StandardCharsets.UTF_8) :
"bad response length " + responseLength,
new String(response, 0, responseLength, StandardCharsets.UTF_8) :
"bad response length " + responseLength,
});
return false;
}
Expand Down
6 changes: 2 additions & 4 deletions core/src/main/java/hudson/cli/InstallPluginCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@
import hudson.util.VersionNumber;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
Expand Down Expand Up @@ -106,16 +104,16 @@

// is this an URL?
try {
URL u = new URI(source).toURL();
URL u = new URL(source);
stdout.println(Messages.InstallPluginCommand_InstallingPluginFromUrl(u));
File f = getTmpFile();
FileUtils.copyURLToFile(u, f); // TODO JENKINS-58248 proxy
f = moveToFinalLocation(f);
if (dynamicLoad) {
pm.dynamicLoad(f);
}
continue;
} catch (MalformedURLException | URISyntaxException e) {
} catch (MalformedURLException e) {

Check warning on line 116 in core/src/main/java/hudson/cli/InstallPluginCommand.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 107-116 are not covered by tests
// not an URL
}

Expand Down
32 changes: 15 additions & 17 deletions core/src/main/java/hudson/model/DownloadService.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
Expand Down Expand Up @@ -80,7 +79,6 @@ public class DownloadService {
* the prefix for the signature validator name
*/
private static final String signatureValidatorPrefix = "downloadable";

/**
* Builds up an HTML fragment that starts all the download jobs.
*
Expand Down Expand Up @@ -110,7 +108,6 @@ public Downloadable getById(String id) {
* Confusingly, the JSONP files are given the {@code *.json} file extension, when they are really JavaScript and should be {@code *.js}.
* This method extracts the JSON from a JSONP URL, since that is what we actually want when we download from the server.
* (Currently the true JSON is not published separately, and extracting from the {@code *.json.html} is more work.)
*
* @param src a URL to a JSONP file (typically including {@code id} and {@code version} query parameters)
* @return the embedded JSON text
* @throws IOException if either downloading or processing failed
Expand All @@ -136,7 +133,6 @@ public static String loadJSON(URL src) throws IOException {

/**
* Loads JSON from a JSON-with-{@code postMessage} URL.
*
* @param src a URL to a JSON HTML file (typically including {@code id} and {@code version} query parameters)
* @return the embedded JSON text
* @throws IOException if either downloading or processing failed
Expand Down Expand Up @@ -219,13 +215,14 @@ public static class Downloadable implements ExtensionPoint {
/**
* Creates a new downloadable.
*
* @param id The ID to use.
* @param url URL relative to {@link UpdateCenter#getDefaultBaseUrl()}.
* So if this string is "foo.json", the ultimate URL will be
* something like "http://updates.jenkins-ci.org/updates/foo.json"
* <p>
* For security and privacy reasons, we don't allow the retrieval
* from random locations.
* @param id The ID to use.
* @param url
* URL relative to {@link UpdateCenter#getDefaultBaseUrl()}.
* So if this string is "foo.json", the ultimate URL will be
* something like "http://updates.jenkins-ci.org/updates/foo.json"
*
* For security and privacy reasons, we don't allow the retrieval
* from random locations.
* @param interval The interval, in milliseconds, between attempts to update this downloadable's data.
*/
public Downloadable(@NonNull String id, @NonNull String url, long interval) {
Expand Down Expand Up @@ -289,6 +286,7 @@ public String getId() {
*
* @param clazz The class to use to generate an ID.
* @return The ID generated based on the specified class.
*
* @since 2.244
*/
@NonNull
Expand Down Expand Up @@ -324,7 +322,8 @@ public List<String> getUrls() {
/**
* How often do we retrieve the new image?
*
* @return number of milliseconds between retrieval.
* @return
* number of milliseconds between retrieval.
*/
public long getInterval() {
return interval;
Expand Down Expand Up @@ -389,7 +388,7 @@ public FormValidation updateNow() throws IOException {
}
String jsonString;
try {
jsonString = loadJSONHTML(new URI(site + ".html?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8)).toURL());
jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8)));
toolInstallerMetadataExists = true;
} catch (Exception e) {
LOGGER.log(Level.FINE, "Could not load json from " + site, e);
Expand Down Expand Up @@ -417,7 +416,6 @@ public FormValidation updateNow() throws IOException {

/**
* Function that takes multiple JSONObjects and returns a single one.
*
* @param jsonList to be processed
* @return a single JSONObject
*/
Expand All @@ -427,10 +425,9 @@ public JSONObject reduce(List<JSONObject> jsonList) {

/**
* check if the list of update center entries has duplicates
*
* @param genericList list of entries coming from multiple update centers
* @param comparator the unique ID of an entry
* @param <T> the generic class
* @param comparator the unique ID of an entry
* @param <T> the generic class
* @return true if the list has duplicates, false otherwise
*/
public static <T> boolean hasDuplicates(List<T> genericList, String comparator) {
Expand Down Expand Up @@ -473,6 +470,7 @@ public static ExtensionList<Downloadable> all() {
* {@link #idFor(Class)}).
*
* @param clazz The class to use to determine the downloadable's ID.
*
* @since 2.244
*/
@CheckForNull
Expand Down
Loading
Loading