xref: /openbmc/qemu/block/curl.c (revision 709f213214609b693857ec988b7411126d615871)
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  */
2480c71a24SPeter Maydell #include "qemu/osdep.h"
25da34e65cSMarkus Armbruster #include "qapi/error.h"
26769ce76dSAlexander Graf #include "qemu-common.h"
27796a060bSRichard W.M. Jones #include "qemu/error-report.h"
28737e150eSPaolo Bonzini #include "block/block_int.h"
2997a3ea57SMatthew Booth #include "qapi/qmp/qbool.h"
30d49b6836SMarkus Armbruster #include "qapi/qmp/qstring.h"
311bff9606SDaniel P. Berrange #include "crypto/secret.h"
32769ce76dSAlexander Graf #include <curl/curl.h>
33f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
34769ce76dSAlexander Graf 
3541c23467SRichard W.M. Jones // #define DEBUG_CURL
36769ce76dSAlexander Graf // #define DEBUG_VERBOSE
37769ce76dSAlexander Graf 
38769ce76dSAlexander Graf #ifdef DEBUG_CURL
39ed79f37dSZhou Jie #define DEBUG_CURL_PRINT 1
40769ce76dSAlexander Graf #else
41ed79f37dSZhou Jie #define DEBUG_CURL_PRINT 0
42769ce76dSAlexander Graf #endif
43ed79f37dSZhou Jie #define DPRINTF(fmt, ...)                                            \
44ed79f37dSZhou Jie     do {                                                             \
45ed79f37dSZhou Jie         if (DEBUG_CURL_PRINT) {                                      \
46ed79f37dSZhou Jie             fprintf(stderr, fmt, ## __VA_ARGS__);                    \
47ed79f37dSZhou Jie         }                                                            \
48ed79f37dSZhou Jie     } while (0)
49769ce76dSAlexander Graf 
50031fd1beSPeter Maydell #if LIBCURL_VERSION_NUM >= 0x071000
51031fd1beSPeter Maydell /* The multi interface timer callback was introduced in 7.16.0 */
52031fd1beSPeter Maydell #define NEED_CURL_TIMER_CALLBACK
539aedd5a5SMatthew Booth #define HAVE_SOCKET_ACTION
549aedd5a5SMatthew Booth #endif
559aedd5a5SMatthew Booth 
569aedd5a5SMatthew Booth #ifndef HAVE_SOCKET_ACTION
579aedd5a5SMatthew Booth /* If curl_multi_socket_action isn't available, define it statically here in
589aedd5a5SMatthew Booth  * terms of curl_multi_socket. Note that ev_bitmask will be ignored, which is
599aedd5a5SMatthew Booth  * less efficient but still safe. */
609aedd5a5SMatthew Booth static CURLMcode __curl_multi_socket_action(CURLM *multi_handle,
619aedd5a5SMatthew Booth                                             curl_socket_t sockfd,
629aedd5a5SMatthew Booth                                             int ev_bitmask,
639aedd5a5SMatthew Booth                                             int *running_handles)
649aedd5a5SMatthew Booth {
659aedd5a5SMatthew Booth     return curl_multi_socket(multi_handle, sockfd, running_handles);
669aedd5a5SMatthew Booth }
679aedd5a5SMatthew Booth #define curl_multi_socket_action __curl_multi_socket_action
68031fd1beSPeter Maydell #endif
69031fd1beSPeter Maydell 
70fb6d1bbdSStefan Hajnoczi #define PROTOCOLS (CURLPROTO_HTTP | CURLPROTO_HTTPS | \
7123dce387SMax Reitz                    CURLPROTO_FTP | CURLPROTO_FTPS)
72fb6d1bbdSStefan Hajnoczi 
73769ce76dSAlexander Graf #define CURL_NUM_STATES 8
74769ce76dSAlexander Graf #define CURL_NUM_ACB    8
75e3542c67SMatthew Booth #define READ_AHEAD_DEFAULT (256 * 1024)
76212aefaaSDaniel Henrique Barboza #define CURL_TIMEOUT_DEFAULT 5
77f76faedaSRichard W.M. Jones #define CURL_TIMEOUT_MAX 10000
78769ce76dSAlexander Graf 
79e3542c67SMatthew Booth #define CURL_BLOCK_OPT_URL       "url"
80e3542c67SMatthew Booth #define CURL_BLOCK_OPT_READAHEAD "readahead"
8197a3ea57SMatthew Booth #define CURL_BLOCK_OPT_SSLVERIFY "sslverify"
82212aefaaSDaniel Henrique Barboza #define CURL_BLOCK_OPT_TIMEOUT "timeout"
83a94f83d9SRichard W.M. Jones #define CURL_BLOCK_OPT_COOKIE    "cookie"
84327c8ebdSPeter Krempa #define CURL_BLOCK_OPT_COOKIE_SECRET "cookie-secret"
851bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_USERNAME "username"
861bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PASSWORD_SECRET "password-secret"
871bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PROXY_USERNAME "proxy-username"
881bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET "proxy-password-secret"
89e3542c67SMatthew Booth 
90769ce76dSAlexander Graf struct BDRVCURLState;
91769ce76dSAlexander Graf 
922d25964dSJeff Cody static bool libcurl_initialized;
932d25964dSJeff Cody 
94769ce76dSAlexander Graf typedef struct CURLAIOCB {
9528256d82SPaolo Bonzini     Coroutine *co;
96769ce76dSAlexander Graf     QEMUIOVector *qiov;
97363c3c85SNick Thomas 
982125e5eaSPaolo Bonzini     uint64_t offset;
992125e5eaSPaolo Bonzini     uint64_t bytes;
10028256d82SPaolo Bonzini     int ret;
101363c3c85SNick Thomas 
102769ce76dSAlexander Graf     size_t start;
103769ce76dSAlexander Graf     size_t end;
104769ce76dSAlexander Graf } CURLAIOCB;
105769ce76dSAlexander Graf 
106ff5ca166SMax Reitz typedef struct CURLSocket {
107ff5ca166SMax Reitz     int fd;
108ff5ca166SMax Reitz     QLIST_ENTRY(CURLSocket) next;
109ff5ca166SMax Reitz } CURLSocket;
110ff5ca166SMax Reitz 
111769ce76dSAlexander Graf typedef struct CURLState
112769ce76dSAlexander Graf {
113769ce76dSAlexander Graf     struct BDRVCURLState *s;
114769ce76dSAlexander Graf     CURLAIOCB *acb[CURL_NUM_ACB];
115769ce76dSAlexander Graf     CURL *curl;
116ff5ca166SMax Reitz     QLIST_HEAD(, CURLSocket) sockets;
117769ce76dSAlexander Graf     char *orig_buf;
1182125e5eaSPaolo Bonzini     uint64_t buf_start;
119769ce76dSAlexander Graf     size_t buf_off;
120769ce76dSAlexander Graf     size_t buf_len;
121769ce76dSAlexander Graf     char range[128];
122769ce76dSAlexander Graf     char errmsg[CURL_ERROR_SIZE];
123769ce76dSAlexander Graf     char in_use;
124769ce76dSAlexander Graf } CURLState;
125769ce76dSAlexander Graf 
126769ce76dSAlexander Graf typedef struct BDRVCURLState {
127769ce76dSAlexander Graf     CURLM *multi;
128031fd1beSPeter Maydell     QEMUTimer timer;
1292125e5eaSPaolo Bonzini     uint64_t len;
130769ce76dSAlexander Graf     CURLState states[CURL_NUM_STATES];
131769ce76dSAlexander Graf     char *url;
132c76f4952SNolan     size_t readahead_size;
13397a3ea57SMatthew Booth     bool sslverify;
134f76faedaSRichard W.M. Jones     uint64_t timeout;
135a94f83d9SRichard W.M. Jones     char *cookie;
1363494d650SFam Zheng     bool accept_range;
13763f0f45fSStefan Hajnoczi     AioContext *aio_context;
138ba3186c4SPaolo Bonzini     QemuMutex mutex;
139*709f2132SPaolo Bonzini     CoQueue free_state_waitq;
1401bff9606SDaniel P. Berrange     char *username;
1411bff9606SDaniel P. Berrange     char *password;
1421bff9606SDaniel P. Berrange     char *proxyusername;
1431bff9606SDaniel P. Berrange     char *proxypassword;
144769ce76dSAlexander Graf } BDRVCURLState;
145769ce76dSAlexander Graf 
146769ce76dSAlexander Graf static void curl_clean_state(CURLState *s);
147769ce76dSAlexander Graf static void curl_multi_do(void *arg);
148838ef602SMatthew Booth static void curl_multi_read(void *arg);
149769ce76dSAlexander Graf 
150031fd1beSPeter Maydell #ifdef NEED_CURL_TIMER_CALLBACK
15134db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
152031fd1beSPeter Maydell static int curl_timer_cb(CURLM *multi, long timeout_ms, void *opaque)
153031fd1beSPeter Maydell {
154031fd1beSPeter Maydell     BDRVCURLState *s = opaque;
155031fd1beSPeter Maydell 
156031fd1beSPeter Maydell     DPRINTF("CURL: timer callback timeout_ms %ld\n", timeout_ms);
157031fd1beSPeter Maydell     if (timeout_ms == -1) {
158031fd1beSPeter Maydell         timer_del(&s->timer);
159031fd1beSPeter Maydell     } else {
160031fd1beSPeter Maydell         int64_t timeout_ns = (int64_t)timeout_ms * 1000 * 1000;
161031fd1beSPeter Maydell         timer_mod(&s->timer,
162031fd1beSPeter Maydell                   qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ns);
163031fd1beSPeter Maydell     }
164031fd1beSPeter Maydell     return 0;
165031fd1beSPeter Maydell }
166031fd1beSPeter Maydell #endif
167031fd1beSPeter Maydell 
16834db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
169769ce76dSAlexander Graf static int curl_sock_cb(CURL *curl, curl_socket_t fd, int action,
17063f0f45fSStefan Hajnoczi                         void *userp, void *sp)
171769ce76dSAlexander Graf {
17263f0f45fSStefan Hajnoczi     BDRVCURLState *s;
173838ef602SMatthew Booth     CURLState *state = NULL;
174ff5ca166SMax Reitz     CURLSocket *socket;
175ff5ca166SMax Reitz 
176838ef602SMatthew Booth     curl_easy_getinfo(curl, CURLINFO_PRIVATE, (char **)&state);
17763f0f45fSStefan Hajnoczi     s = state->s;
178838ef602SMatthew Booth 
179ff5ca166SMax Reitz     QLIST_FOREACH(socket, &state->sockets, next) {
180ff5ca166SMax Reitz         if (socket->fd == fd) {
181ff5ca166SMax Reitz             if (action == CURL_POLL_REMOVE) {
182ff5ca166SMax Reitz                 QLIST_REMOVE(socket, next);
183ff5ca166SMax Reitz                 g_free(socket);
184ff5ca166SMax Reitz             }
185ff5ca166SMax Reitz             break;
186ff5ca166SMax Reitz         }
187ff5ca166SMax Reitz     }
188ff5ca166SMax Reitz     if (!socket) {
189ff5ca166SMax Reitz         socket = g_new0(CURLSocket, 1);
190ff5ca166SMax Reitz         socket->fd = fd;
191ff5ca166SMax Reitz         QLIST_INSERT_HEAD(&state->sockets, socket, next);
192ff5ca166SMax Reitz     }
193ff5ca166SMax Reitz     socket = NULL;
194ff5ca166SMax Reitz 
19592b6a160SFam Zheng     DPRINTF("CURL (AIO): Sock action %d on fd %d\n", action, (int)fd);
196769ce76dSAlexander Graf     switch (action) {
197769ce76dSAlexander Graf         case CURL_POLL_IN:
198dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
199f6a51c84SStefan Hajnoczi                                curl_multi_read, NULL, NULL, state);
200769ce76dSAlexander Graf             break;
201769ce76dSAlexander Graf         case CURL_POLL_OUT:
202dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
203f6a51c84SStefan Hajnoczi                                NULL, curl_multi_do, NULL, state);
204769ce76dSAlexander Graf             break;
205769ce76dSAlexander Graf         case CURL_POLL_INOUT:
206dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
207f6a51c84SStefan Hajnoczi                                curl_multi_read, curl_multi_do, NULL, state);
208769ce76dSAlexander Graf             break;
209769ce76dSAlexander Graf         case CURL_POLL_REMOVE:
210dca21ef2SFam Zheng             aio_set_fd_handler(s->aio_context, fd, false,
211f6a51c84SStefan Hajnoczi                                NULL, NULL, NULL, NULL);
212769ce76dSAlexander Graf             break;
213769ce76dSAlexander Graf     }
214769ce76dSAlexander Graf 
215769ce76dSAlexander Graf     return 0;
216769ce76dSAlexander Graf }
217769ce76dSAlexander Graf 
21834db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
2193494d650SFam Zheng static size_t curl_header_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
220769ce76dSAlexander Graf {
2213494d650SFam Zheng     BDRVCURLState *s = opaque;
222769ce76dSAlexander Graf     size_t realsize = size * nmemb;
2233494d650SFam Zheng     const char *accept_line = "Accept-Ranges: bytes";
224769ce76dSAlexander Graf 
2253494d650SFam Zheng     if (realsize >= strlen(accept_line)
2263494d650SFam Zheng         && strncmp((char *)ptr, accept_line, strlen(accept_line)) == 0) {
2273494d650SFam Zheng         s->accept_range = true;
2280bfcd599SBlue Swirl     }
229769ce76dSAlexander Graf 
230769ce76dSAlexander Graf     return realsize;
231769ce76dSAlexander Graf }
232769ce76dSAlexander Graf 
23334db05e7SPaolo Bonzini /* Called from curl_multi_do_locked, with s->mutex held.  */
234769ce76dSAlexander Graf static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
235769ce76dSAlexander Graf {
236769ce76dSAlexander Graf     CURLState *s = ((CURLState*)opaque);
237769ce76dSAlexander Graf     size_t realsize = size * nmemb;
238769ce76dSAlexander Graf     int i;
239769ce76dSAlexander Graf 
2400bfcd599SBlue Swirl     DPRINTF("CURL: Just reading %zd bytes\n", realsize);
241769ce76dSAlexander Graf 
2424e767657SMax Reitz     if (!s || !s->orig_buf) {
2434e767657SMax Reitz         goto read_end;
2444e767657SMax Reitz     }
245769ce76dSAlexander Graf 
2466d4b9e55SFam Zheng     if (s->buf_off >= s->buf_len) {
2476d4b9e55SFam Zheng         /* buffer full, read nothing */
2484e767657SMax Reitz         goto read_end;
2496d4b9e55SFam Zheng     }
2506d4b9e55SFam Zheng     realsize = MIN(realsize, s->buf_len - s->buf_off);
251769ce76dSAlexander Graf     memcpy(s->orig_buf + s->buf_off, ptr, realsize);
252769ce76dSAlexander Graf     s->buf_off += realsize;
253769ce76dSAlexander Graf 
254769ce76dSAlexander Graf     for(i=0; i<CURL_NUM_ACB; i++) {
255769ce76dSAlexander Graf         CURLAIOCB *acb = s->acb[i];
256769ce76dSAlexander Graf 
257769ce76dSAlexander Graf         if (!acb)
258769ce76dSAlexander Graf             continue;
259769ce76dSAlexander Graf 
260769ce76dSAlexander Graf         if ((s->buf_off >= acb->end)) {
2612125e5eaSPaolo Bonzini             size_t request_length = acb->bytes;
2624e504535SMax Reitz 
26303396148SMichael Tokarev             qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,
264769ce76dSAlexander Graf                                 acb->end - acb->start);
2654e504535SMax Reitz 
2664e504535SMax Reitz             if (acb->end - acb->start < request_length) {
2674e504535SMax Reitz                 size_t offset = acb->end - acb->start;
2684e504535SMax Reitz                 qemu_iovec_memset(acb->qiov, offset, 0,
2694e504535SMax Reitz                                   request_length - offset);
2704e504535SMax Reitz             }
2714e504535SMax Reitz 
27228256d82SPaolo Bonzini             acb->ret = 0;
273769ce76dSAlexander Graf             s->acb[i] = NULL;
27428256d82SPaolo Bonzini             qemu_mutex_unlock(&s->s->mutex);
27528256d82SPaolo Bonzini             aio_co_wake(acb->co);
27628256d82SPaolo Bonzini             qemu_mutex_lock(&s->s->mutex);
277769ce76dSAlexander Graf         }
278769ce76dSAlexander Graf     }
279769ce76dSAlexander Graf 
2804e767657SMax Reitz read_end:
2814e767657SMax Reitz     /* curl will error out if we do not return this value */
2824e767657SMax Reitz     return size * nmemb;
283769ce76dSAlexander Graf }
284769ce76dSAlexander Graf 
285456af346SPaolo Bonzini /* Called with s->mutex held.  */
28628256d82SPaolo Bonzini static bool curl_find_buf(BDRVCURLState *s, uint64_t start, uint64_t len,
287769ce76dSAlexander Graf                           CURLAIOCB *acb)
288769ce76dSAlexander Graf {
289769ce76dSAlexander Graf     int i;
2902125e5eaSPaolo Bonzini     uint64_t end = start + len;
2912125e5eaSPaolo Bonzini     uint64_t clamped_end = MIN(end, s->len);
2922125e5eaSPaolo Bonzini     uint64_t clamped_len = clamped_end - start;
293769ce76dSAlexander Graf 
294769ce76dSAlexander Graf     for (i=0; i<CURL_NUM_STATES; i++) {
295769ce76dSAlexander Graf         CURLState *state = &s->states[i];
2962125e5eaSPaolo Bonzini         uint64_t buf_end = (state->buf_start + state->buf_off);
2972125e5eaSPaolo Bonzini         uint64_t buf_fend = (state->buf_start + state->buf_len);
298769ce76dSAlexander Graf 
299769ce76dSAlexander Graf         if (!state->orig_buf)
300769ce76dSAlexander Graf             continue;
301769ce76dSAlexander Graf         if (!state->buf_off)
302769ce76dSAlexander Graf             continue;
303769ce76dSAlexander Graf 
304769ce76dSAlexander Graf         // Does the existing buffer cover our section?
305769ce76dSAlexander Graf         if ((start >= state->buf_start) &&
306769ce76dSAlexander Graf             (start <= buf_end) &&
3074e504535SMax Reitz             (clamped_end >= state->buf_start) &&
3084e504535SMax Reitz             (clamped_end <= buf_end))
309769ce76dSAlexander Graf         {
310769ce76dSAlexander Graf             char *buf = state->orig_buf + (start - state->buf_start);
311769ce76dSAlexander Graf 
3124e504535SMax Reitz             qemu_iovec_from_buf(acb->qiov, 0, buf, clamped_len);
3134e504535SMax Reitz             if (clamped_len < len) {
3144e504535SMax Reitz                 qemu_iovec_memset(acb->qiov, clamped_len, 0, len - clamped_len);
3154e504535SMax Reitz             }
31628256d82SPaolo Bonzini             acb->ret = 0;
31728256d82SPaolo Bonzini             return true;
318769ce76dSAlexander Graf         }
319769ce76dSAlexander Graf 
320769ce76dSAlexander Graf         // Wait for unfinished chunks
321b7079df4SMatthew Booth         if (state->in_use &&
322b7079df4SMatthew Booth             (start >= state->buf_start) &&
323769ce76dSAlexander Graf             (start <= buf_fend) &&
3244e504535SMax Reitz             (clamped_end >= state->buf_start) &&
3254e504535SMax Reitz             (clamped_end <= buf_fend))
326769ce76dSAlexander Graf         {
327769ce76dSAlexander Graf             int j;
328769ce76dSAlexander Graf 
329769ce76dSAlexander Graf             acb->start = start - state->buf_start;
3304e504535SMax Reitz             acb->end = acb->start + clamped_len;
331769ce76dSAlexander Graf 
332769ce76dSAlexander Graf             for (j=0; j<CURL_NUM_ACB; j++) {
333769ce76dSAlexander Graf                 if (!state->acb[j]) {
334769ce76dSAlexander Graf                     state->acb[j] = acb;
33528256d82SPaolo Bonzini                     return true;
336769ce76dSAlexander Graf                 }
337769ce76dSAlexander Graf             }
338769ce76dSAlexander Graf         }
339769ce76dSAlexander Graf     }
340769ce76dSAlexander Graf 
34128256d82SPaolo Bonzini     return false;
342769ce76dSAlexander Graf }
343769ce76dSAlexander Graf 
344ba3186c4SPaolo Bonzini /* Called with s->mutex held.  */
345838ef602SMatthew Booth static void curl_multi_check_completion(BDRVCURLState *s)
346769ce76dSAlexander Graf {
347769ce76dSAlexander Graf     int msgs_in_queue;
348769ce76dSAlexander Graf 
349769ce76dSAlexander Graf     /* Try to find done transfers, so we can free the easy
350769ce76dSAlexander Graf      * handle again. */
3511f2cead3SMatthew Booth     for (;;) {
352769ce76dSAlexander Graf         CURLMsg *msg;
353769ce76dSAlexander Graf         msg = curl_multi_info_read(s->multi, &msgs_in_queue);
354769ce76dSAlexander Graf 
3551f2cead3SMatthew Booth         /* Quit when there are no more completions */
356769ce76dSAlexander Graf         if (!msg)
357769ce76dSAlexander Graf             break;
358769ce76dSAlexander Graf 
3591f2cead3SMatthew Booth         if (msg->msg == CURLMSG_DONE) {
360769ce76dSAlexander Graf             CURLState *state = NULL;
361f6246509SMatthew Booth             curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,
362f6246509SMatthew Booth                               (char **)&state);
363f785a5aeSNicholas Thomas 
364f785a5aeSNicholas Thomas             /* ACBs for successful messages get completed in curl_read_cb */
365f785a5aeSNicholas Thomas             if (msg->data.result != CURLE_OK) {
366f785a5aeSNicholas Thomas                 int i;
367796a060bSRichard W.M. Jones                 static int errcount = 100;
368796a060bSRichard W.M. Jones 
369796a060bSRichard W.M. Jones                 /* Don't lose the original error message from curl, since
370796a060bSRichard W.M. Jones                  * it contains extra data.
371796a060bSRichard W.M. Jones                  */
372796a060bSRichard W.M. Jones                 if (errcount > 0) {
373796a060bSRichard W.M. Jones                     error_report("curl: %s", state->errmsg);
374796a060bSRichard W.M. Jones                     if (--errcount == 0) {
375796a060bSRichard W.M. Jones                         error_report("curl: further errors suppressed");
376796a060bSRichard W.M. Jones                     }
377796a060bSRichard W.M. Jones                 }
378796a060bSRichard W.M. Jones 
379f785a5aeSNicholas Thomas                 for (i = 0; i < CURL_NUM_ACB; i++) {
380f785a5aeSNicholas Thomas                     CURLAIOCB *acb = state->acb[i];
381f785a5aeSNicholas Thomas 
382f785a5aeSNicholas Thomas                     if (acb == NULL) {
383f785a5aeSNicholas Thomas                         continue;
384f785a5aeSNicholas Thomas                     }
385f785a5aeSNicholas Thomas 
38628256d82SPaolo Bonzini                     acb->ret = -EIO;
387f785a5aeSNicholas Thomas                     state->acb[i] = NULL;
38828256d82SPaolo Bonzini                     qemu_mutex_unlock(&s->mutex);
38928256d82SPaolo Bonzini                     aio_co_wake(acb->co);
39028256d82SPaolo Bonzini                     qemu_mutex_lock(&s->mutex);
391f785a5aeSNicholas Thomas                 }
392f785a5aeSNicholas Thomas             }
393f785a5aeSNicholas Thomas 
394769ce76dSAlexander Graf             curl_clean_state(state);
395769ce76dSAlexander Graf             break;
396769ce76dSAlexander Graf         }
397769ce76dSAlexander Graf     }
398769ce76dSAlexander Graf }
399769ce76dSAlexander Graf 
400ba3186c4SPaolo Bonzini /* Called with s->mutex held.  */
4019d456654SPaolo Bonzini static void curl_multi_do_locked(CURLState *s)
402031fd1beSPeter Maydell {
403ff5ca166SMax Reitz     CURLSocket *socket, *next_socket;
404031fd1beSPeter Maydell     int running;
405031fd1beSPeter Maydell     int r;
406031fd1beSPeter Maydell 
407838ef602SMatthew Booth     if (!s->s->multi) {
408031fd1beSPeter Maydell         return;
409031fd1beSPeter Maydell     }
410031fd1beSPeter Maydell 
411ff5ca166SMax Reitz     /* Need to use _SAFE because curl_multi_socket_action() may trigger
412ff5ca166SMax Reitz      * curl_sock_cb() which might modify this list */
413ff5ca166SMax Reitz     QLIST_FOREACH_SAFE(socket, &s->sockets, next, next_socket) {
414031fd1beSPeter Maydell         do {
415ff5ca166SMax Reitz             r = curl_multi_socket_action(s->s->multi, socket->fd, 0, &running);
416031fd1beSPeter Maydell         } while (r == CURLM_CALL_MULTI_PERFORM);
417ff5ca166SMax Reitz     }
418838ef602SMatthew Booth }
419838ef602SMatthew Booth 
4209d456654SPaolo Bonzini static void curl_multi_do(void *arg)
4219d456654SPaolo Bonzini {
4229d456654SPaolo Bonzini     CURLState *s = (CURLState *)arg;
4239d456654SPaolo Bonzini 
424ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->s->mutex);
4259d456654SPaolo Bonzini     curl_multi_do_locked(s);
426ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->s->mutex);
4279d456654SPaolo Bonzini }
4289d456654SPaolo Bonzini 
429838ef602SMatthew Booth static void curl_multi_read(void *arg)
430838ef602SMatthew Booth {
431838ef602SMatthew Booth     CURLState *s = (CURLState *)arg;
432838ef602SMatthew Booth 
433ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->s->mutex);
4349d456654SPaolo Bonzini     curl_multi_do_locked(s);
435838ef602SMatthew Booth     curl_multi_check_completion(s->s);
436ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->s->mutex);
437031fd1beSPeter Maydell }
438031fd1beSPeter Maydell 
439031fd1beSPeter Maydell static void curl_multi_timeout_do(void *arg)
440031fd1beSPeter Maydell {
441031fd1beSPeter Maydell #ifdef NEED_CURL_TIMER_CALLBACK
442031fd1beSPeter Maydell     BDRVCURLState *s = (BDRVCURLState *)arg;
443031fd1beSPeter Maydell     int running;
444031fd1beSPeter Maydell 
445031fd1beSPeter Maydell     if (!s->multi) {
446031fd1beSPeter Maydell         return;
447031fd1beSPeter Maydell     }
448031fd1beSPeter Maydell 
449ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
450031fd1beSPeter Maydell     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
451031fd1beSPeter Maydell 
452838ef602SMatthew Booth     curl_multi_check_completion(s);
453ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
454031fd1beSPeter Maydell #else
455031fd1beSPeter Maydell     abort();
456031fd1beSPeter Maydell #endif
457031fd1beSPeter Maydell }
458031fd1beSPeter Maydell 
459456af346SPaolo Bonzini /* Called with s->mutex held.  */
4603ce6a729SPaolo Bonzini static CURLState *curl_find_state(BDRVCURLState *s)
461769ce76dSAlexander Graf {
462769ce76dSAlexander Graf     CURLState *state = NULL;
4633ce6a729SPaolo Bonzini     int i;
464769ce76dSAlexander Graf 
465769ce76dSAlexander Graf     for (i = 0; i < CURL_NUM_STATES; i++) {
4663ce6a729SPaolo Bonzini         if (!s->states[i].in_use) {
467769ce76dSAlexander Graf             state = &s->states[i];
468769ce76dSAlexander Graf             state->in_use = 1;
469769ce76dSAlexander Graf             break;
470769ce76dSAlexander Graf         }
471769ce76dSAlexander Graf     }
4723ce6a729SPaolo Bonzini     return state;
4733ce6a729SPaolo Bonzini }
474769ce76dSAlexander Graf 
4753ce6a729SPaolo Bonzini static int curl_init_state(BDRVCURLState *s, CURLState *state)
4763ce6a729SPaolo Bonzini {
4779e550b32SMatthew Booth     if (!state->curl) {
478769ce76dSAlexander Graf         state->curl = curl_easy_init();
4799e550b32SMatthew Booth         if (!state->curl) {
4803ce6a729SPaolo Bonzini             return -EIO;
4819e550b32SMatthew Booth         }
482769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
48397a3ea57SMatthew Booth         curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,
48497a3ea57SMatthew Booth                          (long) s->sslverify);
485a94f83d9SRichard W.M. Jones         if (s->cookie) {
486a94f83d9SRichard W.M. Jones             curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);
487a94f83d9SRichard W.M. Jones         }
488f76faedaSRichard W.M. Jones         curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);
4899e550b32SMatthew Booth         curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,
4909e550b32SMatthew Booth                          (void *)curl_read_cb);
491769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
492769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
493769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
494769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
495769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
496769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
497f785a5aeSNicholas Thomas         curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
498769ce76dSAlexander Graf 
4991bff9606SDaniel P. Berrange         if (s->username) {
5001bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);
5011bff9606SDaniel P. Berrange         }
5021bff9606SDaniel P. Berrange         if (s->password) {
5031bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);
5041bff9606SDaniel P. Berrange         }
5051bff9606SDaniel P. Berrange         if (s->proxyusername) {
5061bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl,
5071bff9606SDaniel P. Berrange                              CURLOPT_PROXYUSERNAME, s->proxyusername);
5081bff9606SDaniel P. Berrange         }
5091bff9606SDaniel P. Berrange         if (s->proxypassword) {
5101bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl,
5111bff9606SDaniel P. Berrange                              CURLOPT_PROXYPASSWORD, s->proxypassword);
5121bff9606SDaniel P. Berrange         }
5131bff9606SDaniel P. Berrange 
514fb6d1bbdSStefan Hajnoczi         /* Restrict supported protocols to avoid security issues in the more
515fb6d1bbdSStefan Hajnoczi          * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see
516fb6d1bbdSStefan Hajnoczi          * CVE-2013-0249.
5178a8f5840SStefan Hajnoczi          *
5188a8f5840SStefan Hajnoczi          * Restricting protocols is only supported from 7.19.4 upwards.
519fb6d1bbdSStefan Hajnoczi          */
5208a8f5840SStefan Hajnoczi #if LIBCURL_VERSION_NUM >= 0x071304
521fb6d1bbdSStefan Hajnoczi         curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
522fb6d1bbdSStefan Hajnoczi         curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
5238a8f5840SStefan Hajnoczi #endif
524fb6d1bbdSStefan Hajnoczi 
525769ce76dSAlexander Graf #ifdef DEBUG_VERBOSE
526769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
527769ce76dSAlexander Graf #endif
5289e550b32SMatthew Booth     }
529769ce76dSAlexander Graf 
530ff5ca166SMax Reitz     QLIST_INIT(&state->sockets);
531769ce76dSAlexander Graf     state->s = s;
532769ce76dSAlexander Graf 
5333ce6a729SPaolo Bonzini     return 0;
534769ce76dSAlexander Graf }
535769ce76dSAlexander Graf 
536456af346SPaolo Bonzini /* Called with s->mutex held.  */
537769ce76dSAlexander Graf static void curl_clean_state(CURLState *s)
538769ce76dSAlexander Graf {
539675a7756SPaolo Bonzini     int j;
540675a7756SPaolo Bonzini     for (j = 0; j < CURL_NUM_ACB; j++) {
541675a7756SPaolo Bonzini         assert(!s->acb[j]);
542675a7756SPaolo Bonzini     }
543675a7756SPaolo Bonzini 
544769ce76dSAlexander Graf     if (s->s->multi)
545769ce76dSAlexander Graf         curl_multi_remove_handle(s->s->multi, s->curl);
546ff5ca166SMax Reitz 
547ff5ca166SMax Reitz     while (!QLIST_EMPTY(&s->sockets)) {
548ff5ca166SMax Reitz         CURLSocket *socket = QLIST_FIRST(&s->sockets);
549ff5ca166SMax Reitz 
550ff5ca166SMax Reitz         QLIST_REMOVE(socket, next);
551ff5ca166SMax Reitz         g_free(socket);
552ff5ca166SMax Reitz     }
553ff5ca166SMax Reitz 
554769ce76dSAlexander Graf     s->in_use = 0;
5552bb5c936SPaolo Bonzini 
556*709f2132SPaolo Bonzini     qemu_co_enter_next(&s->s->free_state_waitq, &s->s->mutex);
557769ce76dSAlexander Graf }
558769ce76dSAlexander Graf 
5598e6d58cdSKevin Wolf static void curl_parse_filename(const char *filename, QDict *options,
5608e6d58cdSKevin Wolf                                 Error **errp)
561769ce76dSAlexander Graf {
56246f5ac20SEric Blake     qdict_put_str(options, CURL_BLOCK_OPT_URL, filename);
5638e6d58cdSKevin Wolf }
5648e6d58cdSKevin Wolf 
56563f0f45fSStefan Hajnoczi static void curl_detach_aio_context(BlockDriverState *bs)
56663f0f45fSStefan Hajnoczi {
56763f0f45fSStefan Hajnoczi     BDRVCURLState *s = bs->opaque;
56863f0f45fSStefan Hajnoczi     int i;
56963f0f45fSStefan Hajnoczi 
570456af346SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
57163f0f45fSStefan Hajnoczi     for (i = 0; i < CURL_NUM_STATES; i++) {
57263f0f45fSStefan Hajnoczi         if (s->states[i].in_use) {
57363f0f45fSStefan Hajnoczi             curl_clean_state(&s->states[i]);
57463f0f45fSStefan Hajnoczi         }
57563f0f45fSStefan Hajnoczi         if (s->states[i].curl) {
57663f0f45fSStefan Hajnoczi             curl_easy_cleanup(s->states[i].curl);
57763f0f45fSStefan Hajnoczi             s->states[i].curl = NULL;
57863f0f45fSStefan Hajnoczi         }
57963f0f45fSStefan Hajnoczi         g_free(s->states[i].orig_buf);
58063f0f45fSStefan Hajnoczi         s->states[i].orig_buf = NULL;
58163f0f45fSStefan Hajnoczi     }
58263f0f45fSStefan Hajnoczi     if (s->multi) {
58363f0f45fSStefan Hajnoczi         curl_multi_cleanup(s->multi);
58463f0f45fSStefan Hajnoczi         s->multi = NULL;
58563f0f45fSStefan Hajnoczi     }
586456af346SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
58763f0f45fSStefan Hajnoczi 
58863f0f45fSStefan Hajnoczi     timer_del(&s->timer);
58963f0f45fSStefan Hajnoczi }
59063f0f45fSStefan Hajnoczi 
59163f0f45fSStefan Hajnoczi static void curl_attach_aio_context(BlockDriverState *bs,
59263f0f45fSStefan Hajnoczi                                     AioContext *new_context)
59363f0f45fSStefan Hajnoczi {
59463f0f45fSStefan Hajnoczi     BDRVCURLState *s = bs->opaque;
59563f0f45fSStefan Hajnoczi 
59663f0f45fSStefan Hajnoczi     aio_timer_init(new_context, &s->timer,
59763f0f45fSStefan Hajnoczi                    QEMU_CLOCK_REALTIME, SCALE_NS,
59863f0f45fSStefan Hajnoczi                    curl_multi_timeout_do, s);
59963f0f45fSStefan Hajnoczi 
60063f0f45fSStefan Hajnoczi     assert(!s->multi);
60163f0f45fSStefan Hajnoczi     s->multi = curl_multi_init();
60263f0f45fSStefan Hajnoczi     s->aio_context = new_context;
60363f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
60463f0f45fSStefan Hajnoczi #ifdef NEED_CURL_TIMER_CALLBACK
60563f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
60663f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
60763f0f45fSStefan Hajnoczi #endif
60863f0f45fSStefan Hajnoczi }
60963f0f45fSStefan Hajnoczi 
6108e6d58cdSKevin Wolf static QemuOptsList runtime_opts = {
6118e6d58cdSKevin Wolf     .name = "curl",
6128e6d58cdSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
6138e6d58cdSKevin Wolf     .desc = {
6148e6d58cdSKevin Wolf         {
615e3542c67SMatthew Booth             .name = CURL_BLOCK_OPT_URL,
6168e6d58cdSKevin Wolf             .type = QEMU_OPT_STRING,
6178e6d58cdSKevin Wolf             .help = "URL to open",
6188e6d58cdSKevin Wolf         },
6198e6d58cdSKevin Wolf         {
620e3542c67SMatthew Booth             .name = CURL_BLOCK_OPT_READAHEAD,
6218e6d58cdSKevin Wolf             .type = QEMU_OPT_SIZE,
6228e6d58cdSKevin Wolf             .help = "Readahead size",
6238e6d58cdSKevin Wolf         },
62497a3ea57SMatthew Booth         {
62597a3ea57SMatthew Booth             .name = CURL_BLOCK_OPT_SSLVERIFY,
62697a3ea57SMatthew Booth             .type = QEMU_OPT_BOOL,
62797a3ea57SMatthew Booth             .help = "Verify SSL certificate"
62897a3ea57SMatthew Booth         },
629212aefaaSDaniel Henrique Barboza         {
630212aefaaSDaniel Henrique Barboza             .name = CURL_BLOCK_OPT_TIMEOUT,
631212aefaaSDaniel Henrique Barboza             .type = QEMU_OPT_NUMBER,
632212aefaaSDaniel Henrique Barboza             .help = "Curl timeout"
633212aefaaSDaniel Henrique Barboza         },
634a94f83d9SRichard W.M. Jones         {
635a94f83d9SRichard W.M. Jones             .name = CURL_BLOCK_OPT_COOKIE,
636a94f83d9SRichard W.M. Jones             .type = QEMU_OPT_STRING,
637a94f83d9SRichard W.M. Jones             .help = "Pass the cookie or list of cookies with each request"
638a94f83d9SRichard W.M. Jones         },
6391bff9606SDaniel P. Berrange         {
640327c8ebdSPeter Krempa             .name = CURL_BLOCK_OPT_COOKIE_SECRET,
641327c8ebdSPeter Krempa             .type = QEMU_OPT_STRING,
642327c8ebdSPeter Krempa             .help = "ID of secret used as cookie passed with each request"
643327c8ebdSPeter Krempa         },
644327c8ebdSPeter Krempa         {
6451bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_USERNAME,
6461bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6471bff9606SDaniel P. Berrange             .help = "Username for HTTP auth"
6481bff9606SDaniel P. Berrange         },
6491bff9606SDaniel P. Berrange         {
6501bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PASSWORD_SECRET,
6511bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6521bff9606SDaniel P. Berrange             .help = "ID of secret used as password for HTTP auth",
6531bff9606SDaniel P. Berrange         },
6541bff9606SDaniel P. Berrange         {
6551bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PROXY_USERNAME,
6561bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6571bff9606SDaniel P. Berrange             .help = "Username for HTTP proxy auth"
6581bff9606SDaniel P. Berrange         },
6591bff9606SDaniel P. Berrange         {
6601bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
6611bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6621bff9606SDaniel P. Berrange             .help = "ID of secret used as password for HTTP proxy auth",
6631bff9606SDaniel P. Berrange         },
6648e6d58cdSKevin Wolf         { /* end of list */ }
6658e6d58cdSKevin Wolf     },
6668e6d58cdSKevin Wolf };
6678e6d58cdSKevin Wolf 
6681bff9606SDaniel P. Berrange 
669015a1036SMax Reitz static int curl_open(BlockDriverState *bs, QDict *options, int flags,
670015a1036SMax Reitz                      Error **errp)
6718e6d58cdSKevin Wolf {
6728e6d58cdSKevin Wolf     BDRVCURLState *s = bs->opaque;
6738e6d58cdSKevin Wolf     CURLState *state = NULL;
6748e6d58cdSKevin Wolf     QemuOpts *opts;
6758e6d58cdSKevin Wolf     Error *local_err = NULL;
6768e6d58cdSKevin Wolf     const char *file;
677a94f83d9SRichard W.M. Jones     const char *cookie;
678327c8ebdSPeter Krempa     const char *cookie_secret;
6798e6d58cdSKevin Wolf     double d;
6801bff9606SDaniel P. Berrange     const char *secretid;
68134634ca2SMax Reitz     const char *protocol_delimiter;
6822d25964dSJeff Cody     int ret;
6838e6d58cdSKevin Wolf 
6848e6d58cdSKevin Wolf 
685a7cea2baSRichard W.M. Jones     if (flags & BDRV_O_RDWR) {
6862a94fee3SPaolo Bonzini         error_setg(errp, "curl block device does not support writes");
687a7cea2baSRichard W.M. Jones         return -EROFS;
688a7cea2baSRichard W.M. Jones     }
689a7cea2baSRichard W.M. Jones 
6902d25964dSJeff Cody     if (!libcurl_initialized) {
6912d25964dSJeff Cody         ret = curl_global_init(CURL_GLOBAL_ALL);
6922d25964dSJeff Cody         if (ret) {
6932d25964dSJeff Cody             error_setg(errp, "libcurl initialization failed with %d", ret);
6942d25964dSJeff Cody             return -EIO;
6952d25964dSJeff Cody         }
6962d25964dSJeff Cody         libcurl_initialized = true;
6972d25964dSJeff Cody     }
6982d25964dSJeff Cody 
699456af346SPaolo Bonzini     qemu_mutex_init(&s->mutex);
70087ea75d5SPeter Crosthwaite     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
7018e6d58cdSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
70284d18f06SMarkus Armbruster     if (local_err) {
7032a94fee3SPaolo Bonzini         error_propagate(errp, local_err);
7048e6d58cdSKevin Wolf         goto out_noclean;
7058e6d58cdSKevin Wolf     }
7068e6d58cdSKevin Wolf 
707e3542c67SMatthew Booth     s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
708e3542c67SMatthew Booth                                           READ_AHEAD_DEFAULT);
709c76f4952SNolan     if ((s->readahead_size & 0x1ff) != 0) {
7102a94fee3SPaolo Bonzini         error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
711c76f4952SNolan                    s->readahead_size);
712c76f4952SNolan         goto out_noclean;
713c76f4952SNolan     }
714c76f4952SNolan 
715212aefaaSDaniel Henrique Barboza     s->timeout = qemu_opt_get_number(opts, CURL_BLOCK_OPT_TIMEOUT,
716212aefaaSDaniel Henrique Barboza                                      CURL_TIMEOUT_DEFAULT);
717f76faedaSRichard W.M. Jones     if (s->timeout > CURL_TIMEOUT_MAX) {
718f76faedaSRichard W.M. Jones         error_setg(errp, "timeout parameter is too large or negative");
719f76faedaSRichard W.M. Jones         goto out_noclean;
720f76faedaSRichard W.M. Jones     }
721212aefaaSDaniel Henrique Barboza 
72297a3ea57SMatthew Booth     s->sslverify = qemu_opt_get_bool(opts, CURL_BLOCK_OPT_SSLVERIFY, true);
72397a3ea57SMatthew Booth 
724a94f83d9SRichard W.M. Jones     cookie = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE);
725327c8ebdSPeter Krempa     cookie_secret = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE_SECRET);
726327c8ebdSPeter Krempa 
727327c8ebdSPeter Krempa     if (cookie && cookie_secret) {
728327c8ebdSPeter Krempa         error_setg(errp,
729327c8ebdSPeter Krempa                    "curl driver cannot handle both cookie and cookie secret");
730327c8ebdSPeter Krempa         goto out_noclean;
731327c8ebdSPeter Krempa     }
732327c8ebdSPeter Krempa 
733327c8ebdSPeter Krempa     if (cookie_secret) {
734327c8ebdSPeter Krempa         s->cookie = qcrypto_secret_lookup_as_utf8(cookie_secret, errp);
735327c8ebdSPeter Krempa         if (!s->cookie) {
736327c8ebdSPeter Krempa             goto out_noclean;
737327c8ebdSPeter Krempa         }
738327c8ebdSPeter Krempa     } else {
739a94f83d9SRichard W.M. Jones         s->cookie = g_strdup(cookie);
740327c8ebdSPeter Krempa     }
741a94f83d9SRichard W.M. Jones 
742e3542c67SMatthew Booth     file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
7438e6d58cdSKevin Wolf     if (file == NULL) {
7442a94fee3SPaolo Bonzini         error_setg(errp, "curl block driver requires an 'url' option");
7458e6d58cdSKevin Wolf         goto out_noclean;
7468e6d58cdSKevin Wolf     }
7478e6d58cdSKevin Wolf 
74834634ca2SMax Reitz     if (!strstart(file, bs->drv->protocol_name, &protocol_delimiter) ||
74934634ca2SMax Reitz         !strstart(protocol_delimiter, "://", NULL))
75034634ca2SMax Reitz     {
75134634ca2SMax Reitz         error_setg(errp, "%s curl driver cannot handle the URL '%s' (does not "
75234634ca2SMax Reitz                    "start with '%s://')", bs->drv->protocol_name, file,
75334634ca2SMax Reitz                    bs->drv->protocol_name);
75434634ca2SMax Reitz         goto out_noclean;
75534634ca2SMax Reitz     }
75634634ca2SMax Reitz 
7571bff9606SDaniel P. Berrange     s->username = g_strdup(qemu_opt_get(opts, CURL_BLOCK_OPT_USERNAME));
7581bff9606SDaniel P. Berrange     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PASSWORD_SECRET);
7591bff9606SDaniel P. Berrange 
7601bff9606SDaniel P. Berrange     if (secretid) {
7611bff9606SDaniel P. Berrange         s->password = qcrypto_secret_lookup_as_utf8(secretid, errp);
7621bff9606SDaniel P. Berrange         if (!s->password) {
7631bff9606SDaniel P. Berrange             goto out_noclean;
7641bff9606SDaniel P. Berrange         }
7651bff9606SDaniel P. Berrange     }
7661bff9606SDaniel P. Berrange 
7671bff9606SDaniel P. Berrange     s->proxyusername = g_strdup(
7681bff9606SDaniel P. Berrange         qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_USERNAME));
7691bff9606SDaniel P. Berrange     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET);
7701bff9606SDaniel P. Berrange     if (secretid) {
7711bff9606SDaniel P. Berrange         s->proxypassword = qcrypto_secret_lookup_as_utf8(secretid, errp);
7721bff9606SDaniel P. Berrange         if (!s->proxypassword) {
7731bff9606SDaniel P. Berrange             goto out_noclean;
7741bff9606SDaniel P. Berrange         }
7751bff9606SDaniel P. Berrange     }
7761bff9606SDaniel P. Berrange 
777d0f2c4c6Smalc     DPRINTF("CURL: Opening %s\n", file);
778*709f2132SPaolo Bonzini     qemu_co_queue_init(&s->free_state_waitq);
77963f0f45fSStefan Hajnoczi     s->aio_context = bdrv_get_aio_context(bs);
7808e6d58cdSKevin Wolf     s->url = g_strdup(file);
781456af346SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
7823ce6a729SPaolo Bonzini     state = curl_find_state(s);
783456af346SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
7843ce6a729SPaolo Bonzini     if (!state) {
785769ce76dSAlexander Graf         goto out_noclean;
7863ce6a729SPaolo Bonzini     }
787769ce76dSAlexander Graf 
788769ce76dSAlexander Graf     // Get file size
789769ce76dSAlexander Graf 
7903ce6a729SPaolo Bonzini     if (curl_init_state(s, state) < 0) {
7913ce6a729SPaolo Bonzini         goto out;
7923ce6a729SPaolo Bonzini     }
7933ce6a729SPaolo Bonzini 
7943494d650SFam Zheng     s->accept_range = false;
795769ce76dSAlexander Graf     curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
7963494d650SFam Zheng     curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
7973494d650SFam Zheng                      curl_header_cb);
7983494d650SFam Zheng     curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
799769ce76dSAlexander Graf     if (curl_easy_perform(state->curl))
800769ce76dSAlexander Graf         goto out;
801a41c4578STomáš Golembiovský     if (curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) {
802769ce76dSAlexander Graf         goto out;
803a41c4578STomáš Golembiovský     }
804a41c4578STomáš Golembiovský     /* Prior CURL 7.19.4 return value of 0 could mean that the file size is not
805a41c4578STomáš Golembiovský      * know or the size is zero. From 7.19.4 CURL returns -1 if size is not
806a41c4578STomáš Golembiovský      * known and zero if it is realy zero-length file. */
807a41c4578STomáš Golembiovský #if LIBCURL_VERSION_NUM >= 0x071304
808a41c4578STomáš Golembiovský     if (d < 0) {
809a41c4578STomáš Golembiovský         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
810a41c4578STomáš Golembiovský                 "Server didn't report file size.");
811a41c4578STomáš Golembiovský         goto out;
812a41c4578STomáš Golembiovský     }
813a41c4578STomáš Golembiovský #else
814a41c4578STomáš Golembiovský     if (d <= 0) {
815a41c4578STomáš Golembiovský         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
816a41c4578STomáš Golembiovský                 "Unknown file size or zero-length file.");
817a41c4578STomáš Golembiovský         goto out;
818a41c4578STomáš Golembiovský     }
819a41c4578STomáš Golembiovský #endif
820a41c4578STomáš Golembiovský 
8212125e5eaSPaolo Bonzini     s->len = d;
822a41c4578STomáš Golembiovský 
8233494d650SFam Zheng     if ((!strncasecmp(s->url, "http://", strlen("http://"))
8243494d650SFam Zheng         || !strncasecmp(s->url, "https://", strlen("https://")))
8253494d650SFam Zheng         && !s->accept_range) {
8263494d650SFam Zheng         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
8273494d650SFam Zheng                 "Server does not support 'range' (byte ranges).");
8283494d650SFam Zheng         goto out;
8293494d650SFam Zheng     }
8302125e5eaSPaolo Bonzini     DPRINTF("CURL: Size = %" PRIu64 "\n", s->len);
831769ce76dSAlexander Graf 
832456af346SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
833769ce76dSAlexander Graf     curl_clean_state(state);
834456af346SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
835769ce76dSAlexander Graf     curl_easy_cleanup(state->curl);
836769ce76dSAlexander Graf     state->curl = NULL;
837769ce76dSAlexander Graf 
83863f0f45fSStefan Hajnoczi     curl_attach_aio_context(bs, bdrv_get_aio_context(bs));
839769ce76dSAlexander Graf 
8408e6d58cdSKevin Wolf     qemu_opts_del(opts);
841769ce76dSAlexander Graf     return 0;
842769ce76dSAlexander Graf 
843769ce76dSAlexander Graf out:
844acd7fdc6SMaria Kustova     error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
845769ce76dSAlexander Graf     curl_easy_cleanup(state->curl);
846769ce76dSAlexander Graf     state->curl = NULL;
847769ce76dSAlexander Graf out_noclean:
848456af346SPaolo Bonzini     qemu_mutex_destroy(&s->mutex);
849a94f83d9SRichard W.M. Jones     g_free(s->cookie);
8508e6d58cdSKevin Wolf     g_free(s->url);
851996922deSJeff Cody     g_free(s->username);
852996922deSJeff Cody     g_free(s->proxyusername);
853996922deSJeff Cody     g_free(s->proxypassword);
8548e6d58cdSKevin Wolf     qemu_opts_del(opts);
855769ce76dSAlexander Graf     return -EINVAL;
856769ce76dSAlexander Graf }
857769ce76dSAlexander Graf 
85828256d82SPaolo Bonzini static void curl_setup_preadv(BlockDriverState *bs, CURLAIOCB *acb)
859769ce76dSAlexander Graf {
860769ce76dSAlexander Graf     CURLState *state;
861b69cdef8SMatthew Booth     int running;
862769ce76dSAlexander Graf 
8631919631eSPaolo Bonzini     BDRVCURLState *s = bs->opaque;
864769ce76dSAlexander Graf 
8652125e5eaSPaolo Bonzini     uint64_t start = acb->offset;
8662125e5eaSPaolo Bonzini     uint64_t end;
867769ce76dSAlexander Graf 
868ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
8691919631eSPaolo Bonzini 
870769ce76dSAlexander Graf     // In case we have the requested data already (e.g. read-ahead),
871769ce76dSAlexander Graf     // we can just call the callback and be done.
87228256d82SPaolo Bonzini     if (curl_find_buf(s, start, acb->bytes, acb)) {
87334db05e7SPaolo Bonzini         goto out;
874769ce76dSAlexander Graf     }
875769ce76dSAlexander Graf 
876769ce76dSAlexander Graf     // No cache found, so let's start a new request
8773ce6a729SPaolo Bonzini     for (;;) {
8783ce6a729SPaolo Bonzini         state = curl_find_state(s);
8793ce6a729SPaolo Bonzini         if (state) {
8803ce6a729SPaolo Bonzini             break;
8813ce6a729SPaolo Bonzini         }
882*709f2132SPaolo Bonzini         qemu_co_queue_wait(&s->free_state_waitq, &s->mutex);
8833ce6a729SPaolo Bonzini     }
8843ce6a729SPaolo Bonzini 
8853ce6a729SPaolo Bonzini     if (curl_init_state(s, state) < 0) {
8863ce6a729SPaolo Bonzini         curl_clean_state(state);
88728256d82SPaolo Bonzini         acb->ret = -EIO;
8881919631eSPaolo Bonzini         goto out;
889363c3c85SNick Thomas     }
890769ce76dSAlexander Graf 
891769ce76dSAlexander Graf     acb->start = 0;
8922125e5eaSPaolo Bonzini     acb->end = MIN(acb->bytes, s->len - start);
893769ce76dSAlexander Graf 
894769ce76dSAlexander Graf     state->buf_off = 0;
8957267c094SAnthony Liguori     g_free(state->orig_buf);
896769ce76dSAlexander Graf     state->buf_start = start;
8974e504535SMax Reitz     state->buf_len = MIN(acb->end + s->readahead_size, s->len - start);
8984e504535SMax Reitz     end = start + state->buf_len - 1;
8998dc7a772SKevin Wolf     state->orig_buf = g_try_malloc(state->buf_len);
9008dc7a772SKevin Wolf     if (state->buf_len && state->orig_buf == NULL) {
9018dc7a772SKevin Wolf         curl_clean_state(state);
90228256d82SPaolo Bonzini         acb->ret = -ENOMEM;
9031919631eSPaolo Bonzini         goto out;
9048dc7a772SKevin Wolf     }
905769ce76dSAlexander Graf     state->acb[0] = acb;
906769ce76dSAlexander Graf 
9072125e5eaSPaolo Bonzini     snprintf(state->range, 127, "%" PRIu64 "-%" PRIu64, start, end);
9082125e5eaSPaolo Bonzini     DPRINTF("CURL (AIO): Reading %" PRIu64 " at %" PRIu64 " (%s)\n",
9092125e5eaSPaolo Bonzini             acb->bytes, start, state->range);
910769ce76dSAlexander Graf     curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
911769ce76dSAlexander Graf 
912769ce76dSAlexander Graf     curl_multi_add_handle(s->multi, state->curl);
913769ce76dSAlexander Graf 
914b69cdef8SMatthew Booth     /* Tell curl it needs to kick things off */
915b69cdef8SMatthew Booth     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
9161919631eSPaolo Bonzini 
9171919631eSPaolo Bonzini out:
918ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
919363c3c85SNick Thomas }
920363c3c85SNick Thomas 
92128256d82SPaolo Bonzini static int coroutine_fn curl_co_preadv(BlockDriverState *bs,
92228256d82SPaolo Bonzini         uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
923363c3c85SNick Thomas {
92428256d82SPaolo Bonzini     CURLAIOCB acb = {
92528256d82SPaolo Bonzini         .co = qemu_coroutine_self(),
92628256d82SPaolo Bonzini         .ret = -EINPROGRESS,
92728256d82SPaolo Bonzini         .qiov = qiov,
92828256d82SPaolo Bonzini         .offset = offset,
92928256d82SPaolo Bonzini         .bytes = bytes
93028256d82SPaolo Bonzini     };
931363c3c85SNick Thomas 
93228256d82SPaolo Bonzini     curl_setup_preadv(bs, &acb);
93328256d82SPaolo Bonzini     while (acb.ret == -EINPROGRESS) {
93428256d82SPaolo Bonzini         qemu_coroutine_yield();
93528256d82SPaolo Bonzini     }
93628256d82SPaolo Bonzini     return acb.ret;
937769ce76dSAlexander Graf }
938769ce76dSAlexander Graf 
939769ce76dSAlexander Graf static void curl_close(BlockDriverState *bs)
940769ce76dSAlexander Graf {
941769ce76dSAlexander Graf     BDRVCURLState *s = bs->opaque;
942769ce76dSAlexander Graf 
943d0f2c4c6Smalc     DPRINTF("CURL: Close\n");
94463f0f45fSStefan Hajnoczi     curl_detach_aio_context(bs);
945ba3186c4SPaolo Bonzini     qemu_mutex_destroy(&s->mutex);
946031fd1beSPeter Maydell 
947a94f83d9SRichard W.M. Jones     g_free(s->cookie);
94845724d6dSStefan Weil     g_free(s->url);
949996922deSJeff Cody     g_free(s->username);
950996922deSJeff Cody     g_free(s->proxyusername);
951996922deSJeff Cody     g_free(s->proxypassword);
952769ce76dSAlexander Graf }
953769ce76dSAlexander Graf 
954769ce76dSAlexander Graf static int64_t curl_getlength(BlockDriverState *bs)
955769ce76dSAlexander Graf {
956769ce76dSAlexander Graf     BDRVCURLState *s = bs->opaque;
957769ce76dSAlexander Graf     return s->len;
958769ce76dSAlexander Graf }
959769ce76dSAlexander Graf 
960769ce76dSAlexander Graf static BlockDriver bdrv_http = {
961769ce76dSAlexander Graf     .format_name                = "http",
962769ce76dSAlexander Graf     .protocol_name              = "http",
963769ce76dSAlexander Graf 
964769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
9658e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
96666f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
967769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
968769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
969769ce76dSAlexander Graf 
97028256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
97163f0f45fSStefan Hajnoczi 
97263f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
97363f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
974769ce76dSAlexander Graf };
975769ce76dSAlexander Graf 
976769ce76dSAlexander Graf static BlockDriver bdrv_https = {
977769ce76dSAlexander Graf     .format_name                = "https",
978769ce76dSAlexander Graf     .protocol_name              = "https",
979769ce76dSAlexander Graf 
980769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
9818e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
98266f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
983769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
984769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
985769ce76dSAlexander Graf 
98628256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
98763f0f45fSStefan Hajnoczi 
98863f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
98963f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
990769ce76dSAlexander Graf };
991769ce76dSAlexander Graf 
992769ce76dSAlexander Graf static BlockDriver bdrv_ftp = {
993769ce76dSAlexander Graf     .format_name                = "ftp",
994769ce76dSAlexander Graf     .protocol_name              = "ftp",
995769ce76dSAlexander Graf 
996769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
9978e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
99866f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
999769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
1000769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
1001769ce76dSAlexander Graf 
100228256d82SPaolo Bonzini     .bdrv_co_preadv             = curl_co_preadv,
100363f0f45fSStefan Hajnoczi 
100463f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
100563f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
1006769ce76dSAlexander Graf };
1007769ce76dSAlexander Graf 
1008769ce76dSAlexander Graf static BlockDriver bdrv_ftps = {
1009769ce76dSAlexander Graf     .format_name                = "ftps",
1010769ce76dSAlexander Graf     .protocol_name              = "ftps",
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,
1022769ce76dSAlexander Graf };
1023769ce76dSAlexander Graf 
1024769ce76dSAlexander Graf static void curl_block_init(void)
1025769ce76dSAlexander Graf {
1026769ce76dSAlexander Graf     bdrv_register(&bdrv_http);
1027769ce76dSAlexander Graf     bdrv_register(&bdrv_https);
1028769ce76dSAlexander Graf     bdrv_register(&bdrv_ftp);
1029769ce76dSAlexander Graf     bdrv_register(&bdrv_ftps);
1030769ce76dSAlexander Graf }
1031769ce76dSAlexander Graf 
1032769ce76dSAlexander Graf block_init(curl_block_init);
1033