java.lang.Object
net.i2p.util.EepGet
net.i2p.util.EepPost
Extends EepGet for POST. Adapted from old jrandom EepPost, removed 2012 as unused. Ref: RFC 7578.
Nested Class Summary
Nested classes/interfaces inherited from class EepGet
EepGet.AUTH_MODE, EepGet.AuthState, EepGet.CLIStatusListener, EepGet.ContentRange, EepGet.Gunzipper, EepGet.StatusListenerModifier and TypeClassDescriptionprotected static enumAuthentication mode enumeration.protected classManage the authentication parameters Ref: RFC 2617 Supports both Basic and Digest, however i2ptunnel HTTP proxy has migrated all previous Basic support to Digest.protected classReports fetch progress to the command line, one mark per markSize bytes and a summary line every lineSize marks.(package private) static final classParsed Content-Range header value.protected classDecompressor thread.static interfaceCallback interface for monitoring EepGet transfer progress.Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final StringLine ending in an HTTP header.private static final byte[]The header line ending, as bytes.private static final intMost of a POST body kept in memory, in bytes.Fields inherited from class EepGet
_aborted, _acceptRanges, _actualURL, _alreadyTransferred, _authState, _bytesRemaining, _bytesTransferred, _cacheControl, _contentEncoding, _contentLanguage, _contentRange, _contentType, _context, _cookie, _csp, _currentAttempt, _decompressException, _encodingChunked, _etag, _etagOrig, _expiryDate, _extraHeaders, _fetchHeaderTimeout, _fetchInactivityTimeout, _fetchTotalTimeout, _isGzippedResponse, _keepFetching, _lastModified, _lastModifiedOrig, _listeners, _log, _maxCompleteFails, _notModified, _numRetries, _out, _outputFile, _outputStream, _proxy, _proxyHost, _proxyIn, _proxyOut, _proxyPort, _redirectLocation, _redirects, _referrerPolicy, _responseCode, _responseText, _retryDelayMs, _server, _shouldProxy, _shouldWriteErrorToOutput, _status, _transferEncoding, _transferFailed, _url, _vary, _xContentTypeOptions, _xframeOptions, _xPoweredBy, _xssProtection, DEFAULT_CONNECT_TIMEOUT, DEFAULT_INACTIVITY_TIMEOUT, DEFAULT_MAX_COMPLETE_FAILS, DEFAULT_NUM_RETRIES, DEFAULT_RETRY_DELAY, DEFAULT_RETRY_JITTER, GZIP_PARTIAL_MARKER_SUFFIX, PROP_CONNECT_TIMEOUT, PROP_DEFAULT_RETRIES, PROP_INACTIVITY_TIMEOUT, PROP_MAX_COMPLETE_FAILS, PROP_RETRY_DELAY, USER_AGENTModifier and TypeFieldDescriptionprotected booleanWhether the fetch was aborted due to timeout or user request.protected StringAccept-Ranges header value from the response.protected StringThe URL we actually fetch from (may differ from _url in case of redirect).protected longTotal bytes transferred across all attempts, including resumed content.protected EepGet.AuthStateAuthentication state for proxy digest/basic auth; created viaEepGet.addAuthorization(String, String).protected longRemaining bytes on the current attempt, -1 if unknown (chunked or no Content-Length).protected longBody bytes transferred in the currentEepGet.fetch(), summed across attempts.protected StringCache-Control header value from the response.protected StringContent-Encoding header value from the response.protected StringContent-Language header value from the response.protected StringContent-Range header value from the response, for validating 206/416 resumes.protected StringContent-Type header value from the response.protected final I2PAppContextI2P application context for configuration, logging, and random number generation.protected StringSet-Cookie header value from the response.protected StringContent-Security-Policy header value from the response.protected intZero-based attempt counter for the current fetch; read by the watchdog command.protected IOExceptionIOException from the background decompressor thread, if any.protected booleanWhether the response is using chunked transfer encoding.protected StringETag received from the server (for conditional requests).protected final StringOriginal ETag passed in constructor, preserved across redirects.protected StringExpires header value from the response.Additional HTTP headers to include in the request.protected intTimeout in ms for receiving the HTTP response headers.protected intInactivity timeout in ms between data packets.protected intTotal timeout in ms for the entire fetch operation.protected booleanWhether the response body is gzip-compressed.protected booleanWhether to continue fetching; set false to abort.protected StringLast-Modified header received from the server.protected final StringOriginal Last-Modified passed in constructor, preserved across redirects.protected final List<EepGet.StatusListener> Registered status listeners for progress callbacks.protected final LogLogger for this instance.protected intMaximum number of complete (zero-byte) failures before giving up.protected booleanWhether the server returned 304 Not Modified.protected final intMaximum number of retry attempts per fetch.protected OutputStreamOutput stream for writing fetched data (file or pipe).protected final StringPath to the output file for saving the fetched content.protected final OutputStreamOutput stream destination, overrides outputFile when non-null.protected SocketThe socket connection to the proxy or the target server (if not proxied).protected final StringProxy hostname or IP address.protected InputStreamInput stream from the proxy/server socket.protected OutputStreamOutput stream to the proxy/server socket.protected final intProxy port number.protected StringLocation header value from redirect or 407 proxy auth response.protected AtomicIntegerCounter tracking the number of HTTP redirects followed.protected StringReferrer-Policy header value from the response.protected intHTTP response status code, -1 if no response received.protected StringHTTP response status text (e.g.protected final longFixed retry delay in ms, -1 selects the jittered default @since 0.9.71+.protected StringServer header value from the response.protected final booleanWhether to route requests through an HTTP proxy.protected booleanWhether to write error response bodies to the output.protected StringStatus header value from the response.protected StringTransfer-Encoding header value from the response.protected booleanWhether the current transfer attempt failed (non-2xx response code).protected final StringThe URL we were asked to fetch.protected StringVary header value from the response.protected StringX-Content-Type-Options header value from the response.protected StringX-Frame-Options header value from the response.protected StringX-Powered-By header value from the response.protected StringX-XSS-Protection header value from the response.protected static final intDefault connect timeout in milliseconds (90 seconds).protected static final intDefault inactivity timeout in milliseconds (5 minutes).protected static final intMaximum times to try without getting any data at all, even if numRetries is higher @since 0.7.14.protected static final intDefault number of retry attempts.protected static final intBase retry delay in milliseconds when the jittered default is used @since 0.9.71+.protected static final intMaximum additional jitter in milliseconds added to the base retry delay @since 0.9.71+.(package private) static final StringSuffix of the sidecar marker file recording that the output file holds transparently-decompressed (gunzipped) bytes rather than raw response bytes, so its length must not be used as a Range resume offset.(package private) static final StringProperty name for connect timeout configuration.(package private) static final StringProperty name for default retries configuration.(package private) static final StringProperty name for inactivity timeout configuration.(package private) static final StringProperty name for max complete fails configuration.(package private) static final StringProperty name for the fixed retry delay in milliseconds.protected static final StringDefault User-Agent header value.Constructor Summary
ConstructorsConstructorDescriptionEepPost(I2PAppContext ctx, String proxyHost, int proxyPort, int numRetries, String outputFile, String url) Constructor for a POST session.Method Summary
Modifier and TypeMethodDescriptionbooleanfetch()Not supported, use post() instead.booleanfetch(long fetchHeaderTimeout) Not supported, use post() instead.booleanfetch(long fetchHeaderTimeout, long totalTimeout, long inactivityTimeout) Not supported, use post() instead.private StringAdapted from old jrandom EepPost.static voidCommand-line entry point for EepPost.booleanpost(String contentType, byte[] data, long headerTimeout, long totalTimeout, long inactivityTimeout) In-memory, not for large POSTs.booleanFor large POSTs.booleanpost(String contentType, String data, long headerTimeout, long totalTimeout, long inactivityTimeout) In-memory, not for large POSTs.booleanSubmit an HTTP POST to the given URL (using the proxy if specified), uploading the given fields.private static voidsendField(OutputStream out, String separator, String field, String val) Multipart Adapted from old jrandom EepPost.private static voidsendField(StringBuilder out, String field, String val) Adapted from old jrandom EepPost.private static voidsendFields(OutputStream out, String separator, Map<String, Object> fields) Multipart Adapted from old jrandom EepPost.private static voidsendFields(StringBuilder out, Map<String, Object> fields) Adapted from old jrandom EepPost.private static voidsendFile(OutputStream out, String separator, String field, File file) Multipart Adapted from old jrandom EepPost.(package private) static Stringusage()Usage text for the command-line entry point.Methods inherited from class EepGet
addAuthorization, addHeader, addStatusListener, doFetch, failureReason, fatalAbort, getAcceptRanges, getCacheControl, getContentEncoding, getContentLanguage, getContentType, getCookie, getCSP, getEtag, getExpiryDate, getLastModified, getNotModified, getReferrerPolicy, getRequest, getResumeOffset, getServer, getStatus, getStatusCode, getStatusText, getTransferEncoding, getVary, getXContentTypeOptions, getXframeOptions, getXPoweredBy, getXSSProtection, gzipMarkerExists, isStalledButProgressing, isTotalBudgetExhausted, markGzipPartial, parseAuthArgs, parseChunkLength, parseContentRange, readChunkLength, readHeaders, redactedUrl, requestedRangeStart, seconds, sendRequest, setPostData, setPostData, setPostData, setWriteErrorToOutput, shouldReadBody, stopFetching, suggestName, usageText, validateResumeResponseModifier and TypeMethodDescriptionvoidaddAuthorization(String userName, String password) Add basic authorization header for the proxy.voidAdd an extra header to the request.voidAdd a status listener.protected voiddoFetch(SocketTimeout timeout) Read response body for a single fetch.(package private) static StringfailureReason(Throwable t, long inactivityMs) The failure reason for a transfer-failed log line.(package private) static booleanfatalAbort(boolean aborted, boolean strictSize, long remaining, boolean sawEof) Decide whether a watchdog abort observed after the body loop must fail the attempt.Show the Accept-Ranges field.Show the Cache-Control field.Show the Content-Encoding field.Show the Content-Language field.After fetch, the received value from the server, or null if none.Show the Set-Cookie field.getCSP()Content-Security-Policy header.getEtag()After fetch, the received value from the server, or null if none.Show the Expires field.After fetch, the received value from the server, or null if none.booleanWhether the server returned 304.Referrer-Policy header.protected StringBuild the HTTP request string for the current URL and state.protected longgetResumeOffset(File outFile) Byte offset to resume from for a file-based fetch, accounting for the persisted gunzip state: a marker means the file holds decompressed bytes, whose length is not a valid offset into the compressed representation, so the fetch restarts instead of resuming.Show the Server field.Combined server status message e.g.intThe server response (200, etc).The server text ("OK", "Not Found", etc).Show the Transfer-Encoding field.getVary()Vary header.X-Content-Type-Options header.X-Frame-Options header.X-Powered-By header.X-XSS-Protection header.(package private) booleanWhether this fetch's output file was written by the transparent gunzipper, so its length is a decompressed size that must not be used as a Range resume offset.(package private) static booleanisStalledButProgressing(IOException ioe, boolean aborted, long attemptStartBytes, long bytesTransferred) Whether a failed attempt was a data-phase stall on an otherwise working path: the read timed out or our SocketTimeout watchdog aborted the transfer (which closes the socket first, surfacing as a raw SocketException, so the explicitabortedsignal.(package private) static booleanisTotalBudgetExhausted(long totalTimeoutMs, long attemptStartMs, long nowMs) Whether an attempt has already consumed its total-timeout budget.(package private) voidmarkGzipPartial(File outFile) Record that the output file now holds decompressed bytes.parseAuthArgs(String args) Parse the args in an authentication header.(package private) static longparseChunkLength(String line) Extract the chunk size from a chunk-size line, dropping any chunk extensions.(package private) static EepGet.ContentRangeparseContentRange(String val) Parse a Content-Range header value.protected longParse a chunk length from the HTTP response stream.protected voidRead and parse HTTP response headers.(package private) static StringredactedUrl(String url) The request URL for log output.(package private) static longrequestedRangeStart(long alreadyTransferred, List<String> extraHeaders) Determine the start offset this fetch requested, so a 206's Content-Range can be validated against what was actually asked for.(package private) static Stringseconds(long ms) Render a millisecond duration in seconds for log output, keeping milliseconds only for sub-second or non-whole-second values.protected voidsendRequest(SocketTimeout timeout) Open connection and send HTTP request.protected voidsetPostData(String contentType, byte[] data) Set post data (binary body).protected voidsetPostData(String contentType, File data) Set post data (file body).protected voidsetPostData(String contentType, String data) Set post data (string body).voidIf called (before calling fetch()), data from the server or proxy will be written to the output file or stream even on an error response code (4xx, 5xx, etc).protected booleanWhether to read the response body.voidStop the fetch in progress.static StringsuggestName(String url) Parse URL for a viable filename.(package private) static StringThe command-line help text, listing every option accepted byEepGet.main(String[]).(package private) booleanValidate a resume-sensitive response once all headers are parsed.
Field Details
CRLF
CRLFB
private static final byte[] CRLFBThe header line ending, as bytes.PROP_MAX_POST_PAYLOAD_RAM
private static final int PROP_MAX_POST_PAYLOAD_RAMMost of a POST body kept in memory, in bytes.- See Also:
Constructor Details
EepPost
public EepPost(I2PAppContext ctx, String proxyHost, int proxyPort, int numRetries, String outputFile, String url) Constructor for a POST session. The post body is supplied later by one of thepost(Map, long, long, long)methods; fetch() is not supported.- Parameters:
ctx- the app contextproxyHost- the proxy hostname, empty for no proxyproxyPort- the proxy port, 0 for no proxynumRetries- number of retriesoutputFile- file to save the response tourl- URL to post to
Method Details
post
public boolean post(Map<String, Object> fields, long headerTimeout, long totalTimeout, long inactivityTimeout) Submit an HTTP POST to the given URL (using the proxy if specified), uploading the given fields. If the field's value is a File object, then that file is uploaded, and if the field's value is a String object, the value is posted for that particular field. Multiple values for one field name is not currently supported.Large files will be copied to a temp file. For large String content, consider the post(File) method.
Note: param field values must be String or File.
- Parameters:
fields- the field names and values to submit, each value a String or a FileheaderTimeout- milliseconds to wait for the response headers of each attempt, <= 0 for nonetotalTimeout- milliseconds for the whole post including retries, <= 0 for noneinactivityTimeout- milliseconds to wait between body bytes, <= 0 for the default- Returns:
- true if the post succeeded
post
public boolean post(String contentType, String data, long headerTimeout, long totalTimeout, long inactivityTimeout) In-memory, not for large POSTs.- Parameters:
contentType- the value for the Content-Type headerdata- the post body, must not be emptyheaderTimeout- milliseconds to wait for the response headers of each attempt, <= 0 for nonetotalTimeout- milliseconds for the whole post including retries, <= 0 for noneinactivityTimeout- milliseconds to wait between body bytes, <= 0 for the default- Returns:
- true if the post succeeded
post
public boolean post(String contentType, byte[] data, long headerTimeout, long totalTimeout, long inactivityTimeout) In-memory, not for large POSTs.- Parameters:
contentType- the value for the Content-Type headerdata- the post body, must not be emptyheaderTimeout- milliseconds to wait for the response headers of each attempt, <= 0 for nonetotalTimeout- milliseconds for the whole post including retries, <= 0 for noneinactivityTimeout- milliseconds to wait between body bytes, <= 0 for the default- Returns:
- true if the post succeeded
post
public boolean post(String contentType, File data, long headerTimeout, long totalTimeout, long inactivityTimeout) For large POSTs.- Parameters:
contentType- the value for the Content-Type headerdata- the post body, must be a regular file and not emptyheaderTimeout- milliseconds to wait for the response headers of each attempt, <= 0 for nonetotalTimeout- milliseconds for the whole post including retries, <= 0 for noneinactivityTimeout- milliseconds to wait between body bytes, <= 0 for the default- Returns:
- true if the post succeeded
fetch
public boolean fetch()Not supported, use post() instead.- Overrides:
fetchin classEepGet- Returns:
- whether the URL was retrieved; false if every attempt failed
- Throws:
UnsupportedOperationException- always; this class posts only
fetch
public boolean fetch(long fetchHeaderTimeout) Not supported, use post() instead.- Overrides:
fetchin classEepGet- Parameters:
fetchHeaderTimeout- timeout in ms- Returns:
- whether the URL was retrieved; false if every attempt failed
- Throws:
UnsupportedOperationException- always; this class posts only
fetch
public boolean fetch(long fetchHeaderTimeout, long totalTimeout, long inactivityTimeout) Not supported, use post() instead.- Overrides:
fetchin classEepGet- Parameters:
fetchHeaderTimeout- <= 0 for none (proxy will timeout if none, none isn't recommended if no proxy) forced to totalTimeout if totalTimeout is set and this is <= 0totalTimeout- operation-wide deadline for the whole fetch, including retries and backoff between attempts; <= 0 for default noneinactivityTimeout- <= 0 for defaultEepGet.DEFAULT_INACTIVITY_TIMEOUT(5 minutes)- Returns:
- whether the URL was retrieved; false if every attempt failed
- Throws:
UnsupportedOperationException- always; this class posts only
sendFields
Adapted from old jrandom EepPost.- Parameters:
out- the StringBuilder the urlencoded body is appended tofields- field names mapped to values, stringified with toString()
sendFields
private static void sendFields(OutputStream out, String separator, Map<String, Object> fields) throws IOExceptionMultipart Adapted from old jrandom EepPost.- Parameters:
out- the stream the multipart body is written toseparator- non-nullfields- field names mapped to values, File values sent as file parts- Throws:
IOException- if writing fails or a File value cannot be read
sendField
Adapted from old jrandom EepPost.- Parameters:
out- the StringBuilder the name=value pair is appended tofield- the field name, spaces replaced with '+'val- the field value, spaces replaced with '+' as well
sendField
private static void sendField(OutputStream out, String separator, String field, String val) throws IOException Multipart Adapted from old jrandom EepPost.- Parameters:
out- the stream the part is written toseparator- non-nullfield- the field name, written into the content dispositionval- the field value, written as the part body- Throws:
IOException- if writing to the stream fails
sendFile
private static void sendFile(OutputStream out, String separator, String field, File file) throws IOException Multipart Adapted from old jrandom EepPost.- Parameters:
out- the stream the part is written toseparator- non-nullfield- the field name, written into the content dispositionfile- the file to upload, sent as application/octet-stream- Throws:
IOException- if the file cannot be read or writing fails
getSeparator
Adapted from old jrandom EepPost.- Returns:
- a fresh random multipart boundary, base32 encoded
main
Command-line entry point for EepPost. Seeusage()for the full option list.Usage: eeppost [-p 127.0.0.1:4444 | -c] [-n #retries] [-o outputFile] [-s key=value] | [-f key=file] url
At least one -s (string field) or -f (file field) is required. All timeouts are in seconds: -t is the inactivity timeout, -v the header timeout, and -w the total timeout, which is unlimited by default.
- Parameters:
args- the options and URL as described byusage()
usage
Usage text for the command-line entry point. Every option accepted bymain(String[])must appear here, with the defaults main() actually uses.- Returns:
- the help text