xref: /openbmc/qemu/block/curl.c (revision ed2a66de)
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"
28922a01a0SMarkus Armbruster #include "qemu/option.h"
29737e150eSPaolo Bonzini #include "block/block_int.h"
30452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
31d49b6836SMarkus Armbruster #include "qapi/qmp/qstring.h"
321bff9606SDaniel P. Berrange #include "crypto/secret.h"
33769ce76dSAlexander Graf #include <curl/curl.h>
34f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
35*ed2a66deSLaurent Vivier #include "trace.h"
36769ce76dSAlexander Graf 
37769ce76dSAlexander Graf // #define DEBUG_VERBOSE
38769ce76dSAlexander Graf 
39031fd1beSPeter Maydell #if LIBCURL_VERSION_NUM >= 0x071000
40031fd1beSPeter Maydell /* The multi interface timer callback was introduced in 7.16.0 */
41031fd1beSPeter Maydell #define NEED_CURL_TIMER_CALLBACK
429aedd5a5SMatthew Booth #define HAVE_SOCKET_ACTION
439aedd5a5SMatthew Booth #endif
449aedd5a5SMatthew Booth 
459aedd5a5SMatthew Booth #ifndef HAVE_SOCKET_ACTION
469aedd5a5SMatthew Booth /* If curl_multi_socket_action isn't available, define it statically here in
479aedd5a5SMatthew Booth  * terms of curl_multi_socket. Note that ev_bitmask will be ignored, which is
489aedd5a5SMatthew Booth  * less efficient but still safe. */
499aedd5a5SMatthew Booth static CURLMcode __curl_multi_socket_action(CURLM *multi_handle,
509aedd5a5SMatthew Booth                                             curl_socket_t sockfd,
519aedd5a5SMatthew Booth                                             int ev_bitmask,
529aedd5a5SMatthew Booth                                             int *running_handles)
539aedd5a5SMatthew Booth {
549aedd5a5SMatthew Booth     return curl_multi_socket(multi_handle, sockfd, running_handles);
559aedd5a5SMatthew Booth }
569aedd5a5SMatthew Booth #define curl_multi_socket_action __curl_multi_socket_action
57031fd1beSPeter Maydell #endif
58031fd1beSPeter Maydell 
59fb6d1bbdSStefan Hajnoczi #define PROTOCOLS (CURLPROTO_HTTP | CURLPROTO_HTTPS | \
6023dce387SMax Reitz                    CURLPROTO_FTP | CURLPROTO_FTPS)
61fb6d1bbdSStefan Hajnoczi 
62769ce76dSAlexander Graf #define CURL_NUM_STATES 8
63769ce76dSAlexander Graf #define CURL_NUM_ACB    8
64e3542c67SMatthew Booth #define READ_AHEAD_DEFAULT (256 * 1024)
65212aefaaSDaniel Henrique Barboza #define CURL_TIMEOUT_DEFAULT 5
66f76faedaSRichard W.M. Jones #define CURL_TIMEOUT_MAX 10000
67769ce76dSAlexander Graf 
68e3542c67SMatthew Booth #define CURL_BLOCK_OPT_URL       "url"
69e3542c67SMatthew Booth #define CURL_BLOCK_OPT_READAHEAD "readahead"
7097a3ea57SMatthew Booth #define CURL_BLOCK_OPT_SSLVERIFY "sslverify"
71212aefaaSDaniel Henrique Barboza #define CURL_BLOCK_OPT_TIMEOUT "timeout"
72a94f83d9SRichard W.M. Jones #define CURL_BLOCK_OPT_COOKIE    "cookie"
73327c8ebdSPeter Krempa #define CURL_BLOCK_OPT_COOKIE_SECRET "cookie-secret"
741bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_USERNAME "username"
751bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PASSWORD_SECRET "password-secret"
761bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PROXY_USERNAME "proxy-username"
771bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET "proxy-password-secret"
78e3542c67SMatthew Booth 
79769ce76dSAlexander Graf struct BDRVCURLState;
80769ce76dSAlexander Graf 
812d25964dSJeff Cody static bool libcurl_initialized;
822d25964dSJeff Cody 
83769ce76dSAlexander Graf typedef struct CURLAIOCB {
8428256d82SPaolo Bonzini     Coroutine *co;
85769ce76dSAlexander Graf     QEMUIOVector *qiov;
86363c3c85SNick Thomas 
872125e5eaSPaolo Bonzini     uint64_t offset;
882125e5eaSPaolo Bonzini     uint64_t bytes;
8928256d82SPaolo Bonzini     int ret;
90363c3c85SNick Thomas 
91769ce76dSAlexander Graf     size_t start;
92769ce76dSAlexander Graf     size_t end;
93769ce76dSAlexander Graf } CURLAIOCB;
94769ce76dSAlexander Graf 
95ff5ca166SMax Reitz typedef struct CURLSocket {
96ff5ca166SMax Reitz     int fd;
97ff5ca166SMax Reitz     QLIST_ENTRY(CURLSocket) next;
98ff5ca166SMax Reitz } CURLSocket;
99ff5ca166SMax Reitz 
100769ce76dSAlexander Graf typedef struct CURLState
101769ce76dSAlexander Graf {
102769ce76dSAlexander Graf     struct BDRVCURLState *s;
103769ce76dSAlexander Graf     CURLAIOCB *acb[CURL_NUM_ACB];
104769ce76dSAlexander Graf     CURL *curl;
105ff5ca166SMax Reitz     QLIST_HEAD(, CURLSocket) sockets;
106769ce76dSAlexander Graf     char *orig_buf;
1072125e5eaSPaolo Bonzini     uint64_t buf_start;
108769ce76dSAlexander Graf     size_t buf_off;
109769ce76dSAlexander Graf     size_t buf_len;
110769ce76dSAlexander Graf     char range[128];
111769ce76dSAlexander Graf     char errmsg[CURL_ERROR_SIZE];
112769ce76dSAlexander Graf     char in_use;
113769ce76dSAlexander Graf } CURLState;
114769ce76dSAlexander Graf 
115769ce76dSAlexander Graf typedef struct BDRVCURLState {
116769ce76dSAlexander Graf     CURLM *multi;
117031fd1beSPeter Maydell     QEMUTimer timer;
1182125e5eaSPaolo Bonzini     uint64_t len;
119769ce76dSAlexander Graf     CURLState states[CURL_NUM_STATES];
120769ce76dSAlexander Graf     char *url;
121c76f4952SNolan     size_t readahead_size;
12297a3ea57SMatthew Booth     bool sslverify;
123f76faedaSRichard W.M. Jones     uint64_t timeout;
124a94f83d9SRichard W.M. Jones     char *cookie;
1253494d650SFam Zheng     bool accept_range;
12663f0f45fSStefan Hajnoczi     AioContext *aio_context;
127ba3186c4SPaolo Bonzini     QemuMutex mutex;
128709f2132SPaolo Bonzini     CoQueue free_state_waitq;
1291bff9606SDaniel P. Berrange     char *username;
1301bff9606SDaniel P. Berrange     char *password;
1311bff9606SDaniel P. Berrange     char *proxyusername;
1321bff9606SDaniel P. Berrange     char *proxypassword;
133769ce76dSAlexander Graf } BDRVCURLState;
134769ce76dSAlexander Graf 
135769ce76dSAlexander Graf static void curl_clean_state(CURLState *s);
136769ce76dSAlexander Graf static void curl_multi_do(void *arg);
137838ef602SMatthew Booth static void curl_multi_read(void *arg);
138769ce76dSAlexander Graf 
139031fd1beSPeter Maydell #ifdef NEED_CURL_TIMER_CALLBACK
14034db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
141031fd1beSPeter Maydell static int curl_timer_cb(CURLM *multi, long timeout_ms, void *opaque)
142031fd1beSPeter Maydell {
143031fd1beSPeter Maydell     BDRVCURLState *s = opaque;
144031fd1beSPeter Maydell 
145*ed2a66deSLaurent Vivier     trace_curl_timer_cb(timeout_ms);
146031fd1beSPeter Maydell     if (timeout_ms == -1) {
147031fd1beSPeter Maydell         timer_del(&s->timer);
148031fd1beSPeter Maydell     } else {
149031fd1beSPeter Maydell         int64_t timeout_ns = (int64_t)timeout_ms * 1000 * 1000;
150031fd1beSPeter Maydell         timer_mod(&s->timer,
151031fd1beSPeter Maydell                   qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ns);
152031fd1beSPeter Maydell     }
153031fd1beSPeter Maydell     return 0;
154031fd1beSPeter Maydell }
155031fd1beSPeter Maydell #endif
156031fd1beSPeter Maydell 
15734db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
158769ce76dSAlexander Graf static int curl_sock_cb(CURL *curl, curl_socket_t fd, int action,
15963f0f45fSStefan Hajnoczi                         void *userp, void *sp)
160769ce76dSAlexander Graf {
16163f0f45fSStefan Hajnoczi     BDRVCURLState *s;
162838ef602SMatthew Booth     CURLState *state = NULL;
163ff5ca166SMax Reitz     CURLSocket *socket;
164ff5ca166SMax Reitz 
165838ef602SMatthew Booth     curl_easy_getinfo(curl, CURLINFO_PRIVATE, (char **)&state);
16663f0f45fSStefan Hajnoczi     s = state->s;
167838ef602SMatthew Booth 
168ff5ca166SMax Reitz     QLIST_FOREACH(socket, &state->sockets, next) {
169ff5ca166SMax Reitz         if (socket->fd == fd) {
170ff5ca166SMax Reitz             if (action == CURL_POLL_REMOVE) {
171ff5ca166SMax Reitz                 QLIST_REMOVE(socket, next);
172ff5ca166SMax Reitz                 g_free(socket);
173ff5ca166SMax Reitz             }
174ff5ca166SMax Reitz             break;
175ff5ca166SMax Reitz         }
176ff5ca166SMax Reitz     }
177ff5ca166SMax Reitz     if (!socket) {
178ff5ca166SMax Reitz         socket = g_new0(CURLSocket, 1);
179ff5ca166SMax Reitz         socket->fd = fd;
180ff5ca166SMax Reitz         QLIST_INSERT_HEAD(&state->sockets, socket, next);
181ff5ca166SMax Reitz     }
182ff5ca166SMax Reitz     socket = NULL;
183ff5ca166SMax Reitz 
184*ed2a66deSLaurent Vivier     trace_curl_sock_cb(action, (int)fd);
185769ce76dSAlexander Graf     switch (action) {
186769ce76dSAlexander Graf         case CURL_POLL_IN:
187dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
188f6a51c84SStefan Hajnoczi                                curl_multi_read, NULL, NULL, state);
189769ce76dSAlexander Graf             break;
190769ce76dSAlexander Graf         case CURL_POLL_OUT:
191dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
192f6a51c84SStefan Hajnoczi                                NULL, curl_multi_do, NULL, state);
193769ce76dSAlexander Graf             break;
194769ce76dSAlexander Graf         case CURL_POLL_INOUT:
195dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
196f6a51c84SStefan Hajnoczi                                curl_multi_read, curl_multi_do, NULL, state);
197769ce76dSAlexander Graf             break;
198769ce76dSAlexander Graf         case CURL_POLL_REMOVE:
199dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
200f6a51c84SStefan Hajnoczi                                NULL, NULL, NULL, NULL);
201769ce76dSAlexander Graf             break;
202769ce76dSAlexander Graf     }
203769ce76dSAlexander Graf 
204769ce76dSAlexander Graf     return 0;
205769ce76dSAlexander Graf }
206769ce76dSAlexander Graf 
20734db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
2083494d650SFam Zheng static size_t curl_header_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
209769ce76dSAlexander Graf {
2103494d650SFam Zheng     BDRVCURLState *s = opaque;
211769ce76dSAlexander Graf     size_t realsize = size * nmemb;
2123494d650SFam Zheng     const char *accept_line = "Accept-Ranges: bytes";
213769ce76dSAlexander Graf 
2143494d650SFam Zheng     if (realsize >= strlen(accept_line)
2153494d650SFam Zheng         && strncmp((char *)ptr, accept_line, strlen(accept_line)) == 0) {
2163494d650SFam Zheng         s->accept_range = true;
2170bfcd599SBlue Swirl     }
218769ce76dSAlexander Graf 
219769ce76dSAlexander Graf     return realsize;
220769ce76dSAlexander Graf }
221769ce76dSAlexander Graf 
22234db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
223769ce76dSAlexander Graf static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
224769ce76dSAlexander Graf {
225769ce76dSAlexander Graf     CURLState *s = ((CURLState*)opaque);
226769ce76dSAlexander Graf     size_t realsize = size * nmemb;
227769ce76dSAlexander Graf     int i;
228769ce76dSAlexander Graf 
229*ed2a66deSLaurent Vivier     trace_curl_read_cb(realsize);
230769ce76dSAlexander Graf 
2314e767657SMax Reitz     if (!s || !s->orig_buf) {
2324e767657SMax Reitz         goto read_end;
2334e767657SMax Reitz     }
234769ce76dSAlexander Graf 
2356d4b9e55SFam Zheng     if (s->buf_off >= s->buf_len) {
2366d4b9e55SFam Zheng         /* buffer full, read nothing */
2374e767657SMax Reitz         goto read_end;
2386d4b9e55SFam Zheng     }
2396d4b9e55SFam Zheng     realsize = MIN(realsize, s->buf_len - s->buf_off);
240769ce76dSAlexander Graf     memcpy(s->orig_buf + s->buf_off, ptr, realsize);
241769ce76dSAlexander Graf     s->buf_off += realsize;
242769ce76dSAlexander Graf 
243769ce76dSAlexander Graf     for(i=0; i<CURL_NUM_ACB; i++) {
244769ce76dSAlexander Graf         CURLAIOCB *acb = s->acb[i];
245769ce76dSAlexander Graf 
246769ce76dSAlexander Graf         if (!acb)
247769ce76dSAlexander Graf             continue;
248769ce76dSAlexander Graf 
249769ce76dSAlexander Graf         if ((s->buf_off >= acb->end)) {
2502125e5eaSPaolo Bonzini             size_t request_length = acb->bytes;
2514e504535SMax Reitz 
25203396148SMichael Tokarev             qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,
253769ce76dSAlexander Graf                                 acb->end - acb->start);
2544e504535SMax Reitz 
2554e504535SMax Reitz             if (acb->end - acb->start < request_length) {
2564e504535SMax Reitz                 size_t offset = acb->end - acb->start;
2574e504535SMax Reitz                 qemu_iovec_memset(acb->qiov, offset, 0,
2584e504535SMax Reitz                                   request_length - offset);
2594e504535SMax Reitz             }
2604e504535SMax Reitz 
26128256d82SPaolo Bonzini             acb->ret = 0;
262769ce76dSAlexander Graf             s->acb[i] = NULL;
26328256d82SPaolo Bonzini             qemu_mutex_unlock(&s->s->mutex);
26428256d82SPaolo Bonzini             aio_co_wake(acb->co);
26528256d82SPaolo Bonzini             qemu_mutex_lock(&s->s->mutex);
266769ce76dSAlexander Graf         }
267769ce76dSAlexander Graf     }
268769ce76dSAlexander Graf 
2694e767657SMax Reitz read_end:
2704e767657SMax Reitz     /* curl will error out if we do not return this value */
2714e767657SMax Reitz     return size * nmemb;
272769ce76dSAlexander Graf }
273769ce76dSAlexander Graf 
274456af346SPaolo Bonzini /* Called with s->mutex held.  */
27528256d82SPaolo Bonzini static bool curl_find_buf(BDRVCURLState *s, uint64_t start, uint64_t len,
276769ce76dSAlexander Graf                           CURLAIOCB *acb)
277769ce76dSAlexander Graf {
278769ce76dSAlexander Graf     int i;
2792125e5eaSPaolo Bonzini     uint64_t end = start + len;
2802125e5eaSPaolo Bonzini     uint64_t clamped_end = MIN(end, s->len);
2812125e5eaSPaolo Bonzini     uint64_t clamped_len = clamped_end - start;
282769ce76dSAlexander Graf 
283769ce76dSAlexander Graf     for (i=0; i<CURL_NUM_STATES; i++) {
284769ce76dSAlexander Graf         CURLState *state = &s->states[i];
2852125e5eaSPaolo Bonzini         uint64_t buf_end = (state->buf_start + state->buf_off);
2862125e5eaSPaolo Bonzini         uint64_t buf_fend = (state->buf_start + state->buf_len);
287769ce76dSAlexander Graf 
288769ce76dSAlexander Graf         if (!state->orig_buf)
289769ce76dSAlexander Graf             continue;
290769ce76dSAlexander Graf         if (!state->buf_off)
291769ce76dSAlexander Graf             continue;
292769ce76dSAlexander Graf 
293769ce76dSAlexander Graf         // Does the existing buffer cover our section?
294769ce76dSAlexander Graf         if ((start >= state->buf_start) &&
295769ce76dSAlexander Graf             (start <= buf_end) &&
2964e504535SMax Reitz             (clamped_end >= state->buf_start) &&
2974e504535SMax Reitz             (clamped_end <= buf_end))
298769ce76dSAlexander Graf         {
299769ce76dSAlexander Graf             char *buf = state->orig_buf + (start - state->buf_start);
300769ce76dSAlexander Graf 
3014e504535SMax Reitz             qemu_iovec_from_buf(acb->qiov, 0, buf, clamped_len);
3024e504535SMax Reitz             if (clamped_len < len) {
3034e504535SMax Reitz                 qemu_iovec_memset(acb->qiov, clamped_len, 0, len - clamped_len);
3044e504535SMax Reitz             }
30528256d82SPaolo Bonzini             acb->ret = 0;
30628256d82SPaolo Bonzini             return true;
307769ce76dSAlexander Graf         }
308769ce76dSAlexander Graf 
309769ce76dSAlexander Graf         // Wait for unfinished chunks
310b7079df4SMatthew Booth         if (state->in_use &&
311b7079df4SMatthew Booth             (start >= state->buf_start) &&
312769ce76dSAlexander Graf             (start <= buf_fend) &&
3134e504535SMax Reitz             (clamped_end >= state->buf_start) &&
3144e504535SMax Reitz             (clamped_end <= buf_fend))
315769ce76dSAlexander Graf         {
316769ce76dSAlexander Graf             int j;
317769ce76dSAlexander Graf 
318769ce76dSAlexander Graf             acb->start = start - state->buf_start;
3194e504535SMax Reitz             acb->end = acb->start + clamped_len;
320769ce76dSAlexander Graf 
321769ce76dSAlexander Graf             for (j=0; j<CURL_NUM_ACB; j++) {
322769ce76dSAlexander Graf                 if (!state->acb[j]) {
323769ce76dSAlexander Graf                     state->acb[j] = acb;
32428256d82SPaolo Bonzini                     return true;
325769ce76dSAlexander Graf                 }
326769ce76dSAlexander Graf             }
327769ce76dSAlexander Graf         }
328769ce76dSAlexander Graf     }
329769ce76dSAlexander Graf 
33028256d82SPaolo Bonzini     return false;
331769ce76dSAlexander Graf }
332769ce76dSAlexander Graf 
333ba3186c4SPaolo Bonzini /* Called with s->mutex held.  */
334838ef602SMatthew Booth static void curl_multi_check_completion(BDRVCURLState *s)
335769ce76dSAlexander Graf {
336769ce76dSAlexander Graf     int msgs_in_queue;
337769ce76dSAlexander Graf 
338769ce76dSAlexander Graf     /* Try to find done transfers, so we can free the easy
339769ce76dSAlexander Graf      * handle again. */
3401f2cead3SMatthew Booth     for (;;) {
341769ce76dSAlexander Graf         CURLMsg *msg;
342769ce76dSAlexander Graf         msg = curl_multi_info_read(s->multi, &msgs_in_queue);
343769ce76dSAlexander Graf 
3441f2cead3SMatthew Booth         /* Quit when there are no more completions */
345769ce76dSAlexander Graf         if (!msg)
346769ce76dSAlexander Graf             break;
347769ce76dSAlexander Graf 
3481f2cead3SMatthew Booth         if (msg->msg == CURLMSG_DONE) {
349769ce76dSAlexander Graf             CURLState *state = NULL;
350f6246509SMatthew Booth             curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,
351f6246509SMatthew Booth                               (char **)&state);
352f785a5aeSNicholas Thomas 
353f785a5aeSNicholas Thomas             /* ACBs for successful messages get completed in curl_read_cb */
354f785a5aeSNicholas Thomas             if (msg->data.result != CURLE_OK) {
355f785a5aeSNicholas Thomas                 int i;
356796a060bSRichard W.M. Jones                 static int errcount = 100;
357796a060bSRichard W.M. Jones 
358796a060bSRichard W.M. Jones                 /* Don't lose the original error message from curl, since
359796a060bSRichard W.M. Jones                  * it contains extra data.
360796a060bSRichard W.M. Jones                  */
361796a060bSRichard W.M. Jones                 if (errcount > 0) {
362796a060bSRichard W.M. Jones                     error_report("curl: %s", state->errmsg);
363796a060bSRichard W.M. Jones                     if (--errcount == 0) {
364796a060bSRichard W.M. Jones                         error_report("curl: further errors suppressed");
365796a060bSRichard W.M. Jones                     }
366796a060bSRichard W.M. Jones                 }
367796a060bSRichard W.M. Jones 
368f785a5aeSNicholas Thomas                 for (i = 0; i < CURL_NUM_ACB; i++) {
369f785a5aeSNicholas Thomas                     CURLAIOCB *acb = state->acb[i];
370f785a5aeSNicholas Thomas 
371f785a5aeSNicholas Thomas                     if (acb == NULL) {
372f785a5aeSNicholas Thomas                         continue;
373f785a5aeSNicholas Thomas                     }
374f785a5aeSNicholas Thomas 
37528256d82SPaolo Bonzini                     acb->ret = -EIO;
376f785a5aeSNicholas Thomas                     state->acb[i] = NULL;
37728256d82SPaolo Bonzini                     qemu_mutex_unlock(&s->mutex);
37828256d82SPaolo Bonzini                     aio_co_wake(acb->co);
37928256d82SPaolo Bonzini                     qemu_mutex_lock(&s->mutex);
380f785a5aeSNicholas Thomas                 }
381f785a5aeSNicholas Thomas             }
382f785a5aeSNicholas Thomas 
383769ce76dSAlexander Graf             curl_clean_state(state);
384769ce76dSAlexander Graf             break;
385769ce76dSAlexander Graf         }
386769ce76dSAlexander Graf     }
387769ce76dSAlexander Graf }
388769ce76dSAlexander Graf 
389ba3186c4SPaolo Bonzini /* Called with s->mutex held.  */
3909d456654SPaolo Bonzini static void curl_multi_do_locked(CURLState *s)
391031fd1beSPeter Maydell {
392ff5ca166SMax Reitz     CURLSocket *socket, *next_socket;
393031fd1beSPeter Maydell     int running;
394031fd1beSPeter Maydell     int r;
395031fd1beSPeter Maydell 
396838ef602SMatthew Booth     if (!s->s->multi) {
397031fd1beSPeter Maydell         return;
398031fd1beSPeter Maydell     }
399031fd1beSPeter Maydell 
400ff5ca166SMax Reitz     /* Need to use _SAFE because curl_multi_socket_action() may trigger
401ff5ca166SMax Reitz      * curl_sock_cb() which might modify this list */
402ff5ca166SMax Reitz     QLIST_FOREACH_SAFE(socket, &s->sockets, next, next_socket) {
403031fd1beSPeter Maydell         do {
404ff5ca166SMax Reitz             r = curl_multi_socket_action(s->s->multi, socket->fd, 0, &running);
405031fd1beSPeter Maydell         } while (r == CURLM_CALL_MULTI_PERFORM);
406ff5ca166SMax Reitz     }
407838ef602SMatthew Booth }
408838ef602SMatthew Booth 
4099d456654SPaolo Bonzini static void curl_multi_do(void *arg)
4109d456654SPaolo Bonzini {
4119d456654SPaolo Bonzini     CURLState *s = (CURLState *)arg;
4129d456654SPaolo Bonzini 
413ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->s->mutex);
4149d456654SPaolo Bonzini     curl_multi_do_locked(s);
415ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->s->mutex);
4169d456654SPaolo Bonzini }
4179d456654SPaolo Bonzini 
418838ef602SMatthew Booth static void curl_multi_read(void *arg)
419838ef602SMatthew Booth {
420838ef602SMatthew Booth     CURLState *s = (CURLState *)arg;
421838ef602SMatthew Booth 
422ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->s->mutex);
4239d456654SPaolo Bonzini     curl_multi_do_locked(s);
424838ef602SMatthew Booth     curl_multi_check_completion(s->s);
425ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->s->mutex);
426031fd1beSPeter Maydell }
427031fd1beSPeter Maydell 
428031fd1beSPeter Maydell static void curl_multi_timeout_do(void *arg)
429031fd1beSPeter Maydell {
430031fd1beSPeter Maydell #ifdef NEED_CURL_TIMER_CALLBACK
431031fd1beSPeter Maydell     BDRVCURLState *s = (BDRVCURLState *)arg;
432031fd1beSPeter Maydell     int running;
433031fd1beSPeter Maydell 
434031fd1beSPeter Maydell     if (!s->multi) {
435031fd1beSPeter Maydell         return;
436031fd1beSPeter Maydell     }
437031fd1beSPeter Maydell 
438ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
439031fd1beSPeter Maydell     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
440031fd1beSPeter Maydell 
441838ef602SMatthew Booth     curl_multi_check_completion(s);
442ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
443031fd1beSPeter Maydell #else
444031fd1beSPeter Maydell     abort();
445031fd1beSPeter Maydell #endif
446031fd1beSPeter Maydell }
447031fd1beSPeter Maydell 
448456af346SPaolo Bonzini /* Called with s->mutex held.  */
4493ce6a729SPaolo Bonzini static CURLState *curl_find_state(BDRVCURLState *s)
450769ce76dSAlexander Graf {
451769ce76dSAlexander Graf     CURLState *state = NULL;
4523ce6a729SPaolo Bonzini     int i;
453769ce76dSAlexander Graf 
454769ce76dSAlexander Graf     for (i = 0; i < CURL_NUM_STATES; i++) {
4553ce6a729SPaolo Bonzini         if (!s->states[i].in_use) {
456769ce76dSAlexander Graf             state = &s->states[i];
457769ce76dSAlexander Graf             state->in_use = 1;
458769ce76dSAlexander Graf             break;
459769ce76dSAlexander Graf         }
460769ce76dSAlexander Graf     }
4613ce6a729SPaolo Bonzini     return state;
4623ce6a729SPaolo Bonzini }
463769ce76dSAlexander Graf 
4643ce6a729SPaolo Bonzini static int curl_init_state(BDRVCURLState *s, CURLState *state)
4653ce6a729SPaolo Bonzini {
4669e550b32SMatthew Booth     if (!state->curl) {
467769ce76dSAlexander Graf         state->curl = curl_easy_init();
4689e550b32SMatthew Booth         if (!state->curl) {
4693ce6a729SPaolo Bonzini             return -EIO;
4709e550b32SMatthew Booth         }
471769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
47297a3ea57SMatthew Booth         curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,
47397a3ea57SMatthew Booth                          (long) s->sslverify);
474637fa44aSRichard W.M. Jones         curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYHOST,
475637fa44aSRichard W.M. Jones                          s->sslverify ? 2L : 0L);
476a94f83d9SRichard W.M. Jones         if (s->cookie) {
477a94f83d9SRichard W.M. Jones             curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);
478a94f83d9SRichard W.M. Jones         }
479f76faedaSRichard W.M. Jones         curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);
4809e550b32SMatthew Booth         curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,
4819e550b32SMatthew Booth                          (void *)curl_read_cb);
482769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
483769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
484769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
485769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
486769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
487769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
488f785a5aeSNicholas Thomas         curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
489769ce76dSAlexander Graf 
4901bff9606SDaniel P. Berrange         if (s->username) {
4911bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);
4921bff9606SDaniel P. Berrange         }
4931bff9606SDaniel P. Berrange         if (s->password) {
4941bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);
4951bff9606SDaniel P. Berrange         }
4961bff9606SDaniel P. Berrange         if (s->proxyusername) {
4971bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl,
4981bff9606SDaniel P. Berrange                              CURLOPT_PROXYUSERNAME, s->proxyusername);
4991bff9606SDaniel P. Berrange         }
5001bff9606SDaniel P. Berrange         if (s->proxypassword) {
5011bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl,
5021bff9606SDaniel P. Berrange                              CURLOPT_PROXYPASSWORD, s->proxypassword);
5031bff9606SDaniel P. Berrange         }
5041bff9606SDaniel P. Berrange 
505fb6d1bbdSStefan Hajnoczi         /* Restrict supported protocols to avoid security issues in the more
506fb6d1bbdSStefan Hajnoczi          * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see
507fb6d1bbdSStefan Hajnoczi          * CVE-2013-0249.
5088a8f5840SStefan Hajnoczi          *
5098a8f5840SStefan Hajnoczi          * Restricting protocols is only supported from 7.19.4 upwards.
510fb6d1bbdSStefan Hajnoczi          */
5118a8f5840SStefan Hajnoczi #if LIBCURL_VERSION_NUM >= 0x071304
512fb6d1bbdSStefan Hajnoczi         curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
513fb6d1bbdSStefan Hajnoczi         curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
5148a8f5840SStefan Hajnoczi #endif
515fb6d1bbdSStefan Hajnoczi 
516769ce76dSAlexander Graf #ifdef DEBUG_VERBOSE
517769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
518769ce76dSAlexander Graf #endif
5199e550b32SMatthew Booth     }
520769ce76dSAlexander Graf 
521ff5ca166SMax Reitz     QLIST_INIT(&state->sockets);
522769ce76dSAlexander Graf     state->s = s;
523769ce76dSAlexander Graf 
5243ce6a729SPaolo Bonzini     return 0;
525769ce76dSAlexander Graf }
526769ce76dSAlexander Graf 
527456af346SPaolo Bonzini /* Called with s->mutex held.  */
528769ce76dSAlexander Graf static void curl_clean_state(CURLState *s)
529769ce76dSAlexander Graf {
530675a7756SPaolo Bonzini     int j;
531675a7756SPaolo Bonzini     for (j = 0; j < CURL_NUM_ACB; j++) {
532675a7756SPaolo Bonzini         assert(!s->acb[j]);
533675a7756SPaolo Bonzini     }
534675a7756SPaolo Bonzini 
535769ce76dSAlexander Graf     if (s->s->multi)
536769ce76dSAlexander Graf         curl_multi_remove_handle(s->s->multi, s->curl);
537ff5ca166SMax Reitz 
538ff5ca166SMax Reitz     while (!QLIST_EMPTY(&s->sockets)) {
539ff5ca166SMax Reitz         CURLSocket *socket = QLIST_FIRST(&s->sockets);
540ff5ca166SMax Reitz 
541ff5ca166SMax Reitz         QLIST_REMOVE(socket, next);
542ff5ca166SMax Reitz         g_free(socket);
543ff5ca166SMax Reitz     }
544ff5ca166SMax Reitz 
545769ce76dSAlexander Graf     s->in_use = 0;
5462bb5c936SPaolo Bonzini 
547709f2132SPaolo Bonzini     qemu_co_enter_next(&s->s->free_state_waitq, &s->s->mutex);
548769ce76dSAlexander Graf }
549769ce76dSAlexander Graf 
5508e6d58cdSKevin Wolf static void curl_parse_filename(const char *filename, QDict *options,
5518e6d58cdSKevin Wolf                                 Error **errp)
552769ce76dSAlexander Graf {
55346f5ac20SEric Blake     qdict_put_str(options, CURL_BLOCK_OPT_URL, filename);
5548e6d58cdSKevin Wolf }
5558e6d58cdSKevin Wolf 
55663f0f45fSStefan Hajnoczi static void curl_detach_aio_context(BlockDriverState *bs)
55763f0f45fSStefan Hajnoczi {
55863f0f45fSStefan Hajnoczi     BDRVCURLState *s = bs->opaque;
55963f0f45fSStefan Hajnoczi     int i;
56063f0f45fSStefan Hajnoczi 
561456af346SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
56263f0f45fSStefan Hajnoczi     for (i = 0; i < CURL_NUM_STATES; i++) {
56363f0f45fSStefan Hajnoczi         if (s->states[i].in_use) {
56463f0f45fSStefan Hajnoczi             curl_clean_state(&s->states[i]);
56563f0f45fSStefan Hajnoczi         }
56663f0f45fSStefan Hajnoczi         if (s->states[i].curl) {
56763f0f45fSStefan Hajnoczi             curl_easy_cleanup(s->states[i].curl);
56863f0f45fSStefan Hajnoczi             s->states[i].curl = NULL;
56963f0f45fSStefan Hajnoczi         }
57063f0f45fSStefan Hajnoczi         g_free(s->states[i].orig_buf);
57163f0f45fSStefan Hajnoczi         s->states[i].orig_buf = NULL;
57263f0f45fSStefan Hajnoczi     }
57363f0f45fSStefan Hajnoczi     if (s->multi) {
57463f0f45fSStefan Hajnoczi         curl_multi_cleanup(s->multi);
57563f0f45fSStefan Hajnoczi         s->multi = NULL;
57663f0f45fSStefan Hajnoczi     }
577456af346SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
57863f0f45fSStefan Hajnoczi 
57963f0f45fSStefan Hajnoczi     timer_del(&s->timer);
58063f0f45fSStefan Hajnoczi }
58163f0f45fSStefan Hajnoczi 
58263f0f45fSStefan Hajnoczi static void curl_attach_aio_context(BlockDriverState *bs,
58363f0f45fSStefan Hajnoczi                                     AioContext *new_context)
58463f0f45fSStefan Hajnoczi {
58563f0f45fSStefan Hajnoczi     BDRVCURLState *s = bs->opaque;
58663f0f45fSStefan Hajnoczi 
58763f0f45fSStefan Hajnoczi     aio_timer_init(new_context, &s->timer,
58863f0f45fSStefan Hajnoczi                    QEMU_CLOCK_REALTIME, SCALE_NS,
58963f0f45fSStefan Hajnoczi                    curl_multi_timeout_do, s);
59063f0f45fSStefan Hajnoczi 
59163f0f45fSStefan Hajnoczi     assert(!s->multi);
59263f0f45fSStefan Hajnoczi     s->multi = curl_multi_init();
59363f0f45fSStefan Hajnoczi     s->aio_context = new_context;
59463f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
59563f0f45fSStefan Hajnoczi #ifdef NEED_CURL_TIMER_CALLBACK
59663f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
59763f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
59863f0f45fSStefan Hajnoczi #endif
59963f0f45fSStefan Hajnoczi }
60063f0f45fSStefan Hajnoczi 
6018e6d58cdSKevin Wolf static QemuOptsList runtime_opts = {
6028e6d58cdSKevin Wolf     .name = "curl",
6038e6d58cdSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
6048e6d58cdSKevin Wolf     .desc = {
6058e6d58cdSKevin Wolf         {
606e3542c67SMatthew Booth             .name = CURL_BLOCK_OPT_URL,
6078e6d58cdSKevin Wolf             .type = QEMU_OPT_STRING,
6088e6d58cdSKevin Wolf             .help = "URL to open",
6098e6d58cdSKevin Wolf         },
6108e6d58cdSKevin Wolf         {
611e3542c67SMatthew Booth             .name = CURL_BLOCK_OPT_READAHEAD,
6128e6d58cdSKevin Wolf             .type = QEMU_OPT_SIZE,
6138e6d58cdSKevin Wolf             .help = "Readahead size",
6148e6d58cdSKevin Wolf         },
61597a3ea57SMatthew Booth         {
61697a3ea57SMatthew Booth             .name = CURL_BLOCK_OPT_SSLVERIFY,
61797a3ea57SMatthew Booth             .type = QEMU_OPT_BOOL,
61897a3ea57SMatthew Booth             .help = "Verify SSL certificate"
61997a3ea57SMatthew Booth         },
620212aefaaSDaniel Henrique Barboza         {
621212aefaaSDaniel Henrique Barboza             .name = CURL_BLOCK_OPT_TIMEOUT,
622212aefaaSDaniel Henrique Barboza             .type = QEMU_OPT_NUMBER,
623212aefaaSDaniel Henrique Barboza             .help = "Curl timeout"
624212aefaaSDaniel Henrique Barboza         },
625a94f83d9SRichard W.M. Jones         {
626a94f83d9SRichard W.M. Jones             .name = CURL_BLOCK_OPT_COOKIE,
627a94f83d9SRichard W.M. Jones             .type = QEMU_OPT_STRING,
628a94f83d9SRichard W.M. Jones             .help = "Pass the cookie or list of cookies with each request"
629a94f83d9SRichard W.M. Jones         },
6301bff9606SDaniel P. Berrange         {
631327c8ebdSPeter Krempa             .name = CURL_BLOCK_OPT_COOKIE_SECRET,
632327c8ebdSPeter Krempa             .type = QEMU_OPT_STRING,
633327c8ebdSPeter Krempa             .help = "ID of secret used as cookie passed with each request"
634327c8ebdSPeter Krempa         },
635327c8ebdSPeter Krempa         {
6361bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_USERNAME,
6371bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6381bff9606SDaniel P. Berrange             .help = "Username for HTTP auth"
6391bff9606SDaniel P. Berrange         },
6401bff9606SDaniel P. Berrange         {
6411bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PASSWORD_SECRET,
6421bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6431bff9606SDaniel P. Berrange             .help = "ID of secret used as password for HTTP auth",
6441bff9606SDaniel P. Berrange         },
6451bff9606SDaniel P. Berrange         {
6461bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PROXY_USERNAME,
6471bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6481bff9606SDaniel P. Berrange             .help = "Username for HTTP proxy auth"
6491bff9606SDaniel P. Berrange         },
6501bff9606SDaniel P. Berrange         {
6511bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
6521bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6531bff9606SDaniel P. Berrange             .help = "ID of secret used as password for HTTP proxy auth",
6541bff9606SDaniel P. Berrange         },
6558e6d58cdSKevin Wolf         { /* end of list */ }
6568e6d58cdSKevin Wolf     },
6578e6d58cdSKevin Wolf };
6588e6d58cdSKevin Wolf 
6591bff9606SDaniel P. Berrange 
660015a1036SMax Reitz static int curl_open(BlockDriverState *bs, QDict *options, int flags,
661015a1036SMax Reitz                      Error **errp)
6628e6d58cdSKevin Wolf {
6638e6d58cdSKevin Wolf     BDRVCURLState *s = bs->opaque;
6648e6d58cdSKevin Wolf     CURLState *state = NULL;
6658e6d58cdSKevin Wolf     QemuOpts *opts;
6668e6d58cdSKevin Wolf     Error *local_err = NULL;
6678e6d58cdSKevin Wolf     const char *file;
668a94f83d9SRichard W.M. Jones     const char *cookie;
669327c8ebdSPeter Krempa     const char *cookie_secret;
6708e6d58cdSKevin Wolf     double d;
6711bff9606SDaniel P. Berrange     const char *secretid;
67234634ca2SMax Reitz     const char *protocol_delimiter;
6732d25964dSJeff Cody     int ret;
6748e6d58cdSKevin Wolf 
6756ceef36aSKevin Wolf     ret = bdrv_apply_auto_read_only(bs, "curl driver does not support writes",
6766ceef36aSKevin Wolf                                     errp);
6776ceef36aSKevin Wolf     if (ret < 0) {
6786ceef36aSKevin Wolf         return ret;
679a7cea2baSRichard W.M. Jones     }
680a7cea2baSRichard W.M. Jones 
6812d25964dSJeff Cody     if (!libcurl_initialized) {
6822d25964dSJeff Cody         ret = curl_global_init(CURL_GLOBAL_ALL);
6832d25964dSJeff Cody         if (ret) {
6842d25964dSJeff Cody             error_setg(errp, "libcurl initialization failed with %d", ret);
6852d25964dSJeff Cody             return -EIO;
6862d25964dSJeff Cody         }
6872d25964dSJeff Cody         libcurl_initialized = true;
6882d25964dSJeff Cody     }
6892d25964dSJeff Cody 
690456af346SPaolo Bonzini     qemu_mutex_init(&s->mutex);
69187ea75d5SPeter Crosthwaite     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
6928e6d58cdSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
69384d18f06SMarkus Armbruster     if (local_err) {
6942a94fee3SPaolo Bonzini         error_propagate(errp, local_err);
6958e6d58cdSKevin Wolf         goto out_noclean;
6968e6d58cdSKevin Wolf     }
6978e6d58cdSKevin Wolf 
698e3542c67SMatthew Booth     s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
699e3542c67SMatthew Booth                                           READ_AHEAD_DEFAULT);
700c76f4952SNolan     if ((s->readahead_size & 0x1ff) != 0) {
7012a94fee3SPaolo Bonzini         error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
702c76f4952SNolan                    s->readahead_size);
703c76f4952SNolan         goto out_noclean;
704c76f4952SNolan     }
705c76f4952SNolan 
706212aefaaSDaniel Henrique Barboza     s->timeout = qemu_opt_get_number(opts, CURL_BLOCK_OPT_TIMEOUT,
707212aefaaSDaniel Henrique Barboza                                      CURL_TIMEOUT_DEFAULT);
708f76faedaSRichard W.M. Jones     if (s->timeout > CURL_TIMEOUT_MAX) {
709f76faedaSRichard W.M. Jones         error_setg(errp, "timeout parameter is too large or negative");
710f76faedaSRichard W.M. Jones         goto out_noclean;
711f76faedaSRichard W.M. Jones     }
712212aefaaSDaniel Henrique Barboza 
71397a3ea57SMatthew Booth     s->sslverify = qemu_opt_get_bool(opts, CURL_BLOCK_OPT_SSLVERIFY, true);
71497a3ea57SMatthew Booth 
715a94f83d9SRichard W.M. Jones     cookie = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE);
716327c8ebdSPeter Krempa     cookie_secret = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE_SECRET);
717327c8ebdSPeter Krempa 
718327c8ebdSPeter Krempa     if (cookie && cookie_secret) {
719327c8ebdSPeter Krempa         error_setg(errp,
720327c8ebdSPeter Krempa                    "curl driver cannot handle both cookie and cookie secret");
721327c8ebdSPeter Krempa         goto out_noclean;
722327c8ebdSPeter Krempa     }
723327c8ebdSPeter Krempa 
724327c8ebdSPeter Krempa     if (cookie_secret) {
725327c8ebdSPeter Krempa         s->cookie = qcrypto_secret_lookup_as_utf8(cookie_secret, errp);
726327c8ebdSPeter Krempa         if (!s->cookie) {
727327c8ebdSPeter Krempa             goto out_noclean;
728327c8ebdSPeter Krempa         }
729327c8ebdSPeter Krempa     } else {
730a94f83d9SRichard W.M. Jones         s->cookie = g_strdup(cookie);
731327c8ebdSPeter Krempa     }
732a94f83d9SRichard W.M. Jones 
733e3542c67SMatthew Booth     file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
7348e6d58cdSKevin Wolf     if (file == NULL) {
7352a94fee3SPaolo Bonzini         error_setg(errp, "curl block driver requires an 'url' option");
7368e6d58cdSKevin Wolf         goto out_noclean;
7378e6d58cdSKevin Wolf     }
7388e6d58cdSKevin Wolf 
73934634ca2SMax Reitz     if (!strstart(file, bs->drv->protocol_name, &protocol_delimiter) ||
74034634ca2SMax Reitz         !strstart(protocol_delimiter, "://", NULL))
74134634ca2SMax Reitz     {
74234634ca2SMax Reitz         error_setg(errp, "%s curl driver cannot handle the URL '%s' (does not "
74334634ca2SMax Reitz                    "start with '%s://')", bs->drv->protocol_name, file,
74434634ca2SMax Reitz                    bs->drv->protocol_name);
74534634ca2SMax Reitz         goto out_noclean;
74634634ca2SMax Reitz     }
74734634ca2SMax Reitz 
7481bff9606SDaniel P. Berrange     s->username = g_strdup(qemu_opt_get(opts, CURL_BLOCK_OPT_USERNAME));
7491bff9606SDaniel P. Berrange     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PASSWORD_SECRET);
7501bff9606SDaniel P. Berrange 
7511bff9606SDaniel P. Berrange     if (secretid) {
7521bff9606SDaniel P. Berrange         s->password = qcrypto_secret_lookup_as_utf8(secretid, errp);
7531bff9606SDaniel P. Berrange         if (!s->password) {
7541bff9606SDaniel P. Berrange             goto out_noclean;
7551bff9606SDaniel P. Berrange         }
7561bff9606SDaniel P. Berrange     }
7571bff9606SDaniel P. Berrange 
7581bff9606SDaniel P. Berrange     s->proxyusername = g_strdup(
7591bff9606SDaniel P. Berrange         qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_USERNAME));
7601bff9606SDaniel P. Berrange     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET);
7611bff9606SDaniel P. Berrange     if (secretid) {
7621bff9606SDaniel P. Berrange         s->proxypassword = qcrypto_secret_lookup_as_utf8(secretid, errp);
7631bff9606SDaniel P. Berrange         if (!s->proxypassword) {
7641bff9606SDaniel P. Berrange             goto out_noclean;
7651bff9606SDaniel P. Berrange         }
7661bff9606SDaniel P. Berrange     }
7671bff9606SDaniel P. Berrange 
768*ed2a66deSLaurent Vivier     trace_curl_open(file);
769709f2132SPaolo Bonzini     qemu_co_queue_init(&s->free_state_waitq);
77063f0f45fSStefan Hajnoczi     s->aio_context = bdrv_get_aio_context(bs);
7718e6d58cdSKevin Wolf     s->url = g_strdup(file);
772456af346SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
7733ce6a729SPaolo Bonzini     state = curl_find_state(s);
774456af346SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
7753ce6a729SPaolo Bonzini     if (!state) {
776769ce76dSAlexander Graf         goto out_noclean;
7773ce6a729SPaolo Bonzini     }
778769ce76dSAlexander Graf 
779769ce76dSAlexander Graf     // Get file size
780769ce76dSAlexander Graf 
7813ce6a729SPaolo Bonzini     if (curl_init_state(s, state) < 0) {
7823ce6a729SPaolo Bonzini         goto out;
7833ce6a729SPaolo Bonzini     }
7843ce6a729SPaolo Bonzini 
7853494d650SFam Zheng     s->accept_range = false;
786769ce76dSAlexander Graf     curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
7873494d650SFam Zheng     curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
7883494d650SFam Zheng                      curl_header_cb);
7893494d650SFam Zheng     curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
790769ce76dSAlexander Graf     if (curl_easy_perform(state->curl))
791769ce76dSAlexander Graf         goto out;
792a41c4578STomáš Golembiovský     if (curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) {
793769ce76dSAlexander Graf         goto out;
794a41c4578STomáš Golembiovský     }
795a41c4578STomáš Golembiovský     /* Prior CURL 7.19.4 return value of 0 could mean that the file size is not
796a41c4578STomáš Golembiovský      * know or the size is zero. From 7.19.4 CURL returns -1 if size is not
79750d6a8a3SStefan Weil      * known and zero if it is really zero-length file. */
798a41c4578STomáš Golembiovský #if LIBCURL_VERSION_NUM >= 0x071304
799a41c4578STomáš Golembiovský     if (d < 0) {
800a41c4578STomáš Golembiovský         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
801a41c4578STomáš Golembiovský                 "Server didn't report file size.");
802a41c4578STomáš Golembiovský         goto out;
803a41c4578STomáš Golembiovský     }
804a41c4578STomáš Golembiovský #else
805a41c4578STomáš Golembiovský     if (d <= 0) {
806a41c4578STomáš Golembiovský         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
807a41c4578STomáš Golembiovský                 "Unknown file size or zero-length file.");
808a41c4578STomáš Golembiovský         goto out;
809a41c4578STomáš Golembiovský     }
810a41c4578STomáš Golembiovský #endif
811a41c4578STomáš Golembiovský 
8122125e5eaSPaolo Bonzini     s->len = d;
813a41c4578STomáš Golembiovský 
8143494d650SFam Zheng     if ((!strncasecmp(s->url, "http://", strlen("http://"))
8153494d650SFam Zheng         || !strncasecmp(s->url, "https://", strlen("https://")))
8163494d650SFam Zheng         && !s->accept_range) {
8173494d650SFam Zheng         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
8183494d650SFam Zheng                 "Server does not support 'range' (byte ranges).");
8193494d650SFam Zheng         goto out;
8203494d650SFam Zheng     }
821*ed2a66deSLaurent Vivier     trace_curl_open_size(s->len);
822769ce76dSAlexander Graf 
823456af346SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
824769ce76dSAlexander Graf     curl_clean_state(state);
825456af346SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
826769ce76dSAlexander Graf     curl_easy_cleanup(state->curl);
827769ce76dSAlexander Graf     state->curl = NULL;
828769ce76dSAlexander Graf 
82963f0f45fSStefan Hajnoczi     curl_attach_aio_context(bs, bdrv_get_aio_context(bs));
830769ce76dSAlexander Graf 
8318e6d58cdSKevin Wolf     qemu_opts_del(opts);
832769ce76dSAlexander Graf     return 0;
833769ce76dSAlexander Graf 
834769ce76dSAlexander Graf out:
835acd7fdc6SMaria Kustova     error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
836769ce76dSAlexander Graf     curl_easy_cleanup(state->curl);
837769ce76dSAlexander Graf     state->curl = NULL;
838769ce76dSAlexander Graf out_noclean:
839456af346SPaolo Bonzini     qemu_mutex_destroy(&s->mutex);
840a94f83d9SRichard W.M. Jones     g_free(s->cookie);
8418e6d58cdSKevin Wolf     g_free(s->url);
842996922deSJeff Cody     g_free(s->username);
843996922deSJeff Cody     g_free(s->proxyusername);
844996922deSJeff Cody     g_free(s->proxypassword);
8458e6d58cdSKevin Wolf     qemu_opts_del(opts);
846769ce76dSAlexander Graf     return -EINVAL;
847769ce76dSAlexander Graf }
848769ce76dSAlexander Graf 
84928256d82SPaolo Bonzini static void curl_setup_preadv(BlockDriverState *bs, CURLAIOCB *acb)
850769ce76dSAlexander Graf {
851769ce76dSAlexander Graf     CURLState *state;
852b69cdef8SMatthew Booth     int running;
853769ce76dSAlexander Graf 
8541919631eSPaolo Bonzini     BDRVCURLState *s = bs->opaque;
855769ce76dSAlexander Graf 
8562125e5eaSPaolo Bonzini     uint64_t start = acb->offset;
8572125e5eaSPaolo Bonzini     uint64_t end;
858769ce76dSAlexander Graf 
859ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
8601919631eSPaolo Bonzini 
861769ce76dSAlexander Graf     // In case we have the requested data already (e.g. read-ahead),
862769ce76dSAlexander Graf     // we can just call the callback and be done.
86328256d82SPaolo Bonzini     if (curl_find_buf(s, start, acb->bytes, acb)) {
86434db05e7SPaolo Bonzini         goto out;
865769ce76dSAlexander Graf     }
866769ce76dSAlexander Graf 
867769ce76dSAlexander Graf     // No cache found, so let's start a new request
8683ce6a729SPaolo Bonzini     for (;;) {
8693ce6a729SPaolo Bonzini         state = curl_find_state(s);
8703ce6a729SPaolo Bonzini         if (state) {
8713ce6a729SPaolo Bonzini             break;
8723ce6a729SPaolo Bonzini         }
873709f2132SPaolo Bonzini         qemu_co_queue_wait(&s->free_state_waitq, &s->mutex);
8743ce6a729SPaolo Bonzini     }
8753ce6a729SPaolo Bonzini 
8763ce6a729SPaolo Bonzini     if (curl_init_state(s, state) < 0) {
8773ce6a729SPaolo Bonzini         curl_clean_state(state);
87828256d82SPaolo Bonzini         acb->ret = -EIO;
8791919631eSPaolo Bonzini         goto out;
880363c3c85SNick Thomas     }
881769ce76dSAlexander Graf 
882769ce76dSAlexander Graf     acb->start = 0;
8832125e5eaSPaolo Bonzini     acb->end = MIN(acb->bytes, s->len - start);
884769ce76dSAlexander Graf 
885769ce76dSAlexander Graf     state->buf_off = 0;
8867267c094SAnthony Liguori     g_free(state->orig_buf);
887769ce76dSAlexander Graf     state->buf_start = start;
8884e504535SMax Reitz     state->buf_len = MIN(acb->end + s->readahead_size, s->len - start);
8894e504535SMax Reitz     end = start + state->buf_len - 1;
8908dc7a772SKevin Wolf     state->orig_buf = g_try_malloc(state->buf_len);
8918dc7a772SKevin Wolf     if (state->buf_len && state->orig_buf == NULL) {
8928dc7a772SKevin Wolf         curl_clean_state(state);
89328256d82SPaolo Bonzini         acb->ret = -ENOMEM;
8941919631eSPaolo Bonzini         goto out;
8958dc7a772SKevin Wolf     }
896769ce76dSAlexander Graf     state->acb[0] = acb;
897769ce76dSAlexander Graf 
8982125e5eaSPaolo Bonzini     snprintf(state->range, 127, "%" PRIu64 "-%" PRIu64, start, end);
899*ed2a66deSLaurent Vivier     trace_curl_setup_preadv(acb->bytes, start, state->range);
900769ce76dSAlexander Graf     curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
901769ce76dSAlexander Graf 
902769ce76dSAlexander Graf     curl_multi_add_handle(s->multi, state->curl);
903769ce76dSAlexander Graf 
904b69cdef8SMatthew Booth     /* Tell curl it needs to kick things off */
905b69cdef8SMatthew Booth     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
9061919631eSPaolo Bonzini 
9071919631eSPaolo Bonzini out:
908ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
909363c3c85SNick Thomas }
910363c3c85SNick Thomas 
91128256d82SPaolo Bonzini static int coroutine_fn curl_co_preadv(BlockDriverState *bs,
91228256d82SPaolo Bonzini         uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
913363c3c85SNick Thomas {
91428256d82SPaolo Bonzini     CURLAIOCB acb = {
91528256d82SPaolo Bonzini         .co = qemu_coroutine_self(),
91628256d82SPaolo Bonzini         .ret = -EINPROGRESS,
91728256d82SPaolo Bonzini         .qiov = qiov,
91828256d82SPaolo Bonzini         .offset = offset,
91928256d82SPaolo Bonzini         .bytes = bytes
92028256d82SPaolo Bonzini     };
921363c3c85SNick Thomas 
92228256d82SPaolo Bonzini     curl_setup_preadv(bs, &acb);
92328256d82SPaolo Bonzini     while (acb.ret == -EINPROGRESS) {
92428256d82SPaolo Bonzini         qemu_coroutine_yield();
92528256d82SPaolo Bonzini     }
92628256d82SPaolo Bonzini     return acb.ret;
927769ce76dSAlexander Graf }
928769ce76dSAlexander Graf 
929769ce76dSAlexander Graf static void curl_close(BlockDriverState *bs)
930769ce76dSAlexander Graf {
931769ce76dSAlexander Graf     BDRVCURLState *s = bs->opaque;
932769ce76dSAlexander Graf 
933*ed2a66deSLaurent Vivier     trace_curl_close();
93463f0f45fSStefan Hajnoczi     curl_detach_aio_context(bs);
935ba3186c4SPaolo Bonzini     qemu_mutex_destroy(&s->mutex);
936031fd1beSPeter Maydell 
937a94f83d9SRichard W.M. Jones     g_free(s->cookie);
93845724d6dSStefan Weil     g_free(s->url);
939996922deSJeff Cody     g_free(s->username);
940996922deSJeff Cody     g_free(s->proxyusername);
941996922deSJeff Cody     g_free(s->proxypassword);
942769ce76dSAlexander Graf }
943769ce76dSAlexander Graf 
944769ce76dSAlexander Graf static int64_t curl_getlength(BlockDriverState *bs)
945769ce76dSAlexander Graf {
946769ce76dSAlexander Graf     BDRVCURLState *s = bs->opaque;
947769ce76dSAlexander Graf     return s->len;
948769ce76dSAlexander Graf }
949769ce76dSAlexander Graf 
950769ce76dSAlexander Graf static BlockDriver bdrv_http = {
951769ce76dSAlexander Graf     .format_name                = "http",
952769ce76dSAlexander Graf     .protocol_name              = "http",
953769ce76dSAlexander Graf 
954769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
9558e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
95666f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
957769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
958769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
959769ce76dSAlexander Graf 
96028256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
96163f0f45fSStefan Hajnoczi 
96263f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
96363f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
964769ce76dSAlexander Graf };
965769ce76dSAlexander Graf 
966769ce76dSAlexander Graf static BlockDriver bdrv_https = {
967769ce76dSAlexander Graf     .format_name                = "https",
968769ce76dSAlexander Graf     .protocol_name              = "https",
969769ce76dSAlexander Graf 
970769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
9718e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
97266f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
973769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
974769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
975769ce76dSAlexander Graf 
97628256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
97763f0f45fSStefan Hajnoczi 
97863f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
97963f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
980769ce76dSAlexander Graf };
981769ce76dSAlexander Graf 
982769ce76dSAlexander Graf static BlockDriver bdrv_ftp = {
983769ce76dSAlexander Graf     .format_name                = "ftp",
984769ce76dSAlexander Graf     .protocol_name              = "ftp",
985769ce76dSAlexander Graf 
986769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
9878e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
98866f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
989769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
990769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
991769ce76dSAlexander Graf 
99228256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
99363f0f45fSStefan Hajnoczi 
99463f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
99563f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
996769ce76dSAlexander Graf };
997769ce76dSAlexander Graf 
998769ce76dSAlexander Graf static BlockDriver bdrv_ftps = {
999769ce76dSAlexander Graf     .format_name                = "ftps",
1000769ce76dSAlexander Graf     .protocol_name              = "ftps",
1001769ce76dSAlexander Graf 
1002769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
10038e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
100466f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
1005769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
1006769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
1007769ce76dSAlexander Graf 
100828256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
100963f0f45fSStefan Hajnoczi 
101063f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
101163f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
1012769ce76dSAlexander Graf };
1013769ce76dSAlexander Graf 
1014769ce76dSAlexander Graf static void curl_block_init(void)
1015769ce76dSAlexander Graf {
1016769ce76dSAlexander Graf     bdrv_register(&bdrv_http);
1017769ce76dSAlexander Graf     bdrv_register(&bdrv_https);
1018769ce76dSAlexander Graf     bdrv_register(&bdrv_ftp);
1019769ce76dSAlexander Graf     bdrv_register(&bdrv_ftps);
1020769ce76dSAlexander Graf }
1021769ce76dSAlexander Graf 
1022769ce76dSAlexander Graf block_init(curl_block_init);
1023