![]() |
TSDuck v3.45-4787
MPEG Transport Stream Toolkit
|
Perform a simple Web request (HTTP, HTTPS, FTP). More...
#include <tsWebRequest.h>


Public Member Functions | |
| WebRequest (Report *report, bool non_blocking=false) | |
| Constructor. | |
| WebRequest (ReporterBase *delegate, bool non_blocking=false) | |
| Constructor. | |
| virtual | ~WebRequest () override |
| Destructor. | |
| void | abort () |
| Abort a transfer in progress. | |
| size_t | announcedContentSize () const |
| Get the announced content size in bytes. | |
| void | clearPostData () |
| Clear previous POST data. | |
| void | clearRequestHeaders () |
| Clear all headers which will be sent with the request. | |
| bool | close () |
| Close the transfer. | |
| size_t | contentSize () const |
| Get the size in bytes of the downloaded content. | |
| bool | deleteCookiesFile () const |
| Delete the cookies file, if one was defined. | |
| void | deleteRequestHeader (const UString &name) |
| Delete all headers with a given name. | |
| void | disableCookies () |
| Disable the use of cookies for all requests. | |
| bool | downloadBinaryContent (const UString &url, ByteBlock &data, size_t chunk_size=DEFAULT_CHUNK_SIZE) |
| Download the content of the URL as binary data in one operation. | |
| bool | downloadFile (const UString &url, const fs::path &file_name, size_t chunk_size=DEFAULT_CHUNK_SIZE) |
| Download the content of the URL in a file in one operation. | |
| bool | downloadTextContent (const UString &url, UString &text, size_t chunk_size=DEFAULT_CHUNK_SIZE) |
| Download the content of the URL as text in one operation. | |
| void | enableCompression (bool on=true) |
| Enable compression. | |
| void | enableCookies (const fs::path &file_name=fs::path()) |
| Enable the use of cookies for all requests using this instance. | |
| UString | finalURL () const |
| Get the final URL of the actual download operation. | |
| fs::path | getCookiesFileName () const |
| Get the file name to use for cookies for all requests using this instance. | |
| SysHandleType | getHandle () const |
| Get the underlying file descriptor or device handle. | |
| virtual SysHandleType | getReadHandle () const |
| Get the underlying file descriptor or device handle for read operations. | |
| SysSocketType | getReadSocket () const |
| Get the underlying file descriptor or device handle as a system socket handle for read operations. | |
| void | getResponseHeaders (UStringToUStringMultiMap &headers) const |
| Get all response headers. | |
| SysSocketType | getSocket () const |
| Get the underlying file descriptor or device handle as a system socket handle. | |
| virtual SysHandleType | getWriteHandle () const |
| Get the underlying file descriptor or device handle for write operations. | |
| SysSocketType | getWriteSocket () const |
| Get the underlying file descriptor or device handle as a system socket handle for write operations. | |
| bool | httpClientError () const |
| Check if the HTTP status code indicates a client error. | |
| bool | httpServerError () const |
| Check if the HTTP status code indicates a server error. | |
| int | httpStatus () const |
| Get the HTTP status code (200, 404, etc). | |
| bool | httpSuccess () const |
| Check if the HTTP status code indicates success. | |
| bool | isNonBlocking () const |
| Check if the device is in non-blocking mode. | |
| bool | isOpen () const |
| Check if a transfer is open. | |
| bool | isSupportedByReactor (bool recheck=false) |
| Check if the device is supported by a reactor for non-blocking or asynchronous I/O. | |
| UString | mimeType (bool simple=true, bool lowercase=true) const |
| Get the MIME type in the response headers. | |
| bool | muteReport (bool mute) |
| Temporarily mute the associated report. | |
| bool | open (const UString &url, IOSB *iosb=nullptr) |
| Open an URL and start the transfer. | |
| UString | originalURL () const |
| Get the original URL, as set by setURL(). | |
| const UString & | proxyHost () const |
| Get the current actual proxy host. | |
| const UString & | proxyPassword () const |
| Get the current actual proxy user password. | |
| uint16_t | proxyPort () const |
| Get the current actual proxy port number. | |
| const UString & | proxyUser () const |
| Get the current actual proxy user name. | |
| bool | receive (void *buffer, size_t max_size, size_t &ret_size, IOSB *iosb=nullptr) |
| Receive data. | |
| UString | reponseHeader (const UString &name) const |
| Get the value of one header. | |
| virtual Report & | report () const override |
| Access the Report which is associated with this object. | |
| const UStringToUStringMultiMap & | responseHeaders () const |
| Get all response headers. | |
| void | setArgs (const WebRequestArgs &args) |
| Set various arguments from command line. | |
| void | setAutoRedirect (bool on) |
| Enable or disable the automatic redirection of HTTP requests. | |
| void | setConnectionTimeout (cn::milliseconds timeout) |
| Set the connection timeout for this request. | |
| void | setInsecure (bool on=true) |
| Enable or disable HTTPS security (certificate validation). | |
| bool | setNonBlocking (bool non_blocking) |
| Set the device in non-blocking mode. | |
| void | setPostData (const ByteBlock &data) |
| Set data to POST. | |
| void | setPostData (const UString &data, const UString content_type=u"text/plain; charset=utf-8") |
| Set data to POST. | |
| void | setProxyHost (const UString &host, uint16_t port) |
| Set the optional proxy host and port for this request. | |
| void | setProxyUser (const UString &user, const UString &password) |
| Set the optional proxy authentication for this request. | |
| void | setReceiveTimeout (cn::milliseconds timeout) |
| Set the timeout for each receive operation. | |
| Report * | setReport (Report *report) |
| Associate this object with another Report to log errors. | |
| ReporterBase * | setReport (ReporterBase *delegate) |
| Associate this object with another ReporterBase to log errors. | |
| void | setRequestHeader (const UString &name, const UString &value) |
| Set a header which will be sent with the request. | |
| void | setUserAgent (const UString &name=UString()) |
| Set the user agent name to use in HTTP headers. | |
| const UString & | userAgent () const |
| Get the current user agent name to use in HTTP headers. | |
Static Public Member Functions | |
| static UString | GetLibraryVersion () |
| Get the version of the underlying HTTP library. | |
| static bool | IsPendingStatus (int error_code) |
| This static method checks if a system error code means "I/O in progress" (asynchronous I/O) or "I/O would block" (non-blocking I/O). | |
| static void | SetDefaultProxyHost (const UString &host, uint16_t port) |
| Set the default proxy host and port for all subsequent requests. | |
| static void | SetDefaultProxyUser (const UString &user, const UString &password) |
| Set the default proxy authentication for all subsequent requests. | |
| static int | SilentLevel (bool silent, int default_severity=Severity::Error) |
| Compute a log severity level from a "silent" parameter. | |
Static Public Attributes | |
| static constexpr size_t | DEFAULT_CHUNK_SIZE = 64 * 1024 |
| Default download chunk size for bulk transfers. | |
| static constexpr uint16_t | DEFAULT_HTTP_PORT = 80 |
| Default TCP port for HTTP. | |
| static constexpr uint16_t | DEFAULT_HTTPS_PORT = 443 |
| Default TCP port for HTTPS. | |
| static constexpr const UChar * | DEFAULT_USER_AGENT = u"tsduck" |
| Default user agent string ("tsduck"). | |
Protected Member Functions | |
| virtual bool | allowSetNonBlocking () const |
| Check that the non-blocking mode can be set. | |
| bool | checkNonBlocking (bool non_blocking, const UChar *opname) |
| Check the blocking mode of a device. | |
| bool | checkNonBlocking (IOSB *iosb, const UChar *opname) |
| Check the blocking mode of a device. | |
| int | genericSystemRead (void *addr, size_t max_size, size_t &ret_size, const AbortInterface *abort, Device::IOSB *iosb, uint64_t position) |
| Generic system read operation. | |
| int | genericSystemWrite (const void *addr, size_t size, size_t &written_size, Device::IOSB *iosb, uint64_t position) |
| Generic system write operation. | |
| bool | setSystemNonBlocking (bool non_blocking) |
| Low-level method to set the system file or socket descriptor in non-blocking mode. | |
Perform a simple Web request (HTTP, HTTPS, FTP).
On UNIX systems, the implementation uses libcurl. On Windows systems, the implementation uses Microsoft Wininet. We could have used libcurl on Windows but building it was a pain...
The proxy and transfer settings must be set before starting any download operation. The HTTP status and the response headers are available after a successful download start.
By default, no proxy is used. If no proxy is set, the default proxy is used (system configuration on Windows, http_proxy environment on Unix systems).
|
explicit |
Constructor.
| [in] | report | Where to report errors. The report object must remain valid as long as this object exists or setReport() is used with another Report object. If report is null, log messages are discarded. |
| [in] | non_blocking | It true, the Web request is initially set in non-blocking mode. |
|
explicit |
Constructor.
| [in] | delegate | Use the report of another ReporterBase. If delegate is null, log messages are discarded. |
| [in] | non_blocking | It true, the Web request is initially set in non-blocking mode. |
|
inline |
Set the connection timeout for this request.
| [in] | timeout | Connection timeout in milliseconds. |
|
inline |
Set the timeout for each receive operation.
| [in] | timeout | Reception timeout in milliseconds. |
| void ts::WebRequest::setProxyHost | ( | const UString & | host, |
| uint16_t | port | ||
| ) |
Set the optional proxy host and port for this request.
| [in] | host | Proxy host name or address. |
| [in] | port | Proxy port number. |
Set the optional proxy authentication for this request.
| [in] | user | Proxy user name. |
| [in] | password | Proxy user's password. |
|
static |
Set the default proxy host and port for all subsequent requests.
| [in] | host | Proxy host name or address. |
| [in] | port | Proxy port number. |
|
static |
Set the default proxy authentication for all subsequent requests.
| [in] | user | Proxy user name. |
| [in] | password | Proxy user's password. |
| const UString & ts::WebRequest::proxyHost | ( | ) | const |
Get the current actual proxy host.
| uint16_t ts::WebRequest::proxyPort | ( | ) | const |
Get the current actual proxy port number.
| const UString & ts::WebRequest::proxyUser | ( | ) | const |
Get the current actual proxy user name.
| const UString & ts::WebRequest::proxyPassword | ( | ) | const |
Get the current actual proxy user password.
| void ts::WebRequest::enableCookies | ( | const fs::path & | file_name = fs::path() | ) |
Enable the use of cookies for all requests using this instance.
| [in] | file_name | The name of the file to use to load and store cookies. On Windows, there is an implicit per-user cookie repository and fileName is ignored. On Unix systems, this file is used to store and retrieve cookies in the libcurl format. When fileName is empty, use a temporary file name. |
| void ts::WebRequest::disableCookies | ( | ) |
Disable the use of cookies for all requests.
Cookies are initially disabled by default.
| fs::path ts::WebRequest::getCookiesFileName | ( | ) | const |
Get the file name to use for cookies for all requests using this instance.
| bool ts::WebRequest::deleteCookiesFile | ( | ) | const |
Delete the cookies file, if one was defined.
Set the user agent name to use in HTTP headers.
| [in] | name | The user agent name. If empty, DEFAULT_USER_AGENT is used. |
|
inline |
Get the current user agent name to use in HTTP headers.
|
inline |
Enable compression.
Compression is disabled by default.
| [in] | on | Boolean setting compression on or off. |
|
inline |
Enable or disable HTTPS security (certificate validation).
Certificate validation is enabled by default.
| [in] | on | If true, disable certificate validation. |
|
inline |
Enable or disable the automatic redirection of HTTP requests.
This option is active by default.
| [in] | on | If true, allow automatic redirection of HTTP requests. |
| void ts::WebRequest::setArgs | ( | const WebRequestArgs & | args | ) |
Set various arguments from command line.
| [in] | args | Command line arguments. |
Set a header which will be sent with the request.
If the same header already exists with another value, a new header is added.
| [in] | name | The header name. |
| [in] | value | The header value. |
| void ts::WebRequest::deleteRequestHeader | ( | const UString & | name | ) |
Delete all headers with a given name.
| [in] | name | The header name. |
| void ts::WebRequest::setPostData | ( | const UString & | data, |
| const UString | content_type = u"text/plain; charset=utf-8" |
||
| ) |
Set data to POST.
The request will be a POST one.
| [in] | data | Text POST data. The text will be sent in UTF-8 format. |
| [in] | content_type | The content type to set in the request headers. The default "Content-Type" header is "text/plain; charset=utf-8", which is usually appropriate. When set to the empty string, no header is set. |
| void ts::WebRequest::setPostData | ( | const ByteBlock & | data | ) |
Set data to POST.
The request will be a POST one.
| [in] | data | Binary POST data. |
| void ts::WebRequest::clearPostData | ( | ) |
Clear previous POST data.
The request will be a GET one.
Open an URL and start the transfer.
For HTTP request, perform all redirections and get response headers.
| [in] | url | The complete URL to fetch. |
| [in,out] | iosb | Address of an IOSB structure. If non-null, the request must be in non-blocking mode. When null, the request must be in blocking mode (the default). See the description of IOSB. Important: The parameter iosb should not be used by applications. It should be used only by "reactive classes", which work in combination with a Reactor. |
|
inline |
Check if a transfer is open.
|
inline |
Get the HTTP status code (200, 404, etc).
|
inline |
Check if the HTTP status code indicates success.
The HTTP status codes are classified as follow (Wikipedia):
|
inline |
Check if the HTTP status code indicates a client error.
|
inline |
Check if the HTTP status code indicates a server error.
|
inline |
Get the announced content size in bytes.
This is the value which was sent in the content headers. This may be zero, this may not be the actual size of the content to download.
|
inline |
Get all response headers.
| [out] | headers | A multimap of all response headers. |
|
inline |
Get all response headers.
Get the value of one header.
| [in] | name | Header name, case sensitive. |
| UString ts::WebRequest::mimeType | ( | bool | simple = true, |
| bool | lowercase = true |
||
| ) | const |
Get the MIME type in the response headers.
| [in] | simple | If true, simple type name. If false, return the full specification with options. |
| [in] | lowercase | Force lowercase in the result. |
|
inline |
|
inline |
Get the final URL of the actual download operation.
It can be different from originalURL() if some HTTP redirections were performed. When called before a download operation, return originalURL().
If redirections are disabled using setAutoRedirect() and the site returned a redirection, finalURL() returns the redirected URL.
| bool ts::WebRequest::receive | ( | void * | buffer, |
| size_t | max_size, | ||
| size_t & | ret_size, | ||
| IOSB * | iosb = nullptr |
||
| ) |
Receive data.
| [out] | buffer | Address of the buffer for the received data. |
| [in] | max_size | Size in bytes of the reception buffer. |
| [out] | ret_size | Size in bytes of the received data. Will never be larger than max_size. When ret_size is zero, this is the end of the transfer. |
| [in,out] | iosb | Address of an IOSB structure. If non-null, the request must be in non-blocking mode. When null, the request must be in blocking mode (the default). See the description of IOSB. Important: The parameter iosb should not be used by applications. It should be used only by "reactive classes", which work in combination with a Reactor. |
| bool ts::WebRequest::close | ( | ) |
Close the transfer.
| void ts::WebRequest::abort | ( | ) |
Abort a transfer in progress.
Can be called from another thread.
|
inline |
Get the size in bytes of the downloaded content.
| bool ts::WebRequest::downloadBinaryContent | ( | const UString & | url, |
| ByteBlock & | data, | ||
| size_t | chunk_size = DEFAULT_CHUNK_SIZE |
||
| ) |
Download the content of the URL as binary data in one operation.
The open/read/close session is embedded in this method. The request must be in blocking mode (the default).
| [in] | url | The complete URL to fetch. |
| [out] | data | The content of the URL. |
| [in] | chunk_size | Individual download chunk size. |
| bool ts::WebRequest::downloadTextContent | ( | const UString & | url, |
| UString & | text, | ||
| size_t | chunk_size = DEFAULT_CHUNK_SIZE |
||
| ) |
Download the content of the URL as text in one operation.
The open/read/close session is embedded in this method.. The downloaded text is converted from UTF-8. End of lines are normalized as LF. The request must be in blocking mode (the default).
| [in] | url | The complete URL to fetch. |
| [out] | text | The content of the URL. |
| [in] | chunk_size | Individual download chunk size. |
| bool ts::WebRequest::downloadFile | ( | const UString & | url, |
| const fs::path & | file_name, | ||
| size_t | chunk_size = DEFAULT_CHUNK_SIZE |
||
| ) |
Download the content of the URL in a file in one operation.
The open/read/close session is embedded in this method.. No transformation is applied to the data. The request must be in blocking mode (the default).
| [in] | url | The complete URL to fetch. |
| [in] | file_name | Name of the file to create. |
| [in] | chunk_size | Individual download chunk size. |
|
static |
Get the version of the underlying HTTP library.
|
inherited |
Set the device in non-blocking mode.
Important: Usually, this method must be called before opening the device, whatever it means. Otherwise it is ignored and the device blocking mode is unchanged.
| [in] | non_blocking | It true, the device is set in non-blocking mode. |
|
inlineinherited |
Check if the device is in non-blocking mode.
|
inherited |
Check if the device is supported by a reactor for non-blocking or asynchronous I/O.
| [in] | recheck | If true, force a recheck. If false and the device was previously checked, return the previous cached value. |
|
inlinestaticinherited |
This static method checks if a system error code means "I/O in progress" (asynchronous I/O) or "I/O would block" (non-blocking I/O).
| [in] | error_code | System error code. |
|
inherited |
Get the underlying file descriptor or device handle.
This method is reserved for low-level operations and should not be used by normal applications.
On UNIX systems, sockets are standard file descriptors. On Windows systems, sockets and devices handles are two distinct types (SOCKET, an integer type, and HANDLE, a pointer type). However, SOCKET and HANDLE have the same size and can be converted between each other. In practice, all Windows device handles are pointers. When Microsoft decided to implement the BSD socket API, they needed to represent sockets as integers. The integer is simply a cast of the HANDLE pointer.
In practice, the methods getHandle() and getSocket() return the same value, represented as two different portable types, SysHandleType and SysSocketType. Note that this types are defined as their real representation. On UNIX systems, both are defined as int and are compatible. However, on Windows systems, they are defined as HANDLE and SOCKET and are not compatible. So, accidentally mixing the two compiles on UNIX but not on Windows. Be careful to use the right type for the right usage.
There is one important difference between getHandle() and getSocket(): the error values, SYS_HANDLE_INVALID and SYS_SOCKET_INVALID. Be careful, these constants have distinct binary values on Windows. This is the only case were it is not possible to cast between a SysHandleType value and a SysSocketType value. This is why it is recommended to always use getHandle() when a SysHandleType is required and getSocket() when a SysSocketType is required.
A subclass which uses file descriptors or device handles for read, write, or both, must override the methods getReadHandle(), getWriteHandle(), or both. If the two types of operations use the same file descriptor, the two methods must return the same value.
An application should call getReadHandle() for read operations and getWriteHandle() for write operations. The method getHandle() returns getReadHandle() if its returns a valid value, and getWriteHandle() otherwise.
|
virtualinherited |
Get the underlying file descriptor or device handle for read operations.
Subclasses should override this method.
Reimplemented in ts::Socket, ts::BinaryFile, and ts::ForkPipe.
|
virtualinherited |
Get the underlying file descriptor or device handle for write operations.
Subclasses should override this method.
Reimplemented in ts::Socket, ts::BinaryFile, and ts::ForkPipe.
|
inherited |
Get the underlying file descriptor or device handle as a system socket handle.
|
inherited |
Get the underlying file descriptor or device handle as a system socket handle for read operations.
|
inherited |
Get the underlying file descriptor or device handle as a system socket handle for write operations.
|
protectedinherited |
Check the blocking mode of a device.
Called by subclass methods which are explicitly called in blocking or non-blocking mode.
| [in] | non_blocking | The required non-blocking mode. |
| [in] | opname | Name of the operation, for the error message. |
Check the blocking mode of a device.
Called by subclass methods which are explicitly called in blocking or non-blocking mode.
| [in,out] | iosb | Address of an IOSB structure. If non-null, we are in non-blocking mode. When null, we are in blocking mode. When non-null, pending is reset to false and overlap is zeroed. |
| [in] | opname | Name of the operation, for the error message. |
|
protectedvirtualinherited |
Check that the non-blocking mode can be set.
Must be implemented by subclasses which do not support setting the non-blocking in certain states, such as after being opened. The default implementation always allows setting the non-blocking mode.
Reimplemented in ts::Socket, ts::BinaryFile, and ts::ForkPipe.
|
protectedinherited |
Low-level method to set the system file or socket descriptor in non-blocking mode.
| [in] | non_blocking | It true, the device is set in non-blocking mode. |
Summary: Do not use this method unless you exactly know what you are doing.
UNIX: Depending on the way a file descriptor is created, it may be possible to specify the non-blocking mode from the beginning. Or it can be somehow inherited. However, this is not portable.
Examples:
In all cases, it is possible to set a file descriptor in non-blocking mode at any time using the method setSystemNonBlocking(). This method uses fcntl(F_SETFL) to alter the file descriptor's flags.
Windows: The natural way of not being blocked on I/O on Windows is asynchronous I/O. To increase the general confusion, there is some form of non-blocking mode on Windows sockets, and only sockets, not other forms of file handles. This mode is activated using "ioctlsocket(fd, FIONBIO, &mode)". When this mode is active, socket I/O become similar to UNIX: they immediately either succeed or fail, but never block. However, there is no way to get notified when the I/O becomes possible. There is no equivalent to epoll (Linux) or kqueue (macOS and BSD). The Windows I/O Completion Ports can only work on asynchronous I/O, using OVERLAPPED structures. Because this form of non-blocking mode is mostly useless in practice, we do not use it and the method setSystemNonBlocking() does nothing on Windows.
|
protectedinherited |
Generic system write operation.
This is a convenience method which can be used (or not) by subclasses when the system calls write() (UNIX) or WriteFile() (Windows) are appropriate.
| [in] | addr | Address of the data to write. |
| [in] | size | Size in bytes of the data to write. |
| [out] | written_size | Actually written size in bytes. Can be less than size in case of error in the middle of the write. |
| [in,out] | iosb | Address of an IOSB structure. If non-null, the stream must be in non-blocking mode. When null, the stream must be in blocking mode (the default). See the description of ts::Device::IOSB. |
| [in] | position | This value is only used on Windows with asynchronous I/O on disk file. On Windows, when asynchronous I/O are used on random access files, the file position is not maintained. Each read or write operation is performed at the specified absolute position. |
|
protectedinherited |
Generic system read operation.
This is a convenience method which can be used (or not) by subclasses when the system calls read() (UNIX) or ReadFile() (Windows) are appropriate.
| [out] | addr | Address of the buffer for the incoming data. |
| [in] | max_size | Maximum size in bytes of the buffer. |
| [out] | ret_size | Returned input size in bytes. If zero, end of file has been reached or an error occurred. |
| [in] | abort | If non-zero, invoked when I/O is interrupted (in case of user-interrupt, return, otherwise retry). |
| [in,out] | iosb | Address of an IOSB structure. If non-null, the stream must be in non-blocking mode. When null, the stream must be in blocking mode (the default). See the description of ts::Device::IOSB. |
| [in] | position | This value is only used on Windows with asynchronous I/O on disk file. On Windows, when asynchronous I/O are used on random access files, the file position is not maintained. Each read or write operation is performed at the specified absolute position. |
|
overridevirtualinherited |
Access the Report which is associated with this object.
Can be called from another thread only if the Report object is thread-safe.
Implements ts::ReporterInterface.
Associate this object with another Report to log errors.
| [in] | report | Where to report errors. The report object must remain valid as long as this object exists or setReport() is used with another Report object. If report is null, log messages are discarded. |
|
inherited |
Associate this object with another ReporterBase to log errors.
| [in] | delegate | Use the report of another ReporterBase. If delegate is null, the previous explicit Report is used.. |
|
inherited |
Temporarily mute the associated report.
| [in] | mute | It true, report() will return a null report (log messages are discarded), until muteReport() is invoked again with mute set to false. |
|
inlinestaticinherited |
Compute a log severity level from a "silent" parameter.
Some subclass methods have a "silent" parameter to avoid reporting errors which may be insignificant, typically when closing a device after an error, in which case the close operation may produce other errors if the previous error left the device in an inconsistent state. While those errors should not be displayed as errors, we still display them at debug level.
| [in] | silent | If true, do not report errors, report debug messages instead. |
| [in] | default_severity | Default severity, in non-silent mode (error by default). |