Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -1456,6 +1456,8 @@ view_results_table_request_http_protocol=Protocol
view_results_table_request_params_key=Parameter name
view_results_table_request_params_value=Value
view_results_table_request_raw_nodata=No data to display

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This reads as a fragment glued to a finite clause — "Request body not shown (…) and cannot be reproduced". Since it renders as a shell comment the user reads next to the command, reason-then-consequence is easier to scan:

view_results_table_request_tab_curl_body_omitted=Request body cannot be reproduced: JMeter does not keep the bytes of a file sent as the body or of a non-repeatable entity

view_results_table_request_tab_curl=cURL
view_results_table_request_tab_curl_body_omitted=Request body cannot be reproduced: JMeter does not keep the bytes of a file sent as the body or of a non-repeatable entity
view_results_table_request_tab_http=HTTP
view_results_table_request_tab_raw=Raw
view_results_table_result_tab_parsed=Parsed
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.jmeter.protocol.http.curl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import org.apache.jmeter.protocol.http.config.MultipartUrlConfig;
import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult;
import org.apache.jmeter.protocol.http.sampler.PostWriter;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
import org.apache.jmeter.protocol.http.util.HTTPFileArg;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.util.StringUtilities;

/**
* Renders an {@link HTTPSampleResult} as a ready-to-run {@code curl} command,
* the reverse of what {@link BasicCurlParser} does.
*
* <p>The generated command targets a POSIX-compatible shell: arguments are
* single-quoted and lines are continued with a trailing backslash. It is not
* valid {@code cmd.exe} or PowerShell syntax.</p>
*
* <p>The class has no Swing dependency so it can be reused outside the
* View Results Tree (for example by a future "Copy as cURL" sampler action).</p>
*/
public final class CurlCommandFormatter {

/** Backslash line continuation followed by indentation, for a POSIX shell. */
private static final String NEWLINE = " \\\n "; //$NON-NLS-1$

private static final String ACCEPT_ENCODING = "Accept-Encoding"; //$NON-NLS-1$

private static final String BOUNDARY = "boundary="; //$NON-NLS-1$

/** {@code HTTPArgument} defaults a part's content type to this; see HTTPArgumentSchema. */
private static final String DEFAULT_FIELD_CONTENT_TYPE = "text/plain"; //$NON-NLS-1$

/**
* Headers that must not be reproduced in the curl command: curl generates
* them itself, they are connection-specific (hop-by-hop) headers that are
* forbidden in HTTP/2 and would make the request fail with a protocol
* error, or they are pseudo-headers JMeter adds only for reporting and that
* never went on the wire (X-LocalAddress).
*/
private static final Set<String> SKIPPED_HEADERS = Set.of(
"content-length", //$NON-NLS-1$
"connection", //$NON-NLS-1$
"keep-alive", //$NON-NLS-1$
"proxy-connection", //$NON-NLS-1$
"transfer-encoding", //$NON-NLS-1$
"upgrade", //$NON-NLS-1$
HTTPConstants.HEADER_LOCAL_ADDRESS.toLowerCase(Locale.ROOT));

/**
* Markers JMeter writes into the rendered request body in place of content
* it did not keep (a file sent as the body, or a non-repeatable entity).
* When present, the body is not the real wire body and cannot be reproduced.
*
* @see org.apache.jmeter.protocol.http.sampler.PostWriter
*/
private static final String[] BODY_PLACEHOLDERS = {
Comment thread
poliakov-alex marked this conversation as resolved.
PostWriter.FILE_CONTENT_PLACEHOLDER,
PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
};

private CurlCommandFormatter() {
}

/**
* Build a {@code curl} command line that reproduces the given HTTP request.
*
* @param sampleResult the sampled HTTP request
* @return the curl command as a string
*/
public static String format(HTTPSampleResult sampleResult) {
StringBuilder sb = new StringBuilder(256);
sb.append("curl"); //$NON-NLS-1$

String method = sampleResult.getHTTPMethod();
boolean isHead = HTTPConstants.HEAD.equalsIgnoreCase(method);
boolean isGet = StringUtilities.isBlank(method) || HTTPConstants.GET.equalsIgnoreCase(method);

// Split by line (not via JMeterUtils.parseHeaders) so repeated header
// names such as several Accept values are all preserved.
List<String[]> headers = new ArrayList<>();
String contentType = null;
boolean acceptsEncoding = false;
String requestHeaders = sampleResult.getRequestHeaders();
if (StringUtilities.isNotEmpty(requestHeaders)) {
for (String header : requestHeaders.split("\n")) { //$NON-NLS-1$
int colon = header.indexOf(':');
if (colon <= 0) {
continue;
}
String name = header.substring(0, colon).trim();
String value = header.substring(colon + 1).trim();
String lower = name.toLowerCase(Locale.ROOT);
if (SKIPPED_HEADERS.contains(lower)) {
continue;
}
if (HTTPConstants.HEADER_CONTENT_TYPE.equalsIgnoreCase(name)) {
contentType = value;
}
if (ACCEPT_ENCODING.equalsIgnoreCase(name)) {
acceptsEncoding = true;
}
headers.add(new String[] { name, value });
}
}

String body = isHead ? "" : sampleResult.getQueryString(); //$NON-NLS-1$
boolean hasBody = StringUtilities.isNotEmpty(body);
boolean isMultipart = contentType != null
&& contentType.toLowerCase(Locale.ROOT).startsWith(HTTPConstants.MULTIPART_FORM_DATA);
// Multipart bodies are rebuilt as -F flags; curl then sets its own
// Content-Type (with its own boundary), so the original one is dropped.
List<String[]> formParts = hasBody && isMultipart ? parseMultipartForm(contentType, body) : List.of();
boolean emitsForm = !formParts.isEmpty();
boolean emitsDataRaw = hasBody && !isMultipart && !containsPlaceholder(body);

// Method: --head for HEAD (plain "-X HEAD" makes curl wait for a body it
// never gets); no -X for a plain GET; -X GET only when a GET carries a
// raw body, otherwise curl would switch it to POST; -X for everything else.
if (isHead) {
sb.append(" --head"); //$NON-NLS-1$
} else if (!isGet) {
sb.append(" -X ").append(quote(method)); //$NON-NLS-1$
} else if (emitsDataRaw) {
sb.append(" -X ").append(quote(HTTPConstants.GET)); //$NON-NLS-1$
}

URL url = sampleResult.getURL();
if (url != null) {
sb.append(NEWLINE).append(quote(url.toString()));
}

boolean hasCookieHeader = false;
for (String[] header : headers) {
if (emitsForm && HTTPConstants.HEADER_CONTENT_TYPE.equalsIgnoreCase(header[0])) {
continue;
}
if (HTTPConstants.HEADER_COOKIE.equalsIgnoreCase(header[0])) {
hasCookieHeader = true;
}
sb.append(NEWLINE).append("-H ").append(quote(header[0] + ": " + header[1])); //$NON-NLS-1$ //$NON-NLS-2$
}

// HttpClient disables automatic decompression, so Accept-Encoding is only present
// when explicitly set. --compressed makes curl decode the response; it is kept
// alongside the explicit header rather than replacing it, because curl otherwise
// negotiates its own build-dependent encoding list the test plan never asked for.
if (acceptsEncoding) {
sb.append(NEWLINE).append("--compressed"); //$NON-NLS-1$
}

// Cookies normally arrive through getCookies(), but AjpSampler can also leave a
// Cookie header in the list; curl lets the header win and silently drops -b, so
// only add -b when no Cookie header was emitted.
String cookies = sampleResult.getCookies();
if (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) {
sb.append(NEWLINE).append("-b ").append(quote(cookies)); //$NON-NLS-1$
}
Comment on lines +180 to +183

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A correction to my earlier note, and a narrow case it leaves open.

I said the hasCookieHeader guard was unreachable, and that was too broad. It holds for HTTPHC4Impl and HTTPJavaImpl, which strip Cookie in getAllHeadersExceptCookie, but AjpSampler.setConnectionHeaders copies Header Manager entries into the header string verbatim while setConnectionCookies fills getCookies() separately. With both a Header Manager Cookie and a Cookie Manager, the result is:

curl \
  'http://example.com/' \
  -H 'Cookie: a=1' \
  -b 'b=2'

curl lets the explicit header win, so b=2 is dropped without a word. Skipping -b when a Cookie header was already emitted restores what the guard used to cover. Low stakes given it is AJP-only — mentioning it because I am the reason the guard went away.


if (emitsForm) {
for (String[] part : formParts) {
sb.append(NEWLINE).append(part[0]).append(' ').append(quote(part[1]));
}
} else if (emitsDataRaw) {
sb.append(NEWLINE).append("--data-raw ").append(quote(body)); //$NON-NLS-1$
} else if (hasBody) {
// A file sent as the body or a non-repeatable entity: the bytes were
// not kept, so emitting them would produce a silently-wrong command.
sb.append('\n').append("# ") //$NON-NLS-1$
.append(JMeterUtils.getResString("view_results_table_request_tab_curl_body_omitted")); //$NON-NLS-1$
}

return sb.toString();
}

/**
* Rebuild the {@code -F} form parts of a multipart request from its rendered
* body. Regular fields become {@code name=value}; file parts become
* {@code name=@filename;type=...}. JMeter does not keep the uploaded bytes,
* so the file name is only a placeholder the user edits to a real path
* before running the command.
*
* @return the form parts, or an empty list if the body cannot be parsed
*/
private static List<String[]> parseMultipartForm(String contentType, String body) {
String boundary = extractBoundary(contentType);
// A quoted boundary is unquoted above; but if the header boundary and the body
// disagree, MultipartUrlConfig would treat the whole body as one field and emit
// garbage, so require the delimiter to be present and fall back to the note otherwise.
if (StringUtilities.isBlank(boundary) || !body.contains("--" + boundary)) { //$NON-NLS-1$
return List.of();
}
MultipartUrlConfig multipart = new MultipartUrlConfig(boundary);
try {
multipart.parseArguments(body);
} catch (RuntimeException e) { // NOSONAR malformed body: fall back to the omitted-body note
return List.of();
}
Comment on lines +210 to +223

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A quoted or mismatched boundary yields a corrupted --form-string, not the omitted-body note.

extractBoundary (line 235) returns the boundary with its quotes still attached, so Content-Type: multipart/form-data; boundary="xyz" gives "xyz". MultipartUrlConfig.parseArguments then splits on --"xyz", finds no delimiter, and treats the whole body as one part. That part does contain Content-Disposition: form-data, so a field is created, and its value runs to part.lastIndexOf(CRLF) (MultipartUrlConfig#170) — i.e. it swallows the trailing boundary marker.

Rendered on this branch:

Content-Type: multipart/form-data; boundary="xyz"
body: --xyz\r\nContent-Disposition: form-data; name="a"\r\n\r\nb\r\n--xyz--\r\n

curl -X 'POST' \
  'http://example.com/upload' \
  --form-string 'a=b
--xyz--'

The same thing happens whenever the header boundary and the body disagree: boundary=nomatch over a body delimited by --other renders --form-string 'a=b\n--other--'. Both commands run and send garbage — the class of bug this PR set out to remove.

Quoting is legal per RFC 2046, and both cases are reachable: when getUseMultipart() is false, HTTPHC4Impl#1523 keeps the user's own Content-Type header, so a hand-built multipart body in the Body Data tab arrives here verbatim.

Two small guards fix it: strip surrounding quotes in extractBoundary, and check that the body actually contains --<boundary> before parsing, falling through to the omitted-body branch when it does not.

While you are in extractBoundary — it now duplicates RequestViewHTTP#251, and the new one is the better of the two (it returns null when boundary= is absent, where the old one builds a nonsense substring). Now that the logic is Swing-free, RequestViewHTTP could call it instead.

List<String[]> parts = new ArrayList<>();
for (JMeterProperty property : multipart.getArguments()) {
parts.add(formField((HTTPArgument) property.getObjectValue()));
}
Comment on lines +225 to +227

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The per-part Content-Type is dropped.

MultipartUrlConfig already parses it into the argument (MultipartUrlConfig#119,174), and it is user-settable: the Parameters table has a content-type column (HTTPArgumentsPanel#55,66), and HTTPHC4Impl builds each part as StringBody(value, contentType) from it. --form-string emits no part header at all — verified against a server:

Content-Disposition: form-data; name="meta"
                                              ← no Content-Type
{"a":1}

A field explicitly marked application/json therefore arrives with curl's default. --form-string cannot carry ;type= by design, so the choices are to use -F 'name=value;type=…' when the part has a non-default type and the value does not start with @ or <, or to state the limitation in component_reference.xml. Either is fine; silently losing it is the part worth changing.

Two smaller things in the same loop: the original interleaving of fields and files is lost (all --form-string first, then all -F), and a part with no blank-line separator renders as --form-string 'a=' with the value silently gone.

for (HTTPFileArg file : multipart.getHTTPFileArgs().asArray()) {
parts.add(fileField(file));
}
Comment on lines +228 to +230

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A file name containing ; or , produces a -F spec curl rejects.

The spec is concatenated unquoted, so a part named a;b,c.txt renders as -F 'up=@a;b,c.txt;type=text/plain'. curl parses ; and , inside the argument itself, so shell quoting does not protect it — the same shape as the @-prefixed value that --form-string solved, but on the file side:

$ curl -F 'up=@a;b,c.txt;type=text/plain' http://…
curl: (26) Failed to open/read local data from file/application

$ curl -F 'up=@"a;b,c.txt";type=text/plain' http://…
# exit 0, part sent as filename="a;b,c.txt"

Commas in file names are common enough to hit this in practice. Wrapping the path in double quotes inside the spec — name=@"path", with ;type= after the closing quote — fixes both characters.

return parts;
}

/**
* A multipart text field. {@code --form-string} keeps the value verbatim (curl would
* otherwise read a leading {@code @} or {@code <} as a file reference), but it cannot
* carry a per-part content type; {@code -F} can, so it is used when the value is safe
* for it (no {@code @}/{@code <} prefix and no {@code ;} that curl would read as an
* option separator).
*/
private static String[] formField(HTTPArgument argument) {
String value = argument.getValue() == null ? "" : argument.getValue(); //$NON-NLS-1$
String type = argument.getContentType();
// HTTPArgument defaults content_type to text/plain, which is indistinguishable from
// a part that carried none; only a non-default type is worth reproducing.
boolean hasType = StringUtilities.isNotEmpty(type) && !DEFAULT_FIELD_CONTENT_TYPE.equalsIgnoreCase(type);
boolean safeForF = hasType
&& !value.startsWith("@") && !value.startsWith("<") && value.indexOf(';') < 0; //$NON-NLS-1$ //$NON-NLS-2$
if (safeForF) {
return new String[] { "-F", argument.getName() + "=" + value + ";type=" + type }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
return new String[] { "--form-string", argument.getName() + "=" + value }; //$NON-NLS-1$ //$NON-NLS-2$
}

/**
* A multipart file part. The file name is double-quoted inside the spec so that a name
* containing {@code ;} or {@code ,} is not parsed by curl as an option separator; the
* bytes are not kept by JMeter, so the name is a placeholder to edit to a real path.
*/
private static String[] fileField(HTTPFileArg file) {
StringBuilder spec = new StringBuilder();
spec.append(file.getParamName()).append("=@\"").append(file.getPath()).append('"'); //$NON-NLS-1$
if (StringUtilities.isNotEmpty(file.getMimeType())) {
spec.append(";type=").append(file.getMimeType()); //$NON-NLS-1$
}
return new String[] { "-F", spec.toString() }; //$NON-NLS-1$
}

/**
* Extract the {@code boundary} value of a multipart content type, unquoted.
*
* @param contentType a {@code Content-Type} header value
* @return the boundary, or {@code null} if it is absent
*/
public static String extractBoundary(String contentType) {
int index = contentType.toLowerCase(Locale.ROOT).indexOf(BOUNDARY);
if (index < 0) {
return null;
}
String boundary = contentType.substring(index + BOUNDARY.length());
int semicolon = boundary.indexOf(';');
if (semicolon >= 0) {
boundary = boundary.substring(0, semicolon);
}
boundary = boundary.trim();
// RFC 2046 allows the boundary to be quoted; MultipartUrlConfig expects it unquoted.
if (boundary.length() >= 2 && boundary.charAt(0) == '"'
&& boundary.charAt(boundary.length() - 1) == '"') {
boundary = boundary.substring(1, boundary.length() - 1);
}
return boundary;
}

private static boolean containsPlaceholder(String body) {
for (String placeholder : BODY_PLACEHOLDERS) {
if (body.contains(placeholder)) {
return true;
}
}
return false;
}

/**
* Wrap a value in single quotes for safe use in a POSIX shell, escaping any
* embedded single quotes using the {@code '\''} idiom.
*
* @param value the value to quote
* @return the shell-quoted value
*/
private static String quote(String value) {
return "'" + value.replace("'", "'\\''") + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -1494,7 +1494,7 @@ private static String getFromHeadersMatchingPredicate(HttpRequest method, Predic
// Helper class so we can generate request data without dumping entire file contents
private static class ViewableFileBody extends FileBody {
private static final byte[] CONTENTS_OMITTED =
"<actual file content, not shown here>".getBytes(StandardCharsets.UTF_8);
PostWriter.FILE_CONTENT_PLACEHOLDER.getBytes(StandardCharsets.UTF_8);
private boolean hideFileData;

private ViewableFileBody(File file, ContentType contentType, Charset charset) {
Expand Down Expand Up @@ -1619,7 +1619,7 @@ else if(ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.setEntity(fileRequestEntity);

// We just add placeholder text for file content
postedBody.append("<actual file content, not shown here>");
postedBody.append(PostWriter.FILE_CONTENT_PLACEHOLDER);
} else {
// In a post request which is not multipart, we only support
// parameters, no file upload is allowed
Expand Down Expand Up @@ -1693,7 +1693,7 @@ private static void writeEntityToSB(final StringBuilder postedBody, final HttpEn
: contentEncoding));
bos.close();
} else {
postedBody.append("<Entity was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
postedBody.append(PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,19 @@ public class PostWriter {

public static final String ENCODING = StandardCharsets.UTF_8.name();

/**
* Placeholder written into the rendered request body in place of the actual
* file content, which JMeter does not keep (shown in the View Results Tree).
*/
public static final String FILE_CONTENT_PLACEHOLDER = "<actual file content, not shown here>"; // $NON-NLS-1$

/**
* Placeholder written into the rendered request body when the entity is not
* repeatable and the bytes that were sent cannot be shown.
*/
public static final String NON_REPEATABLE_ENTITY_PLACEHOLDER =
"<Entity was not repeatable, cannot view what was sent>"; // $NON-NLS-1$

/** The form data that is going to be sent as url encoded */
protected byte[] formDataUrlEncoded;
/** The form data that is going to be sent in post body */
Expand Down Expand Up @@ -134,7 +147,7 @@ public String sendPostData(URLConnection connection, HTTPSamplerBase sampler) th
// Write the actual file content
writeFileToStream(file.getPath(), out);
// We just add placeholder text for file content
postedBody.append("<actual file content, not shown here>"); // $NON-NLS-1$
postedBody.append(FILE_CONTENT_PLACEHOLDER);
out.write(CRLF);
postedBody.append(CRLF_STRING);
}
Expand All @@ -158,7 +171,7 @@ public String sendPostData(URLConnection connection, HTTPSamplerBase sampler) th
out.close();

// We just add placeholder text for file content
postedBody.append("<actual file content, not shown here>"); // $NON-NLS-1$
postedBody.append(FILE_CONTENT_PLACEHOLDER);
}
else if (formDataUrlEncoded != null){ // may be null for PUT
// In an application/x-www-form-urlencoded request, we only support
Expand Down
Loading