xref: /openbmc/qemu/block/curl.c (revision 826cc324)
1769ce76dSAlexander Graf /*
2769ce76dSAlexander Graf  * QEMU Block driver for CURL images
3769ce76dSAlexander Graf  *
4769ce76dSAlexander Graf  * Copyright (c) 2009 Alexander Graf <agraf@suse.de>
5769ce76dSAlexander Graf  *
6769ce76dSAlexander Graf  * Permission is hereby granted, free of charge, to any person obtaining a copy
7769ce76dSAlexander Graf  * of this software and associated documentation files (the "Software"), to deal
8769ce76dSAlexander Graf  * in the Software without restriction, including without limitation the rights
9769ce76dSAlexander Graf  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10769ce76dSAlexander Graf  * copies of the Software, and to permit persons to whom the Software is
11769ce76dSAlexander Graf  * furnished to do so, subject to the following conditions:
12769ce76dSAlexander Graf  *
13769ce76dSAlexander Graf  * The above copyright notice and this permission notice shall be included in
14769ce76dSAlexander Graf  * all copies or substantial portions of the Software.
15769ce76dSAlexander Graf  *
16769ce76dSAlexander Graf  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17769ce76dSAlexander Graf  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18769ce76dSAlexander Graf  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19769ce76dSAlexander Graf  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20769ce76dSAlexander Graf  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21769ce76dSAlexander Graf  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22769ce76dSAlexander Graf  * THE SOFTWARE.
23769ce76dSAlexander Graf  */
24452fcdbcSMarkus Armbruster 
2580c71a24SPeter Maydell #include "qemu/osdep.h"
26da34e65cSMarkus Armbruster #include "qapi/error.h"
27796a060bSRichard W.M. Jones #include "qemu/error-report.h"
280b8fa32fSMarkus Armbruster #include "qemu/module.h"
29922a01a0SMarkus Armbruster #include "qemu/option.h"
30737e150eSPaolo Bonzini #include "block/block_int.h"
31452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
32d49b6836SMarkus Armbruster #include "qapi/qmp/qstring.h"
331bff9606SDaniel P. Berrange #include "crypto/secret.h"
34769ce76dSAlexander Graf #include <curl/curl.h>
35f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
36ed2a66deSLaurent Vivier #include "trace.h"
37769ce76dSAlexander Graf 
38769ce76dSAlexander Graf // #define DEBUG_VERBOSE
39769ce76dSAlexander Graf 
40fb6d1bbdSStefan Hajnoczi #define PROTOCOLS (CURLPROTO_HTTP | CURLPROTO_HTTPS | \
4123dce387SMax Reitz                    CURLPROTO_FTP | CURLPROTO_FTPS)
42fb6d1bbdSStefan Hajnoczi 
43769ce76dSAlexander Graf #define CURL_NUM_STATES 8
44769ce76dSAlexander Graf #define CURL_NUM_ACB    8
45f76faedaSRichard W.M. Jones #define CURL_TIMEOUT_MAX 10000
46769ce76dSAlexander Graf 
47e3542c67SMatthew Booth #define CURL_BLOCK_OPT_URL       "url"
48e3542c67SMatthew Booth #define CURL_BLOCK_OPT_READAHEAD "readahead"
4997a3ea57SMatthew Booth #define CURL_BLOCK_OPT_SSLVERIFY "sslverify"
50212aefaaSDaniel Henrique Barboza #define CURL_BLOCK_OPT_TIMEOUT "timeout"
51a94f83d9SRichard W.M. Jones #define CURL_BLOCK_OPT_COOKIE    "cookie"
52327c8ebdSPeter Krempa #define CURL_BLOCK_OPT_COOKIE_SECRET "cookie-secret"
531bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_USERNAME "username"
541bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PASSWORD_SECRET "password-secret"
551bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PROXY_USERNAME "proxy-username"
561bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET "proxy-password-secret"
57e3542c67SMatthew Booth 
58712b64e8SMax Reitz #define CURL_BLOCK_OPT_READAHEAD_DEFAULT (256 * 1024)
59712b64e8SMax Reitz #define CURL_BLOCK_OPT_SSLVERIFY_DEFAULT true
60712b64e8SMax Reitz #define CURL_BLOCK_OPT_TIMEOUT_DEFAULT 5
61712b64e8SMax Reitz 
62769ce76dSAlexander Graf struct BDRVCURLState;
6304878616SMax Reitz struct CURLState;
64769ce76dSAlexander Graf 
652d25964dSJeff Cody static bool libcurl_initialized;
662d25964dSJeff Cody 
67769ce76dSAlexander Graf typedef struct CURLAIOCB {
6828256d82SPaolo Bonzini     Coroutine *co;
69769ce76dSAlexander Graf     QEMUIOVector *qiov;
70363c3c85SNick Thomas 
712125e5eaSPaolo Bonzini     uint64_t offset;
722125e5eaSPaolo Bonzini     uint64_t bytes;
7328256d82SPaolo Bonzini     int ret;
74363c3c85SNick Thomas 
75769ce76dSAlexander Graf     size_t start;
76769ce76dSAlexander Graf     size_t end;
77769ce76dSAlexander Graf } CURLAIOCB;
78769ce76dSAlexander Graf 
79ff5ca166SMax Reitz typedef struct CURLSocket {
80ff5ca166SMax Reitz     int fd;
813663dca4SMax Reitz     struct BDRVCURLState *s;
82ff5ca166SMax Reitz } CURLSocket;
83ff5ca166SMax Reitz 
84769ce76dSAlexander Graf typedef struct CURLState
85769ce76dSAlexander Graf {
86769ce76dSAlexander Graf     struct BDRVCURLState *s;
87769ce76dSAlexander Graf     CURLAIOCB *acb[CURL_NUM_ACB];
88769ce76dSAlexander Graf     CURL *curl;
89769ce76dSAlexander Graf     char *orig_buf;
902125e5eaSPaolo Bonzini     uint64_t buf_start;
91769ce76dSAlexander Graf     size_t buf_off;
92769ce76dSAlexander Graf     size_t buf_len;
93769ce76dSAlexander Graf     char range[128];
94769ce76dSAlexander Graf     char errmsg[CURL_ERROR_SIZE];
95769ce76dSAlexander Graf     char in_use;
96769ce76dSAlexander Graf } CURLState;
97769ce76dSAlexander Graf 
98769ce76dSAlexander Graf typedef struct BDRVCURLState {
99769ce76dSAlexander Graf     CURLM *multi;
100031fd1beSPeter Maydell     QEMUTimer timer;
1012125e5eaSPaolo Bonzini     uint64_t len;
102769ce76dSAlexander Graf     CURLState states[CURL_NUM_STATES];
1030f418a20SMax Reitz     GHashTable *sockets; /* GINT_TO_POINTER(fd) -> socket */
104769ce76dSAlexander Graf     char *url;
105c76f4952SNolan     size_t readahead_size;
10697a3ea57SMatthew Booth     bool sslverify;
107f76faedaSRichard W.M. Jones     uint64_t timeout;
108a94f83d9SRichard W.M. Jones     char *cookie;
1093494d650SFam Zheng     bool accept_range;
11063f0f45fSStefan Hajnoczi     AioContext *aio_context;
111ba3186c4SPaolo Bonzini     QemuMutex mutex;
112709f2132SPaolo Bonzini     CoQueue free_state_waitq;
1131bff9606SDaniel P. Berrange     char *username;
1141bff9606SDaniel P. Berrange     char *password;
1151bff9606SDaniel P. Berrange     char *proxyusername;
1161bff9606SDaniel P. Berrange     char *proxypassword;
117769ce76dSAlexander Graf } BDRVCURLState;
118769ce76dSAlexander Graf 
119769ce76dSAlexander Graf static void curl_clean_state(CURLState *s);
120769ce76dSAlexander Graf static void curl_multi_do(void *arg);
121769ce76dSAlexander Graf 
1220f418a20SMax Reitz static gboolean curl_drop_socket(void *key, void *value, void *opaque)
1230f418a20SMax Reitz {
1240f418a20SMax Reitz     CURLSocket *socket = value;
1250f418a20SMax Reitz     BDRVCURLState *s = socket->s;
1260f418a20SMax Reitz 
1270f418a20SMax Reitz     aio_set_fd_handler(s->aio_context, socket->fd, false,
128*826cc324SStefan Hajnoczi                        NULL, NULL, NULL, NULL, NULL);
1290f418a20SMax Reitz     return true;
1300f418a20SMax Reitz }
1310f418a20SMax Reitz 
1320f418a20SMax Reitz static void curl_drop_all_sockets(GHashTable *sockets)
1330f418a20SMax Reitz {
1340f418a20SMax Reitz     g_hash_table_foreach_remove(sockets, curl_drop_socket, NULL);
1350f418a20SMax Reitz }
1360f418a20SMax Reitz 
13734db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
138031fd1beSPeter Maydell static int curl_timer_cb(CURLM *multi, long timeout_ms, void *opaque)
139031fd1beSPeter Maydell {
140031fd1beSPeter Maydell     BDRVCURLState *s = opaque;
141031fd1beSPeter Maydell 
142ed2a66deSLaurent Vivier     trace_curl_timer_cb(timeout_ms);
143031fd1beSPeter Maydell     if (timeout_ms == -1) {
144031fd1beSPeter Maydell         timer_del(&s->timer);
145031fd1beSPeter Maydell     } else {
146031fd1beSPeter Maydell         int64_t timeout_ns = (int64_t)timeout_ms * 1000 * 1000;
147031fd1beSPeter Maydell         timer_mod(&s->timer,
148031fd1beSPeter Maydell                   qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ns);
149031fd1beSPeter Maydell     }
150031fd1beSPeter Maydell     return 0;
151031fd1beSPeter Maydell }
152031fd1beSPeter Maydell 
15334db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
154769ce76dSAlexander Graf static int curl_sock_cb(CURL *curl, curl_socket_t fd, int action,
15563f0f45fSStefan Hajnoczi                         void *userp, void *sp)
156769ce76dSAlexander Graf {
15763f0f45fSStefan Hajnoczi     BDRVCURLState *s;
158838ef602SMatthew Booth     CURLState *state = NULL;
159ff5ca166SMax Reitz     CURLSocket *socket;
160ff5ca166SMax Reitz 
161838ef602SMatthew Booth     curl_easy_getinfo(curl, CURLINFO_PRIVATE, (char **)&state);
16263f0f45fSStefan Hajnoczi     s = state->s;
163838ef602SMatthew Booth 
1640f418a20SMax Reitz     socket = g_hash_table_lookup(s->sockets, GINT_TO_POINTER(fd));
165ff5ca166SMax Reitz     if (!socket) {
166ff5ca166SMax Reitz         socket = g_new0(CURLSocket, 1);
167ff5ca166SMax Reitz         socket->fd = fd;
1683663dca4SMax Reitz         socket->s = s;
1690f418a20SMax Reitz         g_hash_table_insert(s->sockets, GINT_TO_POINTER(fd), socket);
170ff5ca166SMax Reitz     }
171ff5ca166SMax Reitz 
172ed2a66deSLaurent Vivier     trace_curl_sock_cb(action, (int)fd);
173769ce76dSAlexander Graf     switch (action) {
174769ce76dSAlexander Graf         case CURL_POLL_IN:
175dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
176*826cc324SStefan Hajnoczi                                curl_multi_do, NULL, NULL, NULL, socket);
177769ce76dSAlexander Graf             break;
178769ce76dSAlexander Graf         case CURL_POLL_OUT:
179dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
180*826cc324SStefan Hajnoczi                                NULL, curl_multi_do, NULL, NULL, socket);
181769ce76dSAlexander Graf             break;
182769ce76dSAlexander Graf         case CURL_POLL_INOUT:
183dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
184*826cc324SStefan Hajnoczi                                curl_multi_do, curl_multi_do,
185*826cc324SStefan Hajnoczi                                NULL, NULL, socket);
186769ce76dSAlexander Graf             break;
187769ce76dSAlexander Graf         case CURL_POLL_REMOVE:
188dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
189*826cc324SStefan Hajnoczi                                NULL, NULL, NULL, NULL, NULL);
190769ce76dSAlexander Graf             break;
191769ce76dSAlexander Graf     }
192769ce76dSAlexander Graf 
193007f339bSMax Reitz     if (action == CURL_POLL_REMOVE) {
1940f418a20SMax Reitz         g_hash_table_remove(s->sockets, GINT_TO_POINTER(fd));
195007f339bSMax Reitz     }
196007f339bSMax Reitz 
197769ce76dSAlexander Graf     return 0;
198769ce76dSAlexander Graf }
199769ce76dSAlexander Graf 
20034db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
2013494d650SFam Zheng static size_t curl_header_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
202769ce76dSAlexander Graf {
2033494d650SFam Zheng     BDRVCURLState *s = opaque;
204769ce76dSAlexander Graf     size_t realsize = size * nmemb;
2057788a319SDavid Edmondson     const char *header = (char *)ptr;
2067788a319SDavid Edmondson     const char *end = header + realsize;
20769032253SDavid Edmondson     const char *accept_ranges = "accept-ranges:";
2087788a319SDavid Edmondson     const char *bytes = "bytes";
209769ce76dSAlexander Graf 
2107788a319SDavid Edmondson     if (realsize >= strlen(accept_ranges)
21169032253SDavid Edmondson         && g_ascii_strncasecmp(header, accept_ranges,
21269032253SDavid Edmondson                                strlen(accept_ranges)) == 0) {
2137788a319SDavid Edmondson 
2147788a319SDavid Edmondson         char *p = strchr(header, ':') + 1;
2157788a319SDavid Edmondson 
2167788a319SDavid Edmondson         /* Skip whitespace between the header name and value. */
2177788a319SDavid Edmondson         while (p < end && *p && g_ascii_isspace(*p)) {
2187788a319SDavid Edmondson             p++;
2197788a319SDavid Edmondson         }
2207788a319SDavid Edmondson 
2217788a319SDavid Edmondson         if (end - p >= strlen(bytes)
2227788a319SDavid Edmondson             && strncmp(p, bytes, strlen(bytes)) == 0) {
2237788a319SDavid Edmondson 
2247788a319SDavid Edmondson             /* Check that there is nothing but whitespace after the value. */
2257788a319SDavid Edmondson             p += strlen(bytes);
2267788a319SDavid Edmondson             while (p < end && *p && g_ascii_isspace(*p)) {
2277788a319SDavid Edmondson                 p++;
2287788a319SDavid Edmondson             }
2297788a319SDavid Edmondson 
2307788a319SDavid Edmondson             if (p == end || !*p) {
2313494d650SFam Zheng                 s->accept_range = true;
2320bfcd599SBlue Swirl             }
2337788a319SDavid Edmondson         }
2347788a319SDavid Edmondson     }
235769ce76dSAlexander Graf 
236769ce76dSAlexander Graf     return realsize;
237769ce76dSAlexander Graf }
238769ce76dSAlexander Graf 
23934db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
240769ce76dSAlexander Graf static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
241769ce76dSAlexander Graf {
242769ce76dSAlexander Graf     CURLState *s = ((CURLState*)opaque);
243769ce76dSAlexander Graf     size_t realsize = size * nmemb;
244769ce76dSAlexander Graf 
245ed2a66deSLaurent Vivier     trace_curl_read_cb(realsize);
246769ce76dSAlexander Graf 
2474e767657SMax Reitz     if (!s || !s->orig_buf) {
2484e767657SMax Reitz         goto read_end;
2494e767657SMax Reitz     }
250769ce76dSAlexander Graf 
2516d4b9e55SFam Zheng     if (s->buf_off >= s->buf_len) {
2526d4b9e55SFam Zheng         /* buffer full, read nothing */
2534e767657SMax Reitz         goto read_end;
2546d4b9e55SFam Zheng     }
2556d4b9e55SFam Zheng     realsize = MIN(realsize, s->buf_len - s->buf_off);
256769ce76dSAlexander Graf     memcpy(s->orig_buf + s->buf_off, ptr, realsize);
257769ce76dSAlexander Graf     s->buf_off += realsize;
258769ce76dSAlexander Graf 
2594e767657SMax Reitz read_end:
2604e767657SMax Reitz     /* curl will error out if we do not return this value */
2614e767657SMax Reitz     return size * nmemb;
262769ce76dSAlexander Graf }
263769ce76dSAlexander Graf 
264456af346SPaolo Bonzini /* Called with s->mutex held.  */
26528256d82SPaolo Bonzini static bool curl_find_buf(BDRVCURLState *s, uint64_t start, uint64_t len,
266769ce76dSAlexander Graf                           CURLAIOCB *acb)
267769ce76dSAlexander Graf {
268769ce76dSAlexander Graf     int i;
2692125e5eaSPaolo Bonzini     uint64_t end = start + len;
2702125e5eaSPaolo Bonzini     uint64_t clamped_end = MIN(end, s->len);
2712125e5eaSPaolo Bonzini     uint64_t clamped_len = clamped_end - start;
272769ce76dSAlexander Graf 
273769ce76dSAlexander Graf     for (i=0; i<CURL_NUM_STATES; i++) {
274769ce76dSAlexander Graf         CURLState *state = &s->states[i];
2752125e5eaSPaolo Bonzini         uint64_t buf_end = (state->buf_start + state->buf_off);
2762125e5eaSPaolo Bonzini         uint64_t buf_fend = (state->buf_start + state->buf_len);
277769ce76dSAlexander Graf 
278769ce76dSAlexander Graf         if (!state->orig_buf)
279769ce76dSAlexander Graf             continue;
280769ce76dSAlexander Graf         if (!state->buf_off)
281769ce76dSAlexander Graf             continue;
282769ce76dSAlexander Graf 
283769ce76dSAlexander Graf         // Does the existing buffer cover our section?
284769ce76dSAlexander Graf         if ((start >= state->buf_start) &&
285769ce76dSAlexander Graf             (start <= buf_end) &&
2864e504535SMax Reitz             (clamped_end >= state->buf_start) &&
2874e504535SMax Reitz             (clamped_end <= buf_end))
288769ce76dSAlexander Graf         {
289769ce76dSAlexander Graf             char *buf = state->orig_buf + (start - state->buf_start);
290769ce76dSAlexander Graf 
2914e504535SMax Reitz             qemu_iovec_from_buf(acb->qiov, 0, buf, clamped_len);
2924e504535SMax Reitz             if (clamped_len < len) {
2934e504535SMax Reitz                 qemu_iovec_memset(acb->qiov, clamped_len, 0, len - clamped_len);
2944e504535SMax Reitz             }
29528256d82SPaolo Bonzini             acb->ret = 0;
29628256d82SPaolo Bonzini             return true;
297769ce76dSAlexander Graf         }
298769ce76dSAlexander Graf 
299769ce76dSAlexander Graf         // Wait for unfinished chunks
300b7079df4SMatthew Booth         if (state->in_use &&
301b7079df4SMatthew Booth             (start >= state->buf_start) &&
302769ce76dSAlexander Graf             (start <= buf_fend) &&
3034e504535SMax Reitz             (clamped_end >= state->buf_start) &&
3044e504535SMax Reitz             (clamped_end <= buf_fend))
305769ce76dSAlexander Graf         {
306769ce76dSAlexander Graf             int j;
307769ce76dSAlexander Graf 
308769ce76dSAlexander Graf             acb->start = start - state->buf_start;
3094e504535SMax Reitz             acb->end = acb->start + clamped_len;
310769ce76dSAlexander Graf 
311769ce76dSAlexander Graf             for (j=0; j<CURL_NUM_ACB; j++) {
312769ce76dSAlexander Graf                 if (!state->acb[j]) {
313769ce76dSAlexander Graf                     state->acb[j] = acb;
31428256d82SPaolo Bonzini                     return true;
315769ce76dSAlexander Graf                 }
316769ce76dSAlexander Graf             }
317769ce76dSAlexander Graf         }
318769ce76dSAlexander Graf     }
319769ce76dSAlexander Graf 
32028256d82SPaolo Bonzini     return false;
321769ce76dSAlexander Graf }
322769ce76dSAlexander Graf 
323ba3186c4SPaolo Bonzini /* Called with s->mutex held.  */
324838ef602SMatthew Booth static void curl_multi_check_completion(BDRVCURLState *s)
325769ce76dSAlexander Graf {
326769ce76dSAlexander Graf     int msgs_in_queue;
327769ce76dSAlexander Graf 
328769ce76dSAlexander Graf     /* Try to find done transfers, so we can free the easy
329769ce76dSAlexander Graf      * handle again. */
3301f2cead3SMatthew Booth     for (;;) {
331769ce76dSAlexander Graf         CURLMsg *msg;
332769ce76dSAlexander Graf         msg = curl_multi_info_read(s->multi, &msgs_in_queue);
333769ce76dSAlexander Graf 
3341f2cead3SMatthew Booth         /* Quit when there are no more completions */
335769ce76dSAlexander Graf         if (!msg)
336769ce76dSAlexander Graf             break;
337769ce76dSAlexander Graf 
3381f2cead3SMatthew Booth         if (msg->msg == CURLMSG_DONE) {
339bfb23b48SMax Reitz             int i;
340769ce76dSAlexander Graf             CURLState *state = NULL;
341bfb23b48SMax Reitz             bool error = msg->data.result != CURLE_OK;
342bfb23b48SMax Reitz 
343f6246509SMatthew Booth             curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,
344f6246509SMatthew Booth                               (char **)&state);
345f785a5aeSNicholas Thomas 
346bfb23b48SMax Reitz             if (error) {
347796a060bSRichard W.M. Jones                 static int errcount = 100;
348796a060bSRichard W.M. Jones 
349796a060bSRichard W.M. Jones                 /* Don't lose the original error message from curl, since
350796a060bSRichard W.M. Jones                  * it contains extra data.
351796a060bSRichard W.M. Jones                  */
352796a060bSRichard W.M. Jones                 if (errcount > 0) {
353796a060bSRichard W.M. Jones                     error_report("curl: %s", state->errmsg);
354796a060bSRichard W.M. Jones                     if (--errcount == 0) {
355796a060bSRichard W.M. Jones                         error_report("curl: further errors suppressed");
356796a060bSRichard W.M. Jones                     }
357796a060bSRichard W.M. Jones                 }
358bfb23b48SMax Reitz             }
359796a060bSRichard W.M. Jones 
360f785a5aeSNicholas Thomas             for (i = 0; i < CURL_NUM_ACB; i++) {
361f785a5aeSNicholas Thomas                 CURLAIOCB *acb = state->acb[i];
362f785a5aeSNicholas Thomas 
363f785a5aeSNicholas Thomas                 if (acb == NULL) {
364f785a5aeSNicholas Thomas                     continue;
365f785a5aeSNicholas Thomas                 }
366f785a5aeSNicholas Thomas 
367bfb23b48SMax Reitz                 if (!error) {
368bfb23b48SMax Reitz                     /* Assert that we have read all data */
369bfb23b48SMax Reitz                     assert(state->buf_off >= acb->end);
370bfb23b48SMax Reitz 
371bfb23b48SMax Reitz                     qemu_iovec_from_buf(acb->qiov, 0,
372bfb23b48SMax Reitz                                         state->orig_buf + acb->start,
373bfb23b48SMax Reitz                                         acb->end - acb->start);
374bfb23b48SMax Reitz 
375bfb23b48SMax Reitz                     if (acb->end - acb->start < acb->bytes) {
376bfb23b48SMax Reitz                         size_t offset = acb->end - acb->start;
377bfb23b48SMax Reitz                         qemu_iovec_memset(acb->qiov, offset, 0,
378bfb23b48SMax Reitz                                           acb->bytes - offset);
379bfb23b48SMax Reitz                     }
380bfb23b48SMax Reitz                 }
381bfb23b48SMax Reitz 
382bfb23b48SMax Reitz                 acb->ret = error ? -EIO : 0;
383f785a5aeSNicholas Thomas                 state->acb[i] = NULL;
38428256d82SPaolo Bonzini                 qemu_mutex_unlock(&s->mutex);
38528256d82SPaolo Bonzini                 aio_co_wake(acb->co);
38628256d82SPaolo Bonzini                 qemu_mutex_lock(&s->mutex);
387f785a5aeSNicholas Thomas             }
388f785a5aeSNicholas Thomas 
389769ce76dSAlexander Graf             curl_clean_state(state);
390769ce76dSAlexander Graf             break;
391769ce76dSAlexander Graf         }
392769ce76dSAlexander Graf     }
393769ce76dSAlexander Graf }
394769ce76dSAlexander Graf 
395ba3186c4SPaolo Bonzini /* Called with s->mutex held.  */
3969abaf9fcSMax Reitz static void curl_multi_do_locked(CURLSocket *socket)
397031fd1beSPeter Maydell {
3983663dca4SMax Reitz     BDRVCURLState *s = socket->s;
399031fd1beSPeter Maydell     int running;
400031fd1beSPeter Maydell     int r;
401031fd1beSPeter Maydell 
4029abaf9fcSMax Reitz     if (!s->multi) {
403031fd1beSPeter Maydell         return;
404031fd1beSPeter Maydell     }
405031fd1beSPeter Maydell 
406031fd1beSPeter Maydell     do {
4079abaf9fcSMax Reitz         r = curl_multi_socket_action(s->multi, socket->fd, 0, &running);
408031fd1beSPeter Maydell     } while (r == CURLM_CALL_MULTI_PERFORM);
409ff5ca166SMax Reitz }
410838ef602SMatthew Booth 
4119d456654SPaolo Bonzini static void curl_multi_do(void *arg)
4129d456654SPaolo Bonzini {
4139dbad87dSMax Reitz     CURLSocket *socket = arg;
4143663dca4SMax Reitz     BDRVCURLState *s = socket->s;
4159d456654SPaolo Bonzini 
4169dbad87dSMax Reitz     qemu_mutex_lock(&s->mutex);
4179dbad87dSMax Reitz     curl_multi_do_locked(socket);
4189dbad87dSMax Reitz     curl_multi_check_completion(s);
4199dbad87dSMax Reitz     qemu_mutex_unlock(&s->mutex);
420031fd1beSPeter Maydell }
421031fd1beSPeter Maydell 
422031fd1beSPeter Maydell static void curl_multi_timeout_do(void *arg)
423031fd1beSPeter Maydell {
424031fd1beSPeter Maydell     BDRVCURLState *s = (BDRVCURLState *)arg;
425031fd1beSPeter Maydell     int running;
426031fd1beSPeter Maydell 
427031fd1beSPeter Maydell     if (!s->multi) {
428031fd1beSPeter Maydell         return;
429031fd1beSPeter Maydell     }
430031fd1beSPeter Maydell 
431ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
432031fd1beSPeter Maydell     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
433031fd1beSPeter Maydell 
434838ef602SMatthew Booth     curl_multi_check_completion(s);
435ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
436031fd1beSPeter Maydell }
437031fd1beSPeter Maydell 
438456af346SPaolo Bonzini /* Called with s->mutex held.  */
4393ce6a729SPaolo Bonzini static CURLState *curl_find_state(BDRVCURLState *s)
440769ce76dSAlexander Graf {
441769ce76dSAlexander Graf     CURLState *state = NULL;
4423ce6a729SPaolo Bonzini     int i;
443769ce76dSAlexander Graf 
444769ce76dSAlexander Graf     for (i = 0; i < CURL_NUM_STATES; i++) {
4453ce6a729SPaolo Bonzini         if (!s->states[i].in_use) {
446769ce76dSAlexander Graf             state = &s->states[i];
447769ce76dSAlexander Graf             state->in_use = 1;
448769ce76dSAlexander Graf             break;
449769ce76dSAlexander Graf         }
450769ce76dSAlexander Graf     }
4513ce6a729SPaolo Bonzini     return state;
4523ce6a729SPaolo Bonzini }
453769ce76dSAlexander Graf 
4543ce6a729SPaolo Bonzini static int curl_init_state(BDRVCURLState *s, CURLState *state)
4553ce6a729SPaolo Bonzini {
4569e550b32SMatthew Booth     if (!state->curl) {
457769ce76dSAlexander Graf         state->curl = curl_easy_init();
4589e550b32SMatthew Booth         if (!state->curl) {
4593ce6a729SPaolo Bonzini             return -EIO;
4609e550b32SMatthew Booth         }
461769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
46297a3ea57SMatthew Booth         curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,
46397a3ea57SMatthew Booth                          (long) s->sslverify);
464637fa44aSRichard W.M. Jones         curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYHOST,
465637fa44aSRichard W.M. Jones                          s->sslverify ? 2L : 0L);
466a94f83d9SRichard W.M. Jones         if (s->cookie) {
467a94f83d9SRichard W.M. Jones             curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);
468a94f83d9SRichard W.M. Jones         }
469f76faedaSRichard W.M. Jones         curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);
4709e550b32SMatthew Booth         curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,
4719e550b32SMatthew Booth                          (void *)curl_read_cb);
472769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
473769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
474769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
475769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
476769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
477769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
478f785a5aeSNicholas Thomas         curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
479769ce76dSAlexander Graf 
4801bff9606SDaniel P. Berrange         if (s->username) {
4811bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);
4821bff9606SDaniel P. Berrange         }
4831bff9606SDaniel P. Berrange         if (s->password) {
4841bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);
4851bff9606SDaniel P. Berrange         }
4861bff9606SDaniel P. Berrange         if (s->proxyusername) {
4871bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl,
4881bff9606SDaniel P. Berrange                              CURLOPT_PROXYUSERNAME, s->proxyusername);
4891bff9606SDaniel P. Berrange         }
4901bff9606SDaniel P. Berrange         if (s->proxypassword) {
4911bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl,
4921bff9606SDaniel P. Berrange                              CURLOPT_PROXYPASSWORD, s->proxypassword);
4931bff9606SDaniel P. Berrange         }
4941bff9606SDaniel P. Berrange 
495fb6d1bbdSStefan Hajnoczi         /* Restrict supported protocols to avoid security issues in the more
496fb6d1bbdSStefan Hajnoczi          * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see
497fb6d1bbdSStefan Hajnoczi          * CVE-2013-0249.
4988a8f5840SStefan Hajnoczi          *
4998a8f5840SStefan Hajnoczi          * Restricting protocols is only supported from 7.19.4 upwards.
500fb6d1bbdSStefan Hajnoczi          */
5018a8f5840SStefan Hajnoczi #if LIBCURL_VERSION_NUM >= 0x071304
502fb6d1bbdSStefan Hajnoczi         curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
503fb6d1bbdSStefan Hajnoczi         curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
5048a8f5840SStefan Hajnoczi #endif
505fb6d1bbdSStefan Hajnoczi 
506769ce76dSAlexander Graf #ifdef DEBUG_VERBOSE
507769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
508769ce76dSAlexander Graf #endif
5099e550b32SMatthew Booth     }
510769ce76dSAlexander Graf 
511769ce76dSAlexander Graf     state->s = s;
512769ce76dSAlexander Graf 
5133ce6a729SPaolo Bonzini     return 0;
514769ce76dSAlexander Graf }
515769ce76dSAlexander Graf 
516456af346SPaolo Bonzini /* Called with s->mutex held.  */
517769ce76dSAlexander Graf static void curl_clean_state(CURLState *s)
518769ce76dSAlexander Graf {
519675a7756SPaolo Bonzini     int j;
520675a7756SPaolo Bonzini     for (j = 0; j < CURL_NUM_ACB; j++) {
521675a7756SPaolo Bonzini         assert(!s->acb[j]);
522675a7756SPaolo Bonzini     }
523675a7756SPaolo Bonzini 
524769ce76dSAlexander Graf     if (s->s->multi)
525769ce76dSAlexander Graf         curl_multi_remove_handle(s->s->multi, s->curl);
526ff5ca166SMax Reitz 
527769ce76dSAlexander Graf     s->in_use = 0;
5282bb5c936SPaolo Bonzini 
529709f2132SPaolo Bonzini     qemu_co_enter_next(&s->s->free_state_waitq, &s->s->mutex);
530769ce76dSAlexander Graf }
531769ce76dSAlexander Graf 
5328e6d58cdSKevin Wolf static void curl_parse_filename(const char *filename, QDict *options,
5338e6d58cdSKevin Wolf                                 Error **errp)
534769ce76dSAlexander Graf {
53546f5ac20SEric Blake     qdict_put_str(options, CURL_BLOCK_OPT_URL, filename);
5368e6d58cdSKevin Wolf }
5378e6d58cdSKevin Wolf 
53863f0f45fSStefan Hajnoczi static void curl_detach_aio_context(BlockDriverState *bs)
53963f0f45fSStefan Hajnoczi {
54063f0f45fSStefan Hajnoczi     BDRVCURLState *s = bs->opaque;
54163f0f45fSStefan Hajnoczi     int i;
54263f0f45fSStefan Hajnoczi 
543f5056b70SGan Qixin     WITH_QEMU_LOCK_GUARD(&s->mutex) {
5440f418a20SMax Reitz         curl_drop_all_sockets(s->sockets);
54563f0f45fSStefan Hajnoczi         for (i = 0; i < CURL_NUM_STATES; i++) {
54663f0f45fSStefan Hajnoczi             if (s->states[i].in_use) {
54763f0f45fSStefan Hajnoczi                 curl_clean_state(&s->states[i]);
54863f0f45fSStefan Hajnoczi             }
54963f0f45fSStefan Hajnoczi             if (s->states[i].curl) {
55063f0f45fSStefan Hajnoczi                 curl_easy_cleanup(s->states[i].curl);
55163f0f45fSStefan Hajnoczi                 s->states[i].curl = NULL;
55263f0f45fSStefan Hajnoczi             }
55363f0f45fSStefan Hajnoczi             g_free(s->states[i].orig_buf);
55463f0f45fSStefan Hajnoczi             s->states[i].orig_buf = NULL;
55563f0f45fSStefan Hajnoczi         }
55663f0f45fSStefan Hajnoczi         if (s->multi) {
55763f0f45fSStefan Hajnoczi             curl_multi_cleanup(s->multi);
55863f0f45fSStefan Hajnoczi             s->multi = NULL;
55963f0f45fSStefan Hajnoczi         }
560f5056b70SGan Qixin     }
56163f0f45fSStefan Hajnoczi 
56263f0f45fSStefan Hajnoczi     timer_del(&s->timer);
56363f0f45fSStefan Hajnoczi }
56463f0f45fSStefan Hajnoczi 
56563f0f45fSStefan Hajnoczi static void curl_attach_aio_context(BlockDriverState *bs,
56663f0f45fSStefan Hajnoczi                                     AioContext *new_context)
56763f0f45fSStefan Hajnoczi {
56863f0f45fSStefan Hajnoczi     BDRVCURLState *s = bs->opaque;
56963f0f45fSStefan Hajnoczi 
57063f0f45fSStefan Hajnoczi     aio_timer_init(new_context, &s->timer,
57163f0f45fSStefan Hajnoczi                    QEMU_CLOCK_REALTIME, SCALE_NS,
57263f0f45fSStefan Hajnoczi                    curl_multi_timeout_do, s);
57363f0f45fSStefan Hajnoczi 
57463f0f45fSStefan Hajnoczi     assert(!s->multi);
57563f0f45fSStefan Hajnoczi     s->multi = curl_multi_init();
57663f0f45fSStefan Hajnoczi     s->aio_context = new_context;
57763f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
57863f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
57963f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
58063f0f45fSStefan Hajnoczi }
58163f0f45fSStefan Hajnoczi 
5828e6d58cdSKevin Wolf static QemuOptsList runtime_opts = {
5838e6d58cdSKevin Wolf     .name = "curl",
5848e6d58cdSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
5858e6d58cdSKevin Wolf     .desc = {
5868e6d58cdSKevin Wolf         {
587e3542c67SMatthew Booth             .name = CURL_BLOCK_OPT_URL,
5888e6d58cdSKevin Wolf             .type = QEMU_OPT_STRING,
5898e6d58cdSKevin Wolf             .help = "URL to open",
5908e6d58cdSKevin Wolf         },
5918e6d58cdSKevin Wolf         {
592e3542c67SMatthew Booth             .name = CURL_BLOCK_OPT_READAHEAD,
5938e6d58cdSKevin Wolf             .type = QEMU_OPT_SIZE,
5948e6d58cdSKevin Wolf             .help = "Readahead size",
5958e6d58cdSKevin Wolf         },
59697a3ea57SMatthew Booth         {
59797a3ea57SMatthew Booth             .name = CURL_BLOCK_OPT_SSLVERIFY,
59897a3ea57SMatthew Booth             .type = QEMU_OPT_BOOL,
59997a3ea57SMatthew Booth             .help = "Verify SSL certificate"
60097a3ea57SMatthew Booth         },
601212aefaaSDaniel Henrique Barboza         {
602212aefaaSDaniel Henrique Barboza             .name = CURL_BLOCK_OPT_TIMEOUT,
603212aefaaSDaniel Henrique Barboza             .type = QEMU_OPT_NUMBER,
604212aefaaSDaniel Henrique Barboza             .help = "Curl timeout"
605212aefaaSDaniel Henrique Barboza         },
606a94f83d9SRichard W.M. Jones         {
607a94f83d9SRichard W.M. Jones             .name = CURL_BLOCK_OPT_COOKIE,
608a94f83d9SRichard W.M. Jones             .type = QEMU_OPT_STRING,
609a94f83d9SRichard W.M. Jones             .help = "Pass the cookie or list of cookies with each request"
610a94f83d9SRichard W.M. Jones         },
6111bff9606SDaniel P. Berrange         {
612327c8ebdSPeter Krempa             .name = CURL_BLOCK_OPT_COOKIE_SECRET,
613327c8ebdSPeter Krempa             .type = QEMU_OPT_STRING,
614327c8ebdSPeter Krempa             .help = "ID of secret used as cookie passed with each request"
615327c8ebdSPeter Krempa         },
616327c8ebdSPeter Krempa         {
6171bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_USERNAME,
6181bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6191bff9606SDaniel P. Berrange             .help = "Username for HTTP auth"
6201bff9606SDaniel P. Berrange         },
6211bff9606SDaniel P. Berrange         {
6221bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PASSWORD_SECRET,
6231bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6241bff9606SDaniel P. Berrange             .help = "ID of secret used as password for HTTP auth",
6251bff9606SDaniel P. Berrange         },
6261bff9606SDaniel P. Berrange         {
6271bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PROXY_USERNAME,
6281bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6291bff9606SDaniel P. Berrange             .help = "Username for HTTP proxy auth"
6301bff9606SDaniel P. Berrange         },
6311bff9606SDaniel P. Berrange         {
6321bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
6331bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6341bff9606SDaniel P. Berrange             .help = "ID of secret used as password for HTTP proxy auth",
6351bff9606SDaniel P. Berrange         },
6368e6d58cdSKevin Wolf         { /* end of list */ }
6378e6d58cdSKevin Wolf     },
6388e6d58cdSKevin Wolf };
6398e6d58cdSKevin Wolf 
6401bff9606SDaniel P. Berrange 
641015a1036SMax Reitz static int curl_open(BlockDriverState *bs, QDict *options, int flags,
642015a1036SMax Reitz                      Error **errp)
6438e6d58cdSKevin Wolf {
6448e6d58cdSKevin Wolf     BDRVCURLState *s = bs->opaque;
6458e6d58cdSKevin Wolf     CURLState *state = NULL;
6468e6d58cdSKevin Wolf     QemuOpts *opts;
6478e6d58cdSKevin Wolf     const char *file;
648a94f83d9SRichard W.M. Jones     const char *cookie;
649327c8ebdSPeter Krempa     const char *cookie_secret;
6508e6d58cdSKevin Wolf     double d;
6511bff9606SDaniel P. Berrange     const char *secretid;
65234634ca2SMax Reitz     const char *protocol_delimiter;
6532d25964dSJeff Cody     int ret;
6548e6d58cdSKevin Wolf 
6556ceef36aSKevin Wolf     ret = bdrv_apply_auto_read_only(bs, "curl driver does not support writes",
6566ceef36aSKevin Wolf                                     errp);
6576ceef36aSKevin Wolf     if (ret < 0) {
6586ceef36aSKevin Wolf         return ret;
659a7cea2baSRichard W.M. Jones     }
660a7cea2baSRichard W.M. Jones 
6612d25964dSJeff Cody     if (!libcurl_initialized) {
6622d25964dSJeff Cody         ret = curl_global_init(CURL_GLOBAL_ALL);
6632d25964dSJeff Cody         if (ret) {
6642d25964dSJeff Cody             error_setg(errp, "libcurl initialization failed with %d", ret);
6652d25964dSJeff Cody             return -EIO;
6662d25964dSJeff Cody         }
6672d25964dSJeff Cody         libcurl_initialized = true;
6682d25964dSJeff Cody     }
6692d25964dSJeff Cody 
670456af346SPaolo Bonzini     qemu_mutex_init(&s->mutex);
67187ea75d5SPeter Crosthwaite     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
672668f62ecSMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
6738e6d58cdSKevin Wolf         goto out_noclean;
6748e6d58cdSKevin Wolf     }
6758e6d58cdSKevin Wolf 
676e3542c67SMatthew Booth     s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
677712b64e8SMax Reitz                                           CURL_BLOCK_OPT_READAHEAD_DEFAULT);
678c76f4952SNolan     if ((s->readahead_size & 0x1ff) != 0) {
6792a94fee3SPaolo Bonzini         error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
680c76f4952SNolan                    s->readahead_size);
681c76f4952SNolan         goto out_noclean;
682c76f4952SNolan     }
683c76f4952SNolan 
684212aefaaSDaniel Henrique Barboza     s->timeout = qemu_opt_get_number(opts, CURL_BLOCK_OPT_TIMEOUT,
685712b64e8SMax Reitz                                      CURL_BLOCK_OPT_TIMEOUT_DEFAULT);
686f76faedaSRichard W.M. Jones     if (s->timeout > CURL_TIMEOUT_MAX) {
687f76faedaSRichard W.M. Jones         error_setg(errp, "timeout parameter is too large or negative");
688f76faedaSRichard W.M. Jones         goto out_noclean;
689f76faedaSRichard W.M. Jones     }
690212aefaaSDaniel Henrique Barboza 
691712b64e8SMax Reitz     s->sslverify = qemu_opt_get_bool(opts, CURL_BLOCK_OPT_SSLVERIFY,
692712b64e8SMax Reitz                                      CURL_BLOCK_OPT_SSLVERIFY_DEFAULT);
69397a3ea57SMatthew Booth 
694a94f83d9SRichard W.M. Jones     cookie = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE);
695327c8ebdSPeter Krempa     cookie_secret = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE_SECRET);
696327c8ebdSPeter Krempa 
697327c8ebdSPeter Krempa     if (cookie && cookie_secret) {
698327c8ebdSPeter Krempa         error_setg(errp,
699327c8ebdSPeter Krempa                    "curl driver cannot handle both cookie and cookie secret");
700327c8ebdSPeter Krempa         goto out_noclean;
701327c8ebdSPeter Krempa     }
702327c8ebdSPeter Krempa 
703327c8ebdSPeter Krempa     if (cookie_secret) {
704327c8ebdSPeter Krempa         s->cookie = qcrypto_secret_lookup_as_utf8(cookie_secret, errp);
705327c8ebdSPeter Krempa         if (!s->cookie) {
706327c8ebdSPeter Krempa             goto out_noclean;
707327c8ebdSPeter Krempa         }
708327c8ebdSPeter Krempa     } else {
709a94f83d9SRichard W.M. Jones         s->cookie = g_strdup(cookie);
710327c8ebdSPeter Krempa     }
711a94f83d9SRichard W.M. Jones 
712e3542c67SMatthew Booth     file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
7138e6d58cdSKevin Wolf     if (file == NULL) {
7142a94fee3SPaolo Bonzini         error_setg(errp, "curl block driver requires an 'url' option");
7158e6d58cdSKevin Wolf         goto out_noclean;
7168e6d58cdSKevin Wolf     }
7178e6d58cdSKevin Wolf 
71834634ca2SMax Reitz     if (!strstart(file, bs->drv->protocol_name, &protocol_delimiter) ||
71934634ca2SMax Reitz         !strstart(protocol_delimiter, "://", NULL))
72034634ca2SMax Reitz     {
72134634ca2SMax Reitz         error_setg(errp, "%s curl driver cannot handle the URL '%s' (does not "
72234634ca2SMax Reitz                    "start with '%s://')", bs->drv->protocol_name, file,
72334634ca2SMax Reitz                    bs->drv->protocol_name);
72434634ca2SMax Reitz         goto out_noclean;
72534634ca2SMax Reitz     }
72634634ca2SMax Reitz 
7271bff9606SDaniel P. Berrange     s->username = g_strdup(qemu_opt_get(opts, CURL_BLOCK_OPT_USERNAME));
7281bff9606SDaniel P. Berrange     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PASSWORD_SECRET);
7291bff9606SDaniel P. Berrange 
7301bff9606SDaniel P. Berrange     if (secretid) {
7311bff9606SDaniel P. Berrange         s->password = qcrypto_secret_lookup_as_utf8(secretid, errp);
7321bff9606SDaniel P. Berrange         if (!s->password) {
7331bff9606SDaniel P. Berrange             goto out_noclean;
7341bff9606SDaniel P. Berrange         }
7351bff9606SDaniel P. Berrange     }
7361bff9606SDaniel P. Berrange 
7371bff9606SDaniel P. Berrange     s->proxyusername = g_strdup(
7381bff9606SDaniel P. Berrange         qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_USERNAME));
7391bff9606SDaniel P. Berrange     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET);
7401bff9606SDaniel P. Berrange     if (secretid) {
7411bff9606SDaniel P. Berrange         s->proxypassword = qcrypto_secret_lookup_as_utf8(secretid, errp);
7421bff9606SDaniel P. Berrange         if (!s->proxypassword) {
7431bff9606SDaniel P. Berrange             goto out_noclean;
7441bff9606SDaniel P. Berrange         }
7451bff9606SDaniel P. Berrange     }
7461bff9606SDaniel P. Berrange 
747ed2a66deSLaurent Vivier     trace_curl_open(file);
748709f2132SPaolo Bonzini     qemu_co_queue_init(&s->free_state_waitq);
74963f0f45fSStefan Hajnoczi     s->aio_context = bdrv_get_aio_context(bs);
7508e6d58cdSKevin Wolf     s->url = g_strdup(file);
7510f418a20SMax Reitz     s->sockets = g_hash_table_new_full(NULL, NULL, NULL, g_free);
752456af346SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
7533ce6a729SPaolo Bonzini     state = curl_find_state(s);
754456af346SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
7553ce6a729SPaolo Bonzini     if (!state) {
756769ce76dSAlexander Graf         goto out_noclean;
7573ce6a729SPaolo Bonzini     }
758769ce76dSAlexander Graf 
759769ce76dSAlexander Graf     // Get file size
760769ce76dSAlexander Graf 
7613ce6a729SPaolo Bonzini     if (curl_init_state(s, state) < 0) {
7623ce6a729SPaolo Bonzini         goto out;
7633ce6a729SPaolo Bonzini     }
7643ce6a729SPaolo Bonzini 
7653494d650SFam Zheng     s->accept_range = false;
766769ce76dSAlexander Graf     curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
7673494d650SFam Zheng     curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
7683494d650SFam Zheng                      curl_header_cb);
7693494d650SFam Zheng     curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
770769ce76dSAlexander Graf     if (curl_easy_perform(state->curl))
771769ce76dSAlexander Graf         goto out;
772a41c4578STomáš Golembiovský     if (curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) {
773769ce76dSAlexander Graf         goto out;
774a41c4578STomáš Golembiovský     }
775a41c4578STomáš Golembiovský     /* Prior CURL 7.19.4 return value of 0 could mean that the file size is not
776a41c4578STomáš Golembiovský      * know or the size is zero. From 7.19.4 CURL returns -1 if size is not
77750d6a8a3SStefan Weil      * known and zero if it is really zero-length file. */
778a41c4578STomáš Golembiovský #if LIBCURL_VERSION_NUM >= 0x071304
779a41c4578STomáš Golembiovský     if (d < 0) {
780a41c4578STomáš Golembiovský         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
781a41c4578STomáš Golembiovský                 "Server didn't report file size.");
782a41c4578STomáš Golembiovský         goto out;
783a41c4578STomáš Golembiovský     }
784a41c4578STomáš Golembiovský #else
785a41c4578STomáš Golembiovský     if (d <= 0) {
786a41c4578STomáš Golembiovský         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
787a41c4578STomáš Golembiovský                 "Unknown file size or zero-length file.");
788a41c4578STomáš Golembiovský         goto out;
789a41c4578STomáš Golembiovský     }
790a41c4578STomáš Golembiovský #endif
791a41c4578STomáš Golembiovský 
7922125e5eaSPaolo Bonzini     s->len = d;
793a41c4578STomáš Golembiovský 
7943494d650SFam Zheng     if ((!strncasecmp(s->url, "http://", strlen("http://"))
7953494d650SFam Zheng         || !strncasecmp(s->url, "https://", strlen("https://")))
7963494d650SFam Zheng         && !s->accept_range) {
7973494d650SFam Zheng         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
7983494d650SFam Zheng                 "Server does not support 'range' (byte ranges).");
7993494d650SFam Zheng         goto out;
8003494d650SFam Zheng     }
801ed2a66deSLaurent Vivier     trace_curl_open_size(s->len);
802769ce76dSAlexander Graf 
803456af346SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
804769ce76dSAlexander Graf     curl_clean_state(state);
805456af346SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
806769ce76dSAlexander Graf     curl_easy_cleanup(state->curl);
807769ce76dSAlexander Graf     state->curl = NULL;
808769ce76dSAlexander Graf 
80963f0f45fSStefan Hajnoczi     curl_attach_aio_context(bs, bdrv_get_aio_context(bs));
810769ce76dSAlexander Graf 
8118e6d58cdSKevin Wolf     qemu_opts_del(opts);
812769ce76dSAlexander Graf     return 0;
813769ce76dSAlexander Graf 
814769ce76dSAlexander Graf out:
815acd7fdc6SMaria Kustova     error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
816769ce76dSAlexander Graf     curl_easy_cleanup(state->curl);
817769ce76dSAlexander Graf     state->curl = NULL;
818769ce76dSAlexander Graf out_noclean:
819456af346SPaolo Bonzini     qemu_mutex_destroy(&s->mutex);
820a94f83d9SRichard W.M. Jones     g_free(s->cookie);
8218e6d58cdSKevin Wolf     g_free(s->url);
822996922deSJeff Cody     g_free(s->username);
823996922deSJeff Cody     g_free(s->proxyusername);
824996922deSJeff Cody     g_free(s->proxypassword);
8250f418a20SMax Reitz     curl_drop_all_sockets(s->sockets);
8260f418a20SMax Reitz     g_hash_table_destroy(s->sockets);
8278e6d58cdSKevin Wolf     qemu_opts_del(opts);
828769ce76dSAlexander Graf     return -EINVAL;
829769ce76dSAlexander Graf }
830769ce76dSAlexander Graf 
83128256d82SPaolo Bonzini static void curl_setup_preadv(BlockDriverState *bs, CURLAIOCB *acb)
832769ce76dSAlexander Graf {
833769ce76dSAlexander Graf     CURLState *state;
834b69cdef8SMatthew Booth     int running;
835769ce76dSAlexander Graf 
8361919631eSPaolo Bonzini     BDRVCURLState *s = bs->opaque;
837769ce76dSAlexander Graf 
8382125e5eaSPaolo Bonzini     uint64_t start = acb->offset;
8392125e5eaSPaolo Bonzini     uint64_t end;
840769ce76dSAlexander Graf 
841ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
8421919631eSPaolo Bonzini 
843769ce76dSAlexander Graf     // In case we have the requested data already (e.g. read-ahead),
844769ce76dSAlexander Graf     // we can just call the callback and be done.
84528256d82SPaolo Bonzini     if (curl_find_buf(s, start, acb->bytes, acb)) {
84634db05e7SPaolo Bonzini         goto out;
847769ce76dSAlexander Graf     }
848769ce76dSAlexander Graf 
849769ce76dSAlexander Graf     // No cache found, so let's start a new request
8503ce6a729SPaolo Bonzini     for (;;) {
8513ce6a729SPaolo Bonzini         state = curl_find_state(s);
8523ce6a729SPaolo Bonzini         if (state) {
8533ce6a729SPaolo Bonzini             break;
8543ce6a729SPaolo Bonzini         }
855709f2132SPaolo Bonzini         qemu_co_queue_wait(&s->free_state_waitq, &s->mutex);
8563ce6a729SPaolo Bonzini     }
8573ce6a729SPaolo Bonzini 
8583ce6a729SPaolo Bonzini     if (curl_init_state(s, state) < 0) {
8593ce6a729SPaolo Bonzini         curl_clean_state(state);
86028256d82SPaolo Bonzini         acb->ret = -EIO;
8611919631eSPaolo Bonzini         goto out;
862363c3c85SNick Thomas     }
863769ce76dSAlexander Graf 
864769ce76dSAlexander Graf     acb->start = 0;
8652125e5eaSPaolo Bonzini     acb->end = MIN(acb->bytes, s->len - start);
866769ce76dSAlexander Graf 
867769ce76dSAlexander Graf     state->buf_off = 0;
8687267c094SAnthony Liguori     g_free(state->orig_buf);
869769ce76dSAlexander Graf     state->buf_start = start;
8704e504535SMax Reitz     state->buf_len = MIN(acb->end + s->readahead_size, s->len - start);
8714e504535SMax Reitz     end = start + state->buf_len - 1;
8728dc7a772SKevin Wolf     state->orig_buf = g_try_malloc(state->buf_len);
8738dc7a772SKevin Wolf     if (state->buf_len && state->orig_buf == NULL) {
8748dc7a772SKevin Wolf         curl_clean_state(state);
87528256d82SPaolo Bonzini         acb->ret = -ENOMEM;
8761919631eSPaolo Bonzini         goto out;
8778dc7a772SKevin Wolf     }
878769ce76dSAlexander Graf     state->acb[0] = acb;
879769ce76dSAlexander Graf 
8802125e5eaSPaolo Bonzini     snprintf(state->range, 127, "%" PRIu64 "-%" PRIu64, start, end);
881ed2a66deSLaurent Vivier     trace_curl_setup_preadv(acb->bytes, start, state->range);
882769ce76dSAlexander Graf     curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
883769ce76dSAlexander Graf 
884c34dc07fSMax Reitz     if (curl_multi_add_handle(s->multi, state->curl) != CURLM_OK) {
885c34dc07fSMax Reitz         state->acb[0] = NULL;
886c34dc07fSMax Reitz         acb->ret = -EIO;
887c34dc07fSMax Reitz 
888c34dc07fSMax Reitz         curl_clean_state(state);
889c34dc07fSMax Reitz         goto out;
890c34dc07fSMax Reitz     }
891769ce76dSAlexander Graf 
892b69cdef8SMatthew Booth     /* Tell curl it needs to kick things off */
893b69cdef8SMatthew Booth     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
8941919631eSPaolo Bonzini 
8951919631eSPaolo Bonzini out:
896ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
897363c3c85SNick Thomas }
898363c3c85SNick Thomas 
89928256d82SPaolo Bonzini static int coroutine_fn curl_co_preadv(BlockDriverState *bs,
900f7ef38ddSVladimir Sementsov-Ogievskiy         int64_t offset, int64_t bytes, QEMUIOVector *qiov,
901f7ef38ddSVladimir Sementsov-Ogievskiy         BdrvRequestFlags flags)
902363c3c85SNick Thomas {
90328256d82SPaolo Bonzini     CURLAIOCB acb = {
90428256d82SPaolo Bonzini         .co = qemu_coroutine_self(),
90528256d82SPaolo Bonzini         .ret = -EINPROGRESS,
90628256d82SPaolo Bonzini         .qiov = qiov,
90728256d82SPaolo Bonzini         .offset = offset,
90828256d82SPaolo Bonzini         .bytes = bytes
90928256d82SPaolo Bonzini     };
910363c3c85SNick Thomas 
91128256d82SPaolo Bonzini     curl_setup_preadv(bs, &acb);
91228256d82SPaolo Bonzini     while (acb.ret == -EINPROGRESS) {
91328256d82SPaolo Bonzini         qemu_coroutine_yield();
91428256d82SPaolo Bonzini     }
91528256d82SPaolo Bonzini     return acb.ret;
916769ce76dSAlexander Graf }
917769ce76dSAlexander Graf 
918769ce76dSAlexander Graf static void curl_close(BlockDriverState *bs)
919769ce76dSAlexander Graf {
920769ce76dSAlexander Graf     BDRVCURLState *s = bs->opaque;
921769ce76dSAlexander Graf 
922ed2a66deSLaurent Vivier     trace_curl_close();
92363f0f45fSStefan Hajnoczi     curl_detach_aio_context(bs);
924ba3186c4SPaolo Bonzini     qemu_mutex_destroy(&s->mutex);
925031fd1beSPeter Maydell 
9260f418a20SMax Reitz     g_hash_table_destroy(s->sockets);
927a94f83d9SRichard W.M. Jones     g_free(s->cookie);
92845724d6dSStefan Weil     g_free(s->url);
929996922deSJeff Cody     g_free(s->username);
930996922deSJeff Cody     g_free(s->proxyusername);
931996922deSJeff Cody     g_free(s->proxypassword);
932769ce76dSAlexander Graf }
933769ce76dSAlexander Graf 
934769ce76dSAlexander Graf static int64_t curl_getlength(BlockDriverState *bs)
935769ce76dSAlexander Graf {
936769ce76dSAlexander Graf     BDRVCURLState *s = bs->opaque;
937769ce76dSAlexander Graf     return s->len;
938769ce76dSAlexander Graf }
939769ce76dSAlexander Graf 
940937c007bSMax Reitz static void curl_refresh_filename(BlockDriverState *bs)
941937c007bSMax Reitz {
942937c007bSMax Reitz     BDRVCURLState *s = bs->opaque;
943937c007bSMax Reitz 
944937c007bSMax Reitz     /* "readahead" and "timeout" do not change the guest-visible data,
945937c007bSMax Reitz      * so ignore them */
946937c007bSMax Reitz     if (s->sslverify != CURL_BLOCK_OPT_SSLVERIFY_DEFAULT ||
947937c007bSMax Reitz         s->cookie || s->username || s->password || s->proxyusername ||
948937c007bSMax Reitz         s->proxypassword)
949937c007bSMax Reitz     {
950937c007bSMax Reitz         return;
951937c007bSMax Reitz     }
952937c007bSMax Reitz 
953937c007bSMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), s->url);
954937c007bSMax Reitz }
955937c007bSMax Reitz 
956937c007bSMax Reitz 
9572654267cSMax Reitz static const char *const curl_strong_runtime_opts[] = {
9582654267cSMax Reitz     CURL_BLOCK_OPT_URL,
9592654267cSMax Reitz     CURL_BLOCK_OPT_SSLVERIFY,
9602654267cSMax Reitz     CURL_BLOCK_OPT_COOKIE,
9612654267cSMax Reitz     CURL_BLOCK_OPT_COOKIE_SECRET,
9622654267cSMax Reitz     CURL_BLOCK_OPT_USERNAME,
9632654267cSMax Reitz     CURL_BLOCK_OPT_PASSWORD_SECRET,
9642654267cSMax Reitz     CURL_BLOCK_OPT_PROXY_USERNAME,
9652654267cSMax Reitz     CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
9662654267cSMax Reitz 
9672654267cSMax Reitz     NULL
9682654267cSMax Reitz };
9692654267cSMax Reitz 
970769ce76dSAlexander Graf static BlockDriver bdrv_http = {
971769ce76dSAlexander Graf     .format_name                = "http",
972769ce76dSAlexander Graf     .protocol_name              = "http",
973769ce76dSAlexander Graf 
974769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
9758e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
97666f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
977769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
978769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
979769ce76dSAlexander Graf 
98028256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
98163f0f45fSStefan Hajnoczi 
98263f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
98363f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
9842654267cSMax Reitz 
985937c007bSMax Reitz     .bdrv_refresh_filename      = curl_refresh_filename,
9862654267cSMax Reitz     .strong_runtime_opts        = curl_strong_runtime_opts,
987769ce76dSAlexander Graf };
988769ce76dSAlexander Graf 
989769ce76dSAlexander Graf static BlockDriver bdrv_https = {
990769ce76dSAlexander Graf     .format_name                = "https",
991769ce76dSAlexander Graf     .protocol_name              = "https",
992769ce76dSAlexander Graf 
993769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
9948e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
99566f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
996769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
997769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
998769ce76dSAlexander Graf 
99928256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
100063f0f45fSStefan Hajnoczi 
100163f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
100263f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
10032654267cSMax Reitz 
1004937c007bSMax Reitz     .bdrv_refresh_filename      = curl_refresh_filename,
10052654267cSMax Reitz     .strong_runtime_opts        = curl_strong_runtime_opts,
1006769ce76dSAlexander Graf };
1007769ce76dSAlexander Graf 
1008769ce76dSAlexander Graf static BlockDriver bdrv_ftp = {
1009769ce76dSAlexander Graf     .format_name                = "ftp",
1010769ce76dSAlexander Graf     .protocol_name              = "ftp",
1011769ce76dSAlexander Graf 
1012769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
10138e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
101466f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
1015769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
1016769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
1017769ce76dSAlexander Graf 
101828256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
101963f0f45fSStefan Hajnoczi 
102063f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
102163f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
10222654267cSMax Reitz 
1023937c007bSMax Reitz     .bdrv_refresh_filename      = curl_refresh_filename,
10242654267cSMax Reitz     .strong_runtime_opts        = curl_strong_runtime_opts,
1025769ce76dSAlexander Graf };
1026769ce76dSAlexander Graf 
1027769ce76dSAlexander Graf static BlockDriver bdrv_ftps = {
1028769ce76dSAlexander Graf     .format_name                = "ftps",
1029769ce76dSAlexander Graf     .protocol_name              = "ftps",
1030769ce76dSAlexander Graf 
1031769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
10328e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
103366f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
1034769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
1035769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
1036769ce76dSAlexander Graf 
103728256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
103863f0f45fSStefan Hajnoczi 
103963f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
104063f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
10412654267cSMax Reitz 
1042937c007bSMax Reitz     .bdrv_refresh_filename      = curl_refresh_filename,
10432654267cSMax Reitz     .strong_runtime_opts        = curl_strong_runtime_opts,
1044769ce76dSAlexander Graf };
1045769ce76dSAlexander Graf 
1046769ce76dSAlexander Graf static void curl_block_init(void)
1047769ce76dSAlexander Graf {
1048769ce76dSAlexander Graf     bdrv_register(&bdrv_http);
1049769ce76dSAlexander Graf     bdrv_register(&bdrv_https);
1050769ce76dSAlexander Graf     bdrv_register(&bdrv_ftp);
1051769ce76dSAlexander Graf     bdrv_register(&bdrv_ftps);
1052769ce76dSAlexander Graf }
1053769ce76dSAlexander Graf 
1054769ce76dSAlexander Graf block_init(curl_block_init);
1055