xref: /openbmc/qemu/block/curl.c (revision 34db05e7)
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 
79769ce76dSAlexander Graf #define FIND_RET_NONE   0
80769ce76dSAlexander Graf #define FIND_RET_OK     1
81769ce76dSAlexander Graf #define FIND_RET_WAIT   2
82769ce76dSAlexander Graf 
83e3542c67SMatthew Booth #define CURL_BLOCK_OPT_URL       "url"
84e3542c67SMatthew Booth #define CURL_BLOCK_OPT_READAHEAD "readahead"
8597a3ea57SMatthew Booth #define CURL_BLOCK_OPT_SSLVERIFY "sslverify"
86212aefaaSDaniel Henrique Barboza #define CURL_BLOCK_OPT_TIMEOUT "timeout"
87a94f83d9SRichard W.M. Jones #define CURL_BLOCK_OPT_COOKIE    "cookie"
88327c8ebdSPeter Krempa #define CURL_BLOCK_OPT_COOKIE_SECRET "cookie-secret"
891bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_USERNAME "username"
901bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PASSWORD_SECRET "password-secret"
911bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PROXY_USERNAME "proxy-username"
921bff9606SDaniel P. Berrange #define CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET "proxy-password-secret"
93e3542c67SMatthew Booth 
94769ce76dSAlexander Graf struct BDRVCURLState;
95769ce76dSAlexander Graf 
96769ce76dSAlexander Graf typedef struct CURLAIOCB {
977c84b1b8SMarkus Armbruster     BlockAIOCB common;
98769ce76dSAlexander Graf     QEMUIOVector *qiov;
99363c3c85SNick Thomas 
100363c3c85SNick Thomas     int64_t sector_num;
101363c3c85SNick Thomas     int nb_sectors;
102363c3c85SNick Thomas 
103769ce76dSAlexander Graf     size_t start;
104769ce76dSAlexander Graf     size_t end;
105769ce76dSAlexander Graf } CURLAIOCB;
106769ce76dSAlexander Graf 
107ff5ca166SMax Reitz typedef struct CURLSocket {
108ff5ca166SMax Reitz     int fd;
109ff5ca166SMax Reitz     QLIST_ENTRY(CURLSocket) next;
110ff5ca166SMax Reitz } CURLSocket;
111ff5ca166SMax Reitz 
112769ce76dSAlexander Graf typedef struct CURLState
113769ce76dSAlexander Graf {
114769ce76dSAlexander Graf     struct BDRVCURLState *s;
115769ce76dSAlexander Graf     CURLAIOCB *acb[CURL_NUM_ACB];
116769ce76dSAlexander Graf     CURL *curl;
117ff5ca166SMax Reitz     QLIST_HEAD(, CURLSocket) sockets;
118769ce76dSAlexander Graf     char *orig_buf;
119769ce76dSAlexander Graf     size_t buf_start;
120769ce76dSAlexander Graf     size_t buf_off;
121769ce76dSAlexander Graf     size_t buf_len;
122769ce76dSAlexander Graf     char range[128];
123769ce76dSAlexander Graf     char errmsg[CURL_ERROR_SIZE];
124769ce76dSAlexander Graf     char in_use;
125769ce76dSAlexander Graf } CURLState;
126769ce76dSAlexander Graf 
127769ce76dSAlexander Graf typedef struct BDRVCURLState {
128769ce76dSAlexander Graf     CURLM *multi;
129031fd1beSPeter Maydell     QEMUTimer timer;
130769ce76dSAlexander Graf     size_t len;
131769ce76dSAlexander Graf     CURLState states[CURL_NUM_STATES];
132769ce76dSAlexander Graf     char *url;
133c76f4952SNolan     size_t readahead_size;
13497a3ea57SMatthew Booth     bool sslverify;
135f76faedaSRichard W.M. Jones     uint64_t timeout;
136a94f83d9SRichard W.M. Jones     char *cookie;
1373494d650SFam Zheng     bool accept_range;
13863f0f45fSStefan Hajnoczi     AioContext *aio_context;
139ba3186c4SPaolo Bonzini     QemuMutex mutex;
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
151*34db05e7SPaolo 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 
168*34db05e7SPaolo 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 
218*34db05e7SPaolo 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 
233*34db05e7SPaolo 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)) {
2614e504535SMax Reitz             size_t request_length = acb->nb_sectors * BDRV_SECTOR_SIZE;
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 
272*34db05e7SPaolo Bonzini             qemu_mutex_unlock(&s->s->mutex);
273769ce76dSAlexander Graf             acb->common.cb(acb->common.opaque, 0);
274*34db05e7SPaolo Bonzini             qemu_mutex_lock(&s->s->mutex);
2758007429aSFam Zheng             qemu_aio_unref(acb);
276769ce76dSAlexander Graf             s->acb[i] = NULL;
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 
285769ce76dSAlexander Graf static int curl_find_buf(BDRVCURLState *s, size_t start, size_t len,
286769ce76dSAlexander Graf                          CURLAIOCB *acb)
287769ce76dSAlexander Graf {
288769ce76dSAlexander Graf     int i;
289769ce76dSAlexander Graf     size_t end = start + len;
2904e504535SMax Reitz     size_t clamped_end = MIN(end, s->len);
2914e504535SMax Reitz     size_t clamped_len = clamped_end - start;
292769ce76dSAlexander Graf 
293769ce76dSAlexander Graf     for (i=0; i<CURL_NUM_STATES; i++) {
294769ce76dSAlexander Graf         CURLState *state = &s->states[i];
295769ce76dSAlexander Graf         size_t buf_end = (state->buf_start + state->buf_off);
296769ce76dSAlexander Graf         size_t buf_fend = (state->buf_start + state->buf_len);
297769ce76dSAlexander Graf 
298769ce76dSAlexander Graf         if (!state->orig_buf)
299769ce76dSAlexander Graf             continue;
300769ce76dSAlexander Graf         if (!state->buf_off)
301769ce76dSAlexander Graf             continue;
302769ce76dSAlexander Graf 
303769ce76dSAlexander Graf         // Does the existing buffer cover our section?
304769ce76dSAlexander Graf         if ((start >= state->buf_start) &&
305769ce76dSAlexander Graf             (start <= buf_end) &&
3064e504535SMax Reitz             (clamped_end >= state->buf_start) &&
3074e504535SMax Reitz             (clamped_end <= buf_end))
308769ce76dSAlexander Graf         {
309769ce76dSAlexander Graf             char *buf = state->orig_buf + (start - state->buf_start);
310769ce76dSAlexander Graf 
3114e504535SMax Reitz             qemu_iovec_from_buf(acb->qiov, 0, buf, clamped_len);
3124e504535SMax Reitz             if (clamped_len < len) {
3134e504535SMax Reitz                 qemu_iovec_memset(acb->qiov, clamped_len, 0, len - clamped_len);
3144e504535SMax Reitz             }
315769ce76dSAlexander Graf             return FIND_RET_OK;
316769ce76dSAlexander Graf         }
317769ce76dSAlexander Graf 
318769ce76dSAlexander Graf         // Wait for unfinished chunks
319b7079df4SMatthew Booth         if (state->in_use &&
320b7079df4SMatthew Booth             (start >= state->buf_start) &&
321769ce76dSAlexander Graf             (start <= buf_fend) &&
3224e504535SMax Reitz             (clamped_end >= state->buf_start) &&
3234e504535SMax Reitz             (clamped_end <= buf_fend))
324769ce76dSAlexander Graf         {
325769ce76dSAlexander Graf             int j;
326769ce76dSAlexander Graf 
327769ce76dSAlexander Graf             acb->start = start - state->buf_start;
3284e504535SMax Reitz             acb->end = acb->start + clamped_len;
329769ce76dSAlexander Graf 
330769ce76dSAlexander Graf             for (j=0; j<CURL_NUM_ACB; j++) {
331769ce76dSAlexander Graf                 if (!state->acb[j]) {
332769ce76dSAlexander Graf                     state->acb[j] = acb;
333769ce76dSAlexander Graf                     return FIND_RET_WAIT;
334769ce76dSAlexander Graf                 }
335769ce76dSAlexander Graf             }
336769ce76dSAlexander Graf         }
337769ce76dSAlexander Graf     }
338769ce76dSAlexander Graf 
339769ce76dSAlexander Graf     return FIND_RET_NONE;
340769ce76dSAlexander Graf }
341769ce76dSAlexander Graf 
342ba3186c4SPaolo Bonzini /* Called with s->mutex held.  */
343838ef602SMatthew Booth static void curl_multi_check_completion(BDRVCURLState *s)
344769ce76dSAlexander Graf {
345769ce76dSAlexander Graf     int msgs_in_queue;
346769ce76dSAlexander Graf 
347769ce76dSAlexander Graf     /* Try to find done transfers, so we can free the easy
348769ce76dSAlexander Graf      * handle again. */
3491f2cead3SMatthew Booth     for (;;) {
350769ce76dSAlexander Graf         CURLMsg *msg;
351769ce76dSAlexander Graf         msg = curl_multi_info_read(s->multi, &msgs_in_queue);
352769ce76dSAlexander Graf 
3531f2cead3SMatthew Booth         /* Quit when there are no more completions */
354769ce76dSAlexander Graf         if (!msg)
355769ce76dSAlexander Graf             break;
356769ce76dSAlexander Graf 
3571f2cead3SMatthew Booth         if (msg->msg == CURLMSG_DONE) {
358769ce76dSAlexander Graf             CURLState *state = NULL;
359f6246509SMatthew Booth             curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,
360f6246509SMatthew Booth                               (char **)&state);
361f785a5aeSNicholas Thomas 
362f785a5aeSNicholas Thomas             /* ACBs for successful messages get completed in curl_read_cb */
363f785a5aeSNicholas Thomas             if (msg->data.result != CURLE_OK) {
364f785a5aeSNicholas Thomas                 int i;
365796a060bSRichard W.M. Jones                 static int errcount = 100;
366796a060bSRichard W.M. Jones 
367796a060bSRichard W.M. Jones                 /* Don't lose the original error message from curl, since
368796a060bSRichard W.M. Jones                  * it contains extra data.
369796a060bSRichard W.M. Jones                  */
370796a060bSRichard W.M. Jones                 if (errcount > 0) {
371796a060bSRichard W.M. Jones                     error_report("curl: %s", state->errmsg);
372796a060bSRichard W.M. Jones                     if (--errcount == 0) {
373796a060bSRichard W.M. Jones                         error_report("curl: further errors suppressed");
374796a060bSRichard W.M. Jones                     }
375796a060bSRichard W.M. Jones                 }
376796a060bSRichard W.M. Jones 
377f785a5aeSNicholas Thomas                 for (i = 0; i < CURL_NUM_ACB; i++) {
378f785a5aeSNicholas Thomas                     CURLAIOCB *acb = state->acb[i];
379f785a5aeSNicholas Thomas 
380f785a5aeSNicholas Thomas                     if (acb == NULL) {
381f785a5aeSNicholas Thomas                         continue;
382f785a5aeSNicholas Thomas                     }
383f785a5aeSNicholas Thomas 
384ba3186c4SPaolo Bonzini                     qemu_mutex_unlock(&s->mutex);
385eb048026SPaolo Bonzini                     acb->common.cb(acb->common.opaque, -EIO);
386ba3186c4SPaolo Bonzini                     qemu_mutex_lock(&s->mutex);
3878007429aSFam Zheng                     qemu_aio_unref(acb);
388f785a5aeSNicholas Thomas                     state->acb[i] = NULL;
389f785a5aeSNicholas Thomas                 }
390f785a5aeSNicholas Thomas             }
391f785a5aeSNicholas Thomas 
392769ce76dSAlexander Graf             curl_clean_state(state);
393769ce76dSAlexander Graf             break;
394769ce76dSAlexander Graf         }
395769ce76dSAlexander Graf     }
396769ce76dSAlexander Graf }
397769ce76dSAlexander Graf 
398ba3186c4SPaolo Bonzini /* Called with s->mutex held.  */
3999d456654SPaolo Bonzini static void curl_multi_do_locked(CURLState *s)
400031fd1beSPeter Maydell {
401ff5ca166SMax Reitz     CURLSocket *socket, *next_socket;
402031fd1beSPeter Maydell     int running;
403031fd1beSPeter Maydell     int r;
404031fd1beSPeter Maydell 
405838ef602SMatthew Booth     if (!s->s->multi) {
406031fd1beSPeter Maydell         return;
407031fd1beSPeter Maydell     }
408031fd1beSPeter Maydell 
409ff5ca166SMax Reitz     /* Need to use _SAFE because curl_multi_socket_action() may trigger
410ff5ca166SMax Reitz      * curl_sock_cb() which might modify this list */
411ff5ca166SMax Reitz     QLIST_FOREACH_SAFE(socket, &s->sockets, next, next_socket) {
412031fd1beSPeter Maydell         do {
413ff5ca166SMax Reitz             r = curl_multi_socket_action(s->s->multi, socket->fd, 0, &running);
414031fd1beSPeter Maydell         } while (r == CURLM_CALL_MULTI_PERFORM);
415ff5ca166SMax Reitz     }
416838ef602SMatthew Booth }
417838ef602SMatthew Booth 
4189d456654SPaolo Bonzini static void curl_multi_do(void *arg)
4199d456654SPaolo Bonzini {
4209d456654SPaolo Bonzini     CURLState *s = (CURLState *)arg;
4219d456654SPaolo Bonzini 
422ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->s->mutex);
4239d456654SPaolo Bonzini     curl_multi_do_locked(s);
424ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->s->mutex);
4259d456654SPaolo Bonzini }
4269d456654SPaolo Bonzini 
427838ef602SMatthew Booth static void curl_multi_read(void *arg)
428838ef602SMatthew Booth {
429838ef602SMatthew Booth     CURLState *s = (CURLState *)arg;
430838ef602SMatthew Booth 
431ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->s->mutex);
4329d456654SPaolo Bonzini     curl_multi_do_locked(s);
433838ef602SMatthew Booth     curl_multi_check_completion(s->s);
434ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->s->mutex);
435031fd1beSPeter Maydell }
436031fd1beSPeter Maydell 
437031fd1beSPeter Maydell static void curl_multi_timeout_do(void *arg)
438031fd1beSPeter Maydell {
439031fd1beSPeter Maydell #ifdef NEED_CURL_TIMER_CALLBACK
440031fd1beSPeter Maydell     BDRVCURLState *s = (BDRVCURLState *)arg;
441031fd1beSPeter Maydell     int running;
442031fd1beSPeter Maydell 
443031fd1beSPeter Maydell     if (!s->multi) {
444031fd1beSPeter Maydell         return;
445031fd1beSPeter Maydell     }
446031fd1beSPeter Maydell 
447ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
448031fd1beSPeter Maydell     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
449031fd1beSPeter Maydell 
450838ef602SMatthew Booth     curl_multi_check_completion(s);
451ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
452031fd1beSPeter Maydell #else
453031fd1beSPeter Maydell     abort();
454031fd1beSPeter Maydell #endif
455031fd1beSPeter Maydell }
456031fd1beSPeter Maydell 
457a2f468e4SRichard W.M. Jones static CURLState *curl_init_state(BlockDriverState *bs, BDRVCURLState *s)
458769ce76dSAlexander Graf {
459769ce76dSAlexander Graf     CURLState *state = NULL;
460769ce76dSAlexander Graf     int i, j;
461769ce76dSAlexander Graf 
462769ce76dSAlexander Graf     do {
463769ce76dSAlexander Graf         for (i=0; i<CURL_NUM_STATES; i++) {
464769ce76dSAlexander Graf             for (j=0; j<CURL_NUM_ACB; j++)
465769ce76dSAlexander Graf                 if (s->states[i].acb[j])
466769ce76dSAlexander Graf                     continue;
467769ce76dSAlexander Graf             if (s->states[i].in_use)
468769ce76dSAlexander Graf                 continue;
469769ce76dSAlexander Graf 
470769ce76dSAlexander Graf             state = &s->states[i];
471769ce76dSAlexander Graf             state->in_use = 1;
472769ce76dSAlexander Graf             break;
473769ce76dSAlexander Graf         }
474769ce76dSAlexander Graf         if (!state) {
475a2f468e4SRichard W.M. Jones             aio_poll(bdrv_get_aio_context(bs), true);
476769ce76dSAlexander Graf         }
477769ce76dSAlexander Graf     } while(!state);
478769ce76dSAlexander Graf 
4799e550b32SMatthew Booth     if (!state->curl) {
480769ce76dSAlexander Graf         state->curl = curl_easy_init();
4819e550b32SMatthew Booth         if (!state->curl) {
482769ce76dSAlexander Graf             return NULL;
4839e550b32SMatthew Booth         }
484769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
48597a3ea57SMatthew Booth         curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,
48697a3ea57SMatthew Booth                          (long) s->sslverify);
487a94f83d9SRichard W.M. Jones         if (s->cookie) {
488a94f83d9SRichard W.M. Jones             curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);
489a94f83d9SRichard W.M. Jones         }
490f76faedaSRichard W.M. Jones         curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);
4919e550b32SMatthew Booth         curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,
4929e550b32SMatthew Booth                          (void *)curl_read_cb);
493769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
494769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
495769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
496769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
497769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
498769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
499f785a5aeSNicholas Thomas         curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
500769ce76dSAlexander Graf 
5011bff9606SDaniel P. Berrange         if (s->username) {
5021bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);
5031bff9606SDaniel P. Berrange         }
5041bff9606SDaniel P. Berrange         if (s->password) {
5051bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);
5061bff9606SDaniel P. Berrange         }
5071bff9606SDaniel P. Berrange         if (s->proxyusername) {
5081bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl,
5091bff9606SDaniel P. Berrange                              CURLOPT_PROXYUSERNAME, s->proxyusername);
5101bff9606SDaniel P. Berrange         }
5111bff9606SDaniel P. Berrange         if (s->proxypassword) {
5121bff9606SDaniel P. Berrange             curl_easy_setopt(state->curl,
5131bff9606SDaniel P. Berrange                              CURLOPT_PROXYPASSWORD, s->proxypassword);
5141bff9606SDaniel P. Berrange         }
5151bff9606SDaniel P. Berrange 
516fb6d1bbdSStefan Hajnoczi         /* Restrict supported protocols to avoid security issues in the more
517fb6d1bbdSStefan Hajnoczi          * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see
518fb6d1bbdSStefan Hajnoczi          * CVE-2013-0249.
5198a8f5840SStefan Hajnoczi          *
5208a8f5840SStefan Hajnoczi          * Restricting protocols is only supported from 7.19.4 upwards.
521fb6d1bbdSStefan Hajnoczi          */
5228a8f5840SStefan Hajnoczi #if LIBCURL_VERSION_NUM >= 0x071304
523fb6d1bbdSStefan Hajnoczi         curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
524fb6d1bbdSStefan Hajnoczi         curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
5258a8f5840SStefan Hajnoczi #endif
526fb6d1bbdSStefan Hajnoczi 
527769ce76dSAlexander Graf #ifdef DEBUG_VERBOSE
528769ce76dSAlexander Graf         curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
529769ce76dSAlexander Graf #endif
5309e550b32SMatthew Booth     }
531769ce76dSAlexander Graf 
532ff5ca166SMax Reitz     QLIST_INIT(&state->sockets);
533769ce76dSAlexander Graf     state->s = s;
534769ce76dSAlexander Graf 
535769ce76dSAlexander Graf     return state;
536769ce76dSAlexander Graf }
537769ce76dSAlexander Graf 
538769ce76dSAlexander Graf static void curl_clean_state(CURLState *s)
539769ce76dSAlexander Graf {
540675a7756SPaolo Bonzini     int j;
541675a7756SPaolo Bonzini     for (j = 0; j < CURL_NUM_ACB; j++) {
542675a7756SPaolo Bonzini         assert(!s->acb[j]);
543675a7756SPaolo Bonzini     }
544675a7756SPaolo Bonzini 
545769ce76dSAlexander Graf     if (s->s->multi)
546769ce76dSAlexander Graf         curl_multi_remove_handle(s->s->multi, s->curl);
547ff5ca166SMax Reitz 
548ff5ca166SMax Reitz     while (!QLIST_EMPTY(&s->sockets)) {
549ff5ca166SMax Reitz         CURLSocket *socket = QLIST_FIRST(&s->sockets);
550ff5ca166SMax Reitz 
551ff5ca166SMax Reitz         QLIST_REMOVE(socket, next);
552ff5ca166SMax Reitz         g_free(socket);
553ff5ca166SMax Reitz     }
554ff5ca166SMax Reitz 
555769ce76dSAlexander Graf     s->in_use = 0;
556769ce76dSAlexander Graf }
557769ce76dSAlexander Graf 
5588e6d58cdSKevin Wolf static void curl_parse_filename(const char *filename, QDict *options,
5598e6d58cdSKevin Wolf                                 Error **errp)
560769ce76dSAlexander Graf {
56146f5ac20SEric Blake     qdict_put_str(options, CURL_BLOCK_OPT_URL, filename);
5628e6d58cdSKevin Wolf }
5638e6d58cdSKevin Wolf 
56463f0f45fSStefan Hajnoczi static void curl_detach_aio_context(BlockDriverState *bs)
56563f0f45fSStefan Hajnoczi {
56663f0f45fSStefan Hajnoczi     BDRVCURLState *s = bs->opaque;
56763f0f45fSStefan Hajnoczi     int i;
56863f0f45fSStefan Hajnoczi 
56963f0f45fSStefan Hajnoczi     for (i = 0; i < CURL_NUM_STATES; i++) {
57063f0f45fSStefan Hajnoczi         if (s->states[i].in_use) {
57163f0f45fSStefan Hajnoczi             curl_clean_state(&s->states[i]);
57263f0f45fSStefan Hajnoczi         }
57363f0f45fSStefan Hajnoczi         if (s->states[i].curl) {
57463f0f45fSStefan Hajnoczi             curl_easy_cleanup(s->states[i].curl);
57563f0f45fSStefan Hajnoczi             s->states[i].curl = NULL;
57663f0f45fSStefan Hajnoczi         }
57763f0f45fSStefan Hajnoczi         g_free(s->states[i].orig_buf);
57863f0f45fSStefan Hajnoczi         s->states[i].orig_buf = NULL;
57963f0f45fSStefan Hajnoczi     }
58063f0f45fSStefan Hajnoczi     if (s->multi) {
58163f0f45fSStefan Hajnoczi         curl_multi_cleanup(s->multi);
58263f0f45fSStefan Hajnoczi         s->multi = NULL;
58363f0f45fSStefan Hajnoczi     }
58463f0f45fSStefan Hajnoczi 
58563f0f45fSStefan Hajnoczi     timer_del(&s->timer);
58663f0f45fSStefan Hajnoczi }
58763f0f45fSStefan Hajnoczi 
58863f0f45fSStefan Hajnoczi static void curl_attach_aio_context(BlockDriverState *bs,
58963f0f45fSStefan Hajnoczi                                     AioContext *new_context)
59063f0f45fSStefan Hajnoczi {
59163f0f45fSStefan Hajnoczi     BDRVCURLState *s = bs->opaque;
59263f0f45fSStefan Hajnoczi 
59363f0f45fSStefan Hajnoczi     aio_timer_init(new_context, &s->timer,
59463f0f45fSStefan Hajnoczi                    QEMU_CLOCK_REALTIME, SCALE_NS,
59563f0f45fSStefan Hajnoczi                    curl_multi_timeout_do, s);
59663f0f45fSStefan Hajnoczi 
59763f0f45fSStefan Hajnoczi     assert(!s->multi);
59863f0f45fSStefan Hajnoczi     s->multi = curl_multi_init();
59963f0f45fSStefan Hajnoczi     s->aio_context = new_context;
60063f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
60163f0f45fSStefan Hajnoczi #ifdef NEED_CURL_TIMER_CALLBACK
60263f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
60363f0f45fSStefan Hajnoczi     curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
60463f0f45fSStefan Hajnoczi #endif
60563f0f45fSStefan Hajnoczi }
60663f0f45fSStefan Hajnoczi 
6078e6d58cdSKevin Wolf static QemuOptsList runtime_opts = {
6088e6d58cdSKevin Wolf     .name = "curl",
6098e6d58cdSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
6108e6d58cdSKevin Wolf     .desc = {
6118e6d58cdSKevin Wolf         {
612e3542c67SMatthew Booth             .name = CURL_BLOCK_OPT_URL,
6138e6d58cdSKevin Wolf             .type = QEMU_OPT_STRING,
6148e6d58cdSKevin Wolf             .help = "URL to open",
6158e6d58cdSKevin Wolf         },
6168e6d58cdSKevin Wolf         {
617e3542c67SMatthew Booth             .name = CURL_BLOCK_OPT_READAHEAD,
6188e6d58cdSKevin Wolf             .type = QEMU_OPT_SIZE,
6198e6d58cdSKevin Wolf             .help = "Readahead size",
6208e6d58cdSKevin Wolf         },
62197a3ea57SMatthew Booth         {
62297a3ea57SMatthew Booth             .name = CURL_BLOCK_OPT_SSLVERIFY,
62397a3ea57SMatthew Booth             .type = QEMU_OPT_BOOL,
62497a3ea57SMatthew Booth             .help = "Verify SSL certificate"
62597a3ea57SMatthew Booth         },
626212aefaaSDaniel Henrique Barboza         {
627212aefaaSDaniel Henrique Barboza             .name = CURL_BLOCK_OPT_TIMEOUT,
628212aefaaSDaniel Henrique Barboza             .type = QEMU_OPT_NUMBER,
629212aefaaSDaniel Henrique Barboza             .help = "Curl timeout"
630212aefaaSDaniel Henrique Barboza         },
631a94f83d9SRichard W.M. Jones         {
632a94f83d9SRichard W.M. Jones             .name = CURL_BLOCK_OPT_COOKIE,
633a94f83d9SRichard W.M. Jones             .type = QEMU_OPT_STRING,
634a94f83d9SRichard W.M. Jones             .help = "Pass the cookie or list of cookies with each request"
635a94f83d9SRichard W.M. Jones         },
6361bff9606SDaniel P. Berrange         {
637327c8ebdSPeter Krempa             .name = CURL_BLOCK_OPT_COOKIE_SECRET,
638327c8ebdSPeter Krempa             .type = QEMU_OPT_STRING,
639327c8ebdSPeter Krempa             .help = "ID of secret used as cookie passed with each request"
640327c8ebdSPeter Krempa         },
641327c8ebdSPeter Krempa         {
6421bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_USERNAME,
6431bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6441bff9606SDaniel P. Berrange             .help = "Username for HTTP auth"
6451bff9606SDaniel P. Berrange         },
6461bff9606SDaniel P. Berrange         {
6471bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PASSWORD_SECRET,
6481bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6491bff9606SDaniel P. Berrange             .help = "ID of secret used as password for HTTP auth",
6501bff9606SDaniel P. Berrange         },
6511bff9606SDaniel P. Berrange         {
6521bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PROXY_USERNAME,
6531bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6541bff9606SDaniel P. Berrange             .help = "Username for HTTP proxy auth"
6551bff9606SDaniel P. Berrange         },
6561bff9606SDaniel P. Berrange         {
6571bff9606SDaniel P. Berrange             .name = CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
6581bff9606SDaniel P. Berrange             .type = QEMU_OPT_STRING,
6591bff9606SDaniel P. Berrange             .help = "ID of secret used as password for HTTP proxy auth",
6601bff9606SDaniel P. Berrange         },
6618e6d58cdSKevin Wolf         { /* end of list */ }
6628e6d58cdSKevin Wolf     },
6638e6d58cdSKevin Wolf };
6648e6d58cdSKevin Wolf 
6651bff9606SDaniel P. Berrange 
666015a1036SMax Reitz static int curl_open(BlockDriverState *bs, QDict *options, int flags,
667015a1036SMax Reitz                      Error **errp)
6688e6d58cdSKevin Wolf {
6698e6d58cdSKevin Wolf     BDRVCURLState *s = bs->opaque;
6708e6d58cdSKevin Wolf     CURLState *state = NULL;
6718e6d58cdSKevin Wolf     QemuOpts *opts;
6728e6d58cdSKevin Wolf     Error *local_err = NULL;
6738e6d58cdSKevin Wolf     const char *file;
674a94f83d9SRichard W.M. Jones     const char *cookie;
675327c8ebdSPeter Krempa     const char *cookie_secret;
6768e6d58cdSKevin Wolf     double d;
6771bff9606SDaniel P. Berrange     const char *secretid;
67834634ca2SMax Reitz     const char *protocol_delimiter;
6798e6d58cdSKevin Wolf 
6808e6d58cdSKevin Wolf     static int inited = 0;
6818e6d58cdSKevin Wolf 
682a7cea2baSRichard W.M. Jones     if (flags & BDRV_O_RDWR) {
6832a94fee3SPaolo Bonzini         error_setg(errp, "curl block device does not support writes");
684a7cea2baSRichard W.M. Jones         return -EROFS;
685a7cea2baSRichard W.M. Jones     }
686a7cea2baSRichard W.M. Jones 
68787ea75d5SPeter Crosthwaite     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
6888e6d58cdSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
68984d18f06SMarkus Armbruster     if (local_err) {
6902a94fee3SPaolo Bonzini         error_propagate(errp, local_err);
6918e6d58cdSKevin Wolf         goto out_noclean;
6928e6d58cdSKevin Wolf     }
6938e6d58cdSKevin Wolf 
694e3542c67SMatthew Booth     s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
695e3542c67SMatthew Booth                                           READ_AHEAD_DEFAULT);
696c76f4952SNolan     if ((s->readahead_size & 0x1ff) != 0) {
6972a94fee3SPaolo Bonzini         error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
698c76f4952SNolan                    s->readahead_size);
699c76f4952SNolan         goto out_noclean;
700c76f4952SNolan     }
701c76f4952SNolan 
702212aefaaSDaniel Henrique Barboza     s->timeout = qemu_opt_get_number(opts, CURL_BLOCK_OPT_TIMEOUT,
703212aefaaSDaniel Henrique Barboza                                      CURL_TIMEOUT_DEFAULT);
704f76faedaSRichard W.M. Jones     if (s->timeout > CURL_TIMEOUT_MAX) {
705f76faedaSRichard W.M. Jones         error_setg(errp, "timeout parameter is too large or negative");
706f76faedaSRichard W.M. Jones         goto out_noclean;
707f76faedaSRichard W.M. Jones     }
708212aefaaSDaniel Henrique Barboza 
70997a3ea57SMatthew Booth     s->sslverify = qemu_opt_get_bool(opts, CURL_BLOCK_OPT_SSLVERIFY, true);
71097a3ea57SMatthew Booth 
711a94f83d9SRichard W.M. Jones     cookie = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE);
712327c8ebdSPeter Krempa     cookie_secret = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE_SECRET);
713327c8ebdSPeter Krempa 
714327c8ebdSPeter Krempa     if (cookie && cookie_secret) {
715327c8ebdSPeter Krempa         error_setg(errp,
716327c8ebdSPeter Krempa                    "curl driver cannot handle both cookie and cookie secret");
717327c8ebdSPeter Krempa         goto out_noclean;
718327c8ebdSPeter Krempa     }
719327c8ebdSPeter Krempa 
720327c8ebdSPeter Krempa     if (cookie_secret) {
721327c8ebdSPeter Krempa         s->cookie = qcrypto_secret_lookup_as_utf8(cookie_secret, errp);
722327c8ebdSPeter Krempa         if (!s->cookie) {
723327c8ebdSPeter Krempa             goto out_noclean;
724327c8ebdSPeter Krempa         }
725327c8ebdSPeter Krempa     } else {
726a94f83d9SRichard W.M. Jones         s->cookie = g_strdup(cookie);
727327c8ebdSPeter Krempa     }
728a94f83d9SRichard W.M. Jones 
729e3542c67SMatthew Booth     file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
7308e6d58cdSKevin Wolf     if (file == NULL) {
7312a94fee3SPaolo Bonzini         error_setg(errp, "curl block driver requires an 'url' option");
7328e6d58cdSKevin Wolf         goto out_noclean;
7338e6d58cdSKevin Wolf     }
7348e6d58cdSKevin Wolf 
73534634ca2SMax Reitz     if (!strstart(file, bs->drv->protocol_name, &protocol_delimiter) ||
73634634ca2SMax Reitz         !strstart(protocol_delimiter, "://", NULL))
73734634ca2SMax Reitz     {
73834634ca2SMax Reitz         error_setg(errp, "%s curl driver cannot handle the URL '%s' (does not "
73934634ca2SMax Reitz                    "start with '%s://')", bs->drv->protocol_name, file,
74034634ca2SMax Reitz                    bs->drv->protocol_name);
74134634ca2SMax Reitz         goto out_noclean;
74234634ca2SMax Reitz     }
74334634ca2SMax Reitz 
7441bff9606SDaniel P. Berrange     s->username = g_strdup(qemu_opt_get(opts, CURL_BLOCK_OPT_USERNAME));
7451bff9606SDaniel P. Berrange     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PASSWORD_SECRET);
7461bff9606SDaniel P. Berrange 
7471bff9606SDaniel P. Berrange     if (secretid) {
7481bff9606SDaniel P. Berrange         s->password = qcrypto_secret_lookup_as_utf8(secretid, errp);
7491bff9606SDaniel P. Berrange         if (!s->password) {
7501bff9606SDaniel P. Berrange             goto out_noclean;
7511bff9606SDaniel P. Berrange         }
7521bff9606SDaniel P. Berrange     }
7531bff9606SDaniel P. Berrange 
7541bff9606SDaniel P. Berrange     s->proxyusername = g_strdup(
7551bff9606SDaniel P. Berrange         qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_USERNAME));
7561bff9606SDaniel P. Berrange     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET);
7571bff9606SDaniel P. Berrange     if (secretid) {
7581bff9606SDaniel P. Berrange         s->proxypassword = qcrypto_secret_lookup_as_utf8(secretid, errp);
7591bff9606SDaniel P. Berrange         if (!s->proxypassword) {
7601bff9606SDaniel P. Berrange             goto out_noclean;
7611bff9606SDaniel P. Berrange         }
7621bff9606SDaniel P. Berrange     }
7631bff9606SDaniel P. Berrange 
764769ce76dSAlexander Graf     if (!inited) {
765769ce76dSAlexander Graf         curl_global_init(CURL_GLOBAL_ALL);
766769ce76dSAlexander Graf         inited = 1;
767769ce76dSAlexander Graf     }
768769ce76dSAlexander Graf 
769d0f2c4c6Smalc     DPRINTF("CURL: Opening %s\n", file);
77063f0f45fSStefan Hajnoczi     s->aio_context = bdrv_get_aio_context(bs);
7718e6d58cdSKevin Wolf     s->url = g_strdup(file);
772a2f468e4SRichard W.M. Jones     state = curl_init_state(bs, s);
773769ce76dSAlexander Graf     if (!state)
774769ce76dSAlexander Graf         goto out_noclean;
775769ce76dSAlexander Graf 
776769ce76dSAlexander Graf     // Get file size
777769ce76dSAlexander Graf 
7783494d650SFam Zheng     s->accept_range = false;
779769ce76dSAlexander Graf     curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
7803494d650SFam Zheng     curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
7813494d650SFam Zheng                      curl_header_cb);
7823494d650SFam Zheng     curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
783769ce76dSAlexander Graf     if (curl_easy_perform(state->curl))
784769ce76dSAlexander Graf         goto out;
785a41c4578STomáš Golembiovský     if (curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) {
786769ce76dSAlexander Graf         goto out;
787a41c4578STomáš Golembiovský     }
788a41c4578STomáš Golembiovský     /* Prior CURL 7.19.4 return value of 0 could mean that the file size is not
789a41c4578STomáš Golembiovský      * know or the size is zero. From 7.19.4 CURL returns -1 if size is not
790a41c4578STomáš Golembiovský      * known and zero if it is realy zero-length file. */
791a41c4578STomáš Golembiovský #if LIBCURL_VERSION_NUM >= 0x071304
792a41c4578STomáš Golembiovský     if (d < 0) {
793a41c4578STomáš Golembiovský         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
794a41c4578STomáš Golembiovský                 "Server didn't report file size.");
795a41c4578STomáš Golembiovský         goto out;
796a41c4578STomáš Golembiovský     }
797a41c4578STomáš Golembiovský #else
798a41c4578STomáš Golembiovský     if (d <= 0) {
799a41c4578STomáš Golembiovský         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
800a41c4578STomáš Golembiovský                 "Unknown file size or zero-length file.");
801a41c4578STomáš Golembiovský         goto out;
802a41c4578STomáš Golembiovský     }
803a41c4578STomáš Golembiovský #endif
804a41c4578STomáš Golembiovský 
805a41c4578STomáš Golembiovský     s->len = (size_t)d;
806a41c4578STomáš Golembiovský 
8073494d650SFam Zheng     if ((!strncasecmp(s->url, "http://", strlen("http://"))
8083494d650SFam Zheng         || !strncasecmp(s->url, "https://", strlen("https://")))
8093494d650SFam Zheng         && !s->accept_range) {
8103494d650SFam Zheng         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
8113494d650SFam Zheng                 "Server does not support 'range' (byte ranges).");
8123494d650SFam Zheng         goto out;
8133494d650SFam Zheng     }
8140bfcd599SBlue Swirl     DPRINTF("CURL: Size = %zd\n", s->len);
815769ce76dSAlexander Graf 
816769ce76dSAlexander Graf     curl_clean_state(state);
817769ce76dSAlexander Graf     curl_easy_cleanup(state->curl);
818769ce76dSAlexander Graf     state->curl = NULL;
819769ce76dSAlexander Graf 
820ba3186c4SPaolo Bonzini     qemu_mutex_init(&s->mutex);
82163f0f45fSStefan Hajnoczi     curl_attach_aio_context(bs, bdrv_get_aio_context(bs));
822769ce76dSAlexander Graf 
8238e6d58cdSKevin Wolf     qemu_opts_del(opts);
824769ce76dSAlexander Graf     return 0;
825769ce76dSAlexander Graf 
826769ce76dSAlexander Graf out:
827acd7fdc6SMaria Kustova     error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
828769ce76dSAlexander Graf     curl_easy_cleanup(state->curl);
829769ce76dSAlexander Graf     state->curl = NULL;
830769ce76dSAlexander Graf out_noclean:
831a94f83d9SRichard W.M. Jones     g_free(s->cookie);
8328e6d58cdSKevin Wolf     g_free(s->url);
8338e6d58cdSKevin Wolf     qemu_opts_del(opts);
834769ce76dSAlexander Graf     return -EINVAL;
835769ce76dSAlexander Graf }
836769ce76dSAlexander Graf 
837d7331bedSStefan Hajnoczi static const AIOCBInfo curl_aiocb_info = {
838c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(CURLAIOCB),
839c16b5a2cSChristoph Hellwig };
840c16b5a2cSChristoph Hellwig 
841363c3c85SNick Thomas 
842363c3c85SNick Thomas static void curl_readv_bh_cb(void *p)
843769ce76dSAlexander Graf {
844769ce76dSAlexander Graf     CURLState *state;
845b69cdef8SMatthew Booth     int running;
8461919631eSPaolo Bonzini     int ret = -EINPROGRESS;
847769ce76dSAlexander Graf 
848363c3c85SNick Thomas     CURLAIOCB *acb = p;
8491919631eSPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
8501919631eSPaolo Bonzini     BDRVCURLState *s = bs->opaque;
851769ce76dSAlexander Graf 
8529054d9f6SMax Reitz     size_t start = acb->sector_num * BDRV_SECTOR_SIZE;
853363c3c85SNick Thomas     size_t end;
854769ce76dSAlexander Graf 
855ba3186c4SPaolo Bonzini     qemu_mutex_lock(&s->mutex);
8561919631eSPaolo Bonzini 
857769ce76dSAlexander Graf     // In case we have the requested data already (e.g. read-ahead),
858769ce76dSAlexander Graf     // we can just call the callback and be done.
8599054d9f6SMax Reitz     switch (curl_find_buf(s, start, acb->nb_sectors * BDRV_SECTOR_SIZE, acb)) {
860769ce76dSAlexander Graf         case FIND_RET_OK:
861*34db05e7SPaolo Bonzini             ret = 0;
862*34db05e7SPaolo Bonzini             goto out;
863769ce76dSAlexander Graf         case FIND_RET_WAIT:
8641919631eSPaolo Bonzini             goto out;
865769ce76dSAlexander Graf         default:
866769ce76dSAlexander Graf             break;
867769ce76dSAlexander Graf     }
868769ce76dSAlexander Graf 
869769ce76dSAlexander Graf     // No cache found, so let's start a new request
870a2f468e4SRichard W.M. Jones     state = curl_init_state(acb->common.bs, s);
871363c3c85SNick Thomas     if (!state) {
8721919631eSPaolo Bonzini         ret = -EIO;
8731919631eSPaolo Bonzini         goto out;
874363c3c85SNick Thomas     }
875769ce76dSAlexander Graf 
876769ce76dSAlexander Graf     acb->start = 0;
8774e504535SMax Reitz     acb->end = MIN(acb->nb_sectors * BDRV_SECTOR_SIZE, s->len - start);
878769ce76dSAlexander Graf 
879769ce76dSAlexander Graf     state->buf_off = 0;
8807267c094SAnthony Liguori     g_free(state->orig_buf);
881769ce76dSAlexander Graf     state->buf_start = start;
8824e504535SMax Reitz     state->buf_len = MIN(acb->end + s->readahead_size, s->len - start);
8834e504535SMax Reitz     end = start + state->buf_len - 1;
8848dc7a772SKevin Wolf     state->orig_buf = g_try_malloc(state->buf_len);
8858dc7a772SKevin Wolf     if (state->buf_len && state->orig_buf == NULL) {
8868dc7a772SKevin Wolf         curl_clean_state(state);
8871919631eSPaolo Bonzini         ret = -ENOMEM;
8881919631eSPaolo Bonzini         goto out;
8898dc7a772SKevin Wolf     }
890769ce76dSAlexander Graf     state->acb[0] = acb;
891769ce76dSAlexander Graf 
8920bfcd599SBlue Swirl     snprintf(state->range, 127, "%zd-%zd", start, end);
8939054d9f6SMax Reitz     DPRINTF("CURL (AIO): Reading %llu at %zd (%s)\n",
8949054d9f6SMax Reitz             (acb->nb_sectors * BDRV_SECTOR_SIZE), start, state->range);
895769ce76dSAlexander Graf     curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
896769ce76dSAlexander Graf 
897769ce76dSAlexander Graf     curl_multi_add_handle(s->multi, state->curl);
898769ce76dSAlexander Graf 
899b69cdef8SMatthew Booth     /* Tell curl it needs to kick things off */
900b69cdef8SMatthew Booth     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
9011919631eSPaolo Bonzini 
9021919631eSPaolo Bonzini out:
903ba3186c4SPaolo Bonzini     qemu_mutex_unlock(&s->mutex);
9041919631eSPaolo Bonzini     if (ret != -EINPROGRESS) {
9051919631eSPaolo Bonzini         acb->common.cb(acb->common.opaque, ret);
9061919631eSPaolo Bonzini         qemu_aio_unref(acb);
9071919631eSPaolo Bonzini     }
908363c3c85SNick Thomas }
909363c3c85SNick Thomas 
9107c84b1b8SMarkus Armbruster static BlockAIOCB *curl_aio_readv(BlockDriverState *bs,
911363c3c85SNick Thomas         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
912097310b5SMarkus Armbruster         BlockCompletionFunc *cb, void *opaque)
913363c3c85SNick Thomas {
914363c3c85SNick Thomas     CURLAIOCB *acb;
915363c3c85SNick Thomas 
916d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&curl_aiocb_info, bs, cb, opaque);
917363c3c85SNick Thomas 
918363c3c85SNick Thomas     acb->qiov = qiov;
919363c3c85SNick Thomas     acb->sector_num = sector_num;
920363c3c85SNick Thomas     acb->nb_sectors = nb_sectors;
921363c3c85SNick Thomas 
922fffb6e12SPaolo Bonzini     aio_bh_schedule_oneshot(bdrv_get_aio_context(bs), curl_readv_bh_cb, acb);
923769ce76dSAlexander Graf     return &acb->common;
924769ce76dSAlexander Graf }
925769ce76dSAlexander Graf 
926769ce76dSAlexander Graf static void curl_close(BlockDriverState *bs)
927769ce76dSAlexander Graf {
928769ce76dSAlexander Graf     BDRVCURLState *s = bs->opaque;
929769ce76dSAlexander Graf 
930d0f2c4c6Smalc     DPRINTF("CURL: Close\n");
93163f0f45fSStefan Hajnoczi     curl_detach_aio_context(bs);
932ba3186c4SPaolo Bonzini     qemu_mutex_destroy(&s->mutex);
933031fd1beSPeter Maydell 
934a94f83d9SRichard W.M. Jones     g_free(s->cookie);
93545724d6dSStefan Weil     g_free(s->url);
936769ce76dSAlexander Graf }
937769ce76dSAlexander Graf 
938769ce76dSAlexander Graf static int64_t curl_getlength(BlockDriverState *bs)
939769ce76dSAlexander Graf {
940769ce76dSAlexander Graf     BDRVCURLState *s = bs->opaque;
941769ce76dSAlexander Graf     return s->len;
942769ce76dSAlexander Graf }
943769ce76dSAlexander Graf 
944769ce76dSAlexander Graf static BlockDriver bdrv_http = {
945769ce76dSAlexander Graf     .format_name                = "http",
946769ce76dSAlexander Graf     .protocol_name              = "http",
947769ce76dSAlexander Graf 
948769ce76dSAlexander Graf     .instance_size              = sizeof(BDRVCURLState),
9498e6d58cdSKevin Wolf     .bdrv_parse_filename        = curl_parse_filename,
95066f82ceeSKevin Wolf     .bdrv_file_open             = curl_open,
951769ce76dSAlexander Graf     .bdrv_close                 = curl_close,
952769ce76dSAlexander Graf     .bdrv_getlength             = curl_getlength,
953769ce76dSAlexander Graf 
954769ce76dSAlexander Graf     .bdrv_aio_readv             = curl_aio_readv,
95563f0f45fSStefan Hajnoczi 
95663f0f45fSStefan Hajnoczi     .bdrv_detach_aio_context    = curl_detach_aio_context,
95763f0f45fSStefan Hajnoczi     .bdrv_attach_aio_context    = curl_attach_aio_context,
958769ce76dSAlexander Graf };
959769ce76dSAlexander Graf 
960769ce76dSAlexander Graf static BlockDriver bdrv_https = {
961769ce76dSAlexander Graf     .format_name                = "https",
962769ce76dSAlexander Graf     .protocol_name              = "https",
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 
970769ce76dSAlexander Graf     .bdrv_aio_readv             = curl_aio_readv,
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_ftp = {
977769ce76dSAlexander Graf     .format_name                = "ftp",
978769ce76dSAlexander Graf     .protocol_name              = "ftp",
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 
986769ce76dSAlexander Graf     .bdrv_aio_readv             = curl_aio_readv,
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_ftps = {
993769ce76dSAlexander Graf     .format_name                = "ftps",
994769ce76dSAlexander Graf     .protocol_name              = "ftps",
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 
1002769ce76dSAlexander Graf     .bdrv_aio_readv             = curl_aio_readv,
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 void curl_block_init(void)
1009769ce76dSAlexander Graf {
1010769ce76dSAlexander Graf     bdrv_register(&bdrv_http);
1011769ce76dSAlexander Graf     bdrv_register(&bdrv_https);
1012769ce76dSAlexander Graf     bdrv_register(&bdrv_ftp);
1013769ce76dSAlexander Graf     bdrv_register(&bdrv_ftps);
1014769ce76dSAlexander Graf }
1015769ce76dSAlexander Graf 
1016769ce76dSAlexander Graf block_init(curl_block_init);
1017