xref: /openbmc/qemu/block/curl.c (revision 83a71719)
1 /*
2  * QEMU Block driver for CURL images
3  *
4  * Copyright (c) 2009 Alexander Graf <agraf@suse.de>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qapi/error.h"
27 #include "qemu/error-report.h"
28 #include "qemu/option.h"
29 #include "block/block_int.h"
30 #include "qapi/qmp/qdict.h"
31 #include "qapi/qmp/qstring.h"
32 #include "crypto/secret.h"
33 #include <curl/curl.h>
34 #include "qemu/cutils.h"
35 #include "trace.h"
36 
37 // #define DEBUG_VERBOSE
38 
39 #if LIBCURL_VERSION_NUM >= 0x071000
40 /* The multi interface timer callback was introduced in 7.16.0 */
41 #define NEED_CURL_TIMER_CALLBACK
42 #define HAVE_SOCKET_ACTION
43 #endif
44 
45 #ifndef HAVE_SOCKET_ACTION
46 /* If curl_multi_socket_action isn't available, define it statically here in
47  * terms of curl_multi_socket. Note that ev_bitmask will be ignored, which is
48  * less efficient but still safe. */
49 static CURLMcode __curl_multi_socket_action(CURLM *multi_handle,
50                                             curl_socket_t sockfd,
51                                             int ev_bitmask,
52                                             int *running_handles)
53 {
54     return curl_multi_socket(multi_handle, sockfd, running_handles);
55 }
56 #define curl_multi_socket_action __curl_multi_socket_action
57 #endif
58 
59 #define PROTOCOLS (CURLPROTO_HTTP | CURLPROTO_HTTPS | \
60                    CURLPROTO_FTP | CURLPROTO_FTPS)
61 
62 #define CURL_NUM_STATES 8
63 #define CURL_NUM_ACB    8
64 #define READ_AHEAD_DEFAULT (256 * 1024)
65 #define CURL_TIMEOUT_DEFAULT 5
66 #define CURL_TIMEOUT_MAX 10000
67 
68 #define CURL_BLOCK_OPT_URL       "url"
69 #define CURL_BLOCK_OPT_READAHEAD "readahead"
70 #define CURL_BLOCK_OPT_SSLVERIFY "sslverify"
71 #define CURL_BLOCK_OPT_TIMEOUT "timeout"
72 #define CURL_BLOCK_OPT_COOKIE    "cookie"
73 #define CURL_BLOCK_OPT_COOKIE_SECRET "cookie-secret"
74 #define CURL_BLOCK_OPT_USERNAME "username"
75 #define CURL_BLOCK_OPT_PASSWORD_SECRET "password-secret"
76 #define CURL_BLOCK_OPT_PROXY_USERNAME "proxy-username"
77 #define CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET "proxy-password-secret"
78 
79 struct BDRVCURLState;
80 
81 static bool libcurl_initialized;
82 
83 typedef struct CURLAIOCB {
84     Coroutine *co;
85     QEMUIOVector *qiov;
86 
87     uint64_t offset;
88     uint64_t bytes;
89     int ret;
90 
91     size_t start;
92     size_t end;
93 } CURLAIOCB;
94 
95 typedef struct CURLSocket {
96     int fd;
97     QLIST_ENTRY(CURLSocket) next;
98 } CURLSocket;
99 
100 typedef struct CURLState
101 {
102     struct BDRVCURLState *s;
103     CURLAIOCB *acb[CURL_NUM_ACB];
104     CURL *curl;
105     QLIST_HEAD(, CURLSocket) sockets;
106     char *orig_buf;
107     uint64_t buf_start;
108     size_t buf_off;
109     size_t buf_len;
110     char range[128];
111     char errmsg[CURL_ERROR_SIZE];
112     char in_use;
113 } CURLState;
114 
115 typedef struct BDRVCURLState {
116     CURLM *multi;
117     QEMUTimer timer;
118     uint64_t len;
119     CURLState states[CURL_NUM_STATES];
120     char *url;
121     size_t readahead_size;
122     bool sslverify;
123     uint64_t timeout;
124     char *cookie;
125     bool accept_range;
126     AioContext *aio_context;
127     QemuMutex mutex;
128     CoQueue free_state_waitq;
129     char *username;
130     char *password;
131     char *proxyusername;
132     char *proxypassword;
133 } BDRVCURLState;
134 
135 static void curl_clean_state(CURLState *s);
136 static void curl_multi_do(void *arg);
137 static void curl_multi_read(void *arg);
138 
139 #ifdef NEED_CURL_TIMER_CALLBACK
140 /* Called from curl_multi_do_locked, with s->mutex held.  */
141 static int curl_timer_cb(CURLM *multi, long timeout_ms, void *opaque)
142 {
143     BDRVCURLState *s = opaque;
144 
145     trace_curl_timer_cb(timeout_ms);
146     if (timeout_ms == -1) {
147         timer_del(&s->timer);
148     } else {
149         int64_t timeout_ns = (int64_t)timeout_ms * 1000 * 1000;
150         timer_mod(&s->timer,
151                   qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ns);
152     }
153     return 0;
154 }
155 #endif
156 
157 /* Called from curl_multi_do_locked, with s->mutex held.  */
158 static int curl_sock_cb(CURL *curl, curl_socket_t fd, int action,
159                         void *userp, void *sp)
160 {
161     BDRVCURLState *s;
162     CURLState *state = NULL;
163     CURLSocket *socket;
164 
165     curl_easy_getinfo(curl, CURLINFO_PRIVATE, (char **)&state);
166     s = state->s;
167 
168     QLIST_FOREACH(socket, &state->sockets, next) {
169         if (socket->fd == fd) {
170             if (action == CURL_POLL_REMOVE) {
171                 QLIST_REMOVE(socket, next);
172                 g_free(socket);
173             }
174             break;
175         }
176     }
177     if (!socket) {
178         socket = g_new0(CURLSocket, 1);
179         socket->fd = fd;
180         QLIST_INSERT_HEAD(&state->sockets, socket, next);
181     }
182     socket = NULL;
183 
184     trace_curl_sock_cb(action, (int)fd);
185     switch (action) {
186         case CURL_POLL_IN:
187             aio_set_fd_handler(s->aio_context, fd, false,
188                                curl_multi_read, NULL, NULL, state);
189             break;
190         case CURL_POLL_OUT:
191             aio_set_fd_handler(s->aio_context, fd, false,
192                                NULL, curl_multi_do, NULL, state);
193             break;
194         case CURL_POLL_INOUT:
195             aio_set_fd_handler(s->aio_context, fd, false,
196                                curl_multi_read, curl_multi_do, NULL, state);
197             break;
198         case CURL_POLL_REMOVE:
199             aio_set_fd_handler(s->aio_context, fd, false,
200                                NULL, NULL, NULL, NULL);
201             break;
202     }
203 
204     return 0;
205 }
206 
207 /* Called from curl_multi_do_locked, with s->mutex held.  */
208 static size_t curl_header_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
209 {
210     BDRVCURLState *s = opaque;
211     size_t realsize = size * nmemb;
212     const char *accept_line = "Accept-Ranges: bytes";
213 
214     if (realsize >= strlen(accept_line)
215         && strncmp((char *)ptr, accept_line, strlen(accept_line)) == 0) {
216         s->accept_range = true;
217     }
218 
219     return realsize;
220 }
221 
222 /* Called from curl_multi_do_locked, with s->mutex held.  */
223 static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
224 {
225     CURLState *s = ((CURLState*)opaque);
226     size_t realsize = size * nmemb;
227     int i;
228 
229     trace_curl_read_cb(realsize);
230 
231     if (!s || !s->orig_buf) {
232         goto read_end;
233     }
234 
235     if (s->buf_off >= s->buf_len) {
236         /* buffer full, read nothing */
237         goto read_end;
238     }
239     realsize = MIN(realsize, s->buf_len - s->buf_off);
240     memcpy(s->orig_buf + s->buf_off, ptr, realsize);
241     s->buf_off += realsize;
242 
243     for(i=0; i<CURL_NUM_ACB; i++) {
244         CURLAIOCB *acb = s->acb[i];
245 
246         if (!acb)
247             continue;
248 
249         if ((s->buf_off >= acb->end)) {
250             size_t request_length = acb->bytes;
251 
252             qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,
253                                 acb->end - acb->start);
254 
255             if (acb->end - acb->start < request_length) {
256                 size_t offset = acb->end - acb->start;
257                 qemu_iovec_memset(acb->qiov, offset, 0,
258                                   request_length - offset);
259             }
260 
261             acb->ret = 0;
262             s->acb[i] = NULL;
263             qemu_mutex_unlock(&s->s->mutex);
264             aio_co_wake(acb->co);
265             qemu_mutex_lock(&s->s->mutex);
266         }
267     }
268 
269 read_end:
270     /* curl will error out if we do not return this value */
271     return size * nmemb;
272 }
273 
274 /* Called with s->mutex held.  */
275 static bool curl_find_buf(BDRVCURLState *s, uint64_t start, uint64_t len,
276                           CURLAIOCB *acb)
277 {
278     int i;
279     uint64_t end = start + len;
280     uint64_t clamped_end = MIN(end, s->len);
281     uint64_t clamped_len = clamped_end - start;
282 
283     for (i=0; i<CURL_NUM_STATES; i++) {
284         CURLState *state = &s->states[i];
285         uint64_t buf_end = (state->buf_start + state->buf_off);
286         uint64_t buf_fend = (state->buf_start + state->buf_len);
287 
288         if (!state->orig_buf)
289             continue;
290         if (!state->buf_off)
291             continue;
292 
293         // Does the existing buffer cover our section?
294         if ((start >= state->buf_start) &&
295             (start <= buf_end) &&
296             (clamped_end >= state->buf_start) &&
297             (clamped_end <= buf_end))
298         {
299             char *buf = state->orig_buf + (start - state->buf_start);
300 
301             qemu_iovec_from_buf(acb->qiov, 0, buf, clamped_len);
302             if (clamped_len < len) {
303                 qemu_iovec_memset(acb->qiov, clamped_len, 0, len - clamped_len);
304             }
305             acb->ret = 0;
306             return true;
307         }
308 
309         // Wait for unfinished chunks
310         if (state->in_use &&
311             (start >= state->buf_start) &&
312             (start <= buf_fend) &&
313             (clamped_end >= state->buf_start) &&
314             (clamped_end <= buf_fend))
315         {
316             int j;
317 
318             acb->start = start - state->buf_start;
319             acb->end = acb->start + clamped_len;
320 
321             for (j=0; j<CURL_NUM_ACB; j++) {
322                 if (!state->acb[j]) {
323                     state->acb[j] = acb;
324                     return true;
325                 }
326             }
327         }
328     }
329 
330     return false;
331 }
332 
333 /* Called with s->mutex held.  */
334 static void curl_multi_check_completion(BDRVCURLState *s)
335 {
336     int msgs_in_queue;
337 
338     /* Try to find done transfers, so we can free the easy
339      * handle again. */
340     for (;;) {
341         CURLMsg *msg;
342         msg = curl_multi_info_read(s->multi, &msgs_in_queue);
343 
344         /* Quit when there are no more completions */
345         if (!msg)
346             break;
347 
348         if (msg->msg == CURLMSG_DONE) {
349             CURLState *state = NULL;
350             curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,
351                               (char **)&state);
352 
353             /* ACBs for successful messages get completed in curl_read_cb */
354             if (msg->data.result != CURLE_OK) {
355                 int i;
356                 static int errcount = 100;
357 
358                 /* Don't lose the original error message from curl, since
359                  * it contains extra data.
360                  */
361                 if (errcount > 0) {
362                     error_report("curl: %s", state->errmsg);
363                     if (--errcount == 0) {
364                         error_report("curl: further errors suppressed");
365                     }
366                 }
367 
368                 for (i = 0; i < CURL_NUM_ACB; i++) {
369                     CURLAIOCB *acb = state->acb[i];
370 
371                     if (acb == NULL) {
372                         continue;
373                     }
374 
375                     acb->ret = -EIO;
376                     state->acb[i] = NULL;
377                     qemu_mutex_unlock(&s->mutex);
378                     aio_co_wake(acb->co);
379                     qemu_mutex_lock(&s->mutex);
380                 }
381             }
382 
383             curl_clean_state(state);
384             break;
385         }
386     }
387 }
388 
389 /* Called with s->mutex held.  */
390 static void curl_multi_do_locked(CURLState *s)
391 {
392     CURLSocket *socket, *next_socket;
393     int running;
394     int r;
395 
396     if (!s->s->multi) {
397         return;
398     }
399 
400     /* Need to use _SAFE because curl_multi_socket_action() may trigger
401      * curl_sock_cb() which might modify this list */
402     QLIST_FOREACH_SAFE(socket, &s->sockets, next, next_socket) {
403         do {
404             r = curl_multi_socket_action(s->s->multi, socket->fd, 0, &running);
405         } while (r == CURLM_CALL_MULTI_PERFORM);
406     }
407 }
408 
409 static void curl_multi_do(void *arg)
410 {
411     CURLState *s = (CURLState *)arg;
412 
413     qemu_mutex_lock(&s->s->mutex);
414     curl_multi_do_locked(s);
415     qemu_mutex_unlock(&s->s->mutex);
416 }
417 
418 static void curl_multi_read(void *arg)
419 {
420     CURLState *s = (CURLState *)arg;
421 
422     qemu_mutex_lock(&s->s->mutex);
423     curl_multi_do_locked(s);
424     curl_multi_check_completion(s->s);
425     qemu_mutex_unlock(&s->s->mutex);
426 }
427 
428 static void curl_multi_timeout_do(void *arg)
429 {
430 #ifdef NEED_CURL_TIMER_CALLBACK
431     BDRVCURLState *s = (BDRVCURLState *)arg;
432     int running;
433 
434     if (!s->multi) {
435         return;
436     }
437 
438     qemu_mutex_lock(&s->mutex);
439     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
440 
441     curl_multi_check_completion(s);
442     qemu_mutex_unlock(&s->mutex);
443 #else
444     abort();
445 #endif
446 }
447 
448 /* Called with s->mutex held.  */
449 static CURLState *curl_find_state(BDRVCURLState *s)
450 {
451     CURLState *state = NULL;
452     int i;
453 
454     for (i = 0; i < CURL_NUM_STATES; i++) {
455         if (!s->states[i].in_use) {
456             state = &s->states[i];
457             state->in_use = 1;
458             break;
459         }
460     }
461     return state;
462 }
463 
464 static int curl_init_state(BDRVCURLState *s, CURLState *state)
465 {
466     if (!state->curl) {
467         state->curl = curl_easy_init();
468         if (!state->curl) {
469             return -EIO;
470         }
471         curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
472         curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,
473                          (long) s->sslverify);
474         curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYHOST,
475                          s->sslverify ? 2L : 0L);
476         if (s->cookie) {
477             curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);
478         }
479         curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);
480         curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,
481                          (void *)curl_read_cb);
482         curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
483         curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
484         curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
485         curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
486         curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
487         curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
488         curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
489 
490         if (s->username) {
491             curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);
492         }
493         if (s->password) {
494             curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);
495         }
496         if (s->proxyusername) {
497             curl_easy_setopt(state->curl,
498                              CURLOPT_PROXYUSERNAME, s->proxyusername);
499         }
500         if (s->proxypassword) {
501             curl_easy_setopt(state->curl,
502                              CURLOPT_PROXYPASSWORD, s->proxypassword);
503         }
504 
505         /* Restrict supported protocols to avoid security issues in the more
506          * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see
507          * CVE-2013-0249.
508          *
509          * Restricting protocols is only supported from 7.19.4 upwards.
510          */
511 #if LIBCURL_VERSION_NUM >= 0x071304
512         curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
513         curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
514 #endif
515 
516 #ifdef DEBUG_VERBOSE
517         curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
518 #endif
519     }
520 
521     QLIST_INIT(&state->sockets);
522     state->s = s;
523 
524     return 0;
525 }
526 
527 /* Called with s->mutex held.  */
528 static void curl_clean_state(CURLState *s)
529 {
530     int j;
531     for (j = 0; j < CURL_NUM_ACB; j++) {
532         assert(!s->acb[j]);
533     }
534 
535     if (s->s->multi)
536         curl_multi_remove_handle(s->s->multi, s->curl);
537 
538     while (!QLIST_EMPTY(&s->sockets)) {
539         CURLSocket *socket = QLIST_FIRST(&s->sockets);
540 
541         QLIST_REMOVE(socket, next);
542         g_free(socket);
543     }
544 
545     s->in_use = 0;
546 
547     qemu_co_enter_next(&s->s->free_state_waitq, &s->s->mutex);
548 }
549 
550 static void curl_parse_filename(const char *filename, QDict *options,
551                                 Error **errp)
552 {
553     qdict_put_str(options, CURL_BLOCK_OPT_URL, filename);
554 }
555 
556 static void curl_detach_aio_context(BlockDriverState *bs)
557 {
558     BDRVCURLState *s = bs->opaque;
559     int i;
560 
561     qemu_mutex_lock(&s->mutex);
562     for (i = 0; i < CURL_NUM_STATES; i++) {
563         if (s->states[i].in_use) {
564             curl_clean_state(&s->states[i]);
565         }
566         if (s->states[i].curl) {
567             curl_easy_cleanup(s->states[i].curl);
568             s->states[i].curl = NULL;
569         }
570         g_free(s->states[i].orig_buf);
571         s->states[i].orig_buf = NULL;
572     }
573     if (s->multi) {
574         curl_multi_cleanup(s->multi);
575         s->multi = NULL;
576     }
577     qemu_mutex_unlock(&s->mutex);
578 
579     timer_del(&s->timer);
580 }
581 
582 static void curl_attach_aio_context(BlockDriverState *bs,
583                                     AioContext *new_context)
584 {
585     BDRVCURLState *s = bs->opaque;
586 
587     aio_timer_init(new_context, &s->timer,
588                    QEMU_CLOCK_REALTIME, SCALE_NS,
589                    curl_multi_timeout_do, s);
590 
591     assert(!s->multi);
592     s->multi = curl_multi_init();
593     s->aio_context = new_context;
594     curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
595 #ifdef NEED_CURL_TIMER_CALLBACK
596     curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
597     curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
598 #endif
599 }
600 
601 static QemuOptsList runtime_opts = {
602     .name = "curl",
603     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
604     .desc = {
605         {
606             .name = CURL_BLOCK_OPT_URL,
607             .type = QEMU_OPT_STRING,
608             .help = "URL to open",
609         },
610         {
611             .name = CURL_BLOCK_OPT_READAHEAD,
612             .type = QEMU_OPT_SIZE,
613             .help = "Readahead size",
614         },
615         {
616             .name = CURL_BLOCK_OPT_SSLVERIFY,
617             .type = QEMU_OPT_BOOL,
618             .help = "Verify SSL certificate"
619         },
620         {
621             .name = CURL_BLOCK_OPT_TIMEOUT,
622             .type = QEMU_OPT_NUMBER,
623             .help = "Curl timeout"
624         },
625         {
626             .name = CURL_BLOCK_OPT_COOKIE,
627             .type = QEMU_OPT_STRING,
628             .help = "Pass the cookie or list of cookies with each request"
629         },
630         {
631             .name = CURL_BLOCK_OPT_COOKIE_SECRET,
632             .type = QEMU_OPT_STRING,
633             .help = "ID of secret used as cookie passed with each request"
634         },
635         {
636             .name = CURL_BLOCK_OPT_USERNAME,
637             .type = QEMU_OPT_STRING,
638             .help = "Username for HTTP auth"
639         },
640         {
641             .name = CURL_BLOCK_OPT_PASSWORD_SECRET,
642             .type = QEMU_OPT_STRING,
643             .help = "ID of secret used as password for HTTP auth",
644         },
645         {
646             .name = CURL_BLOCK_OPT_PROXY_USERNAME,
647             .type = QEMU_OPT_STRING,
648             .help = "Username for HTTP proxy auth"
649         },
650         {
651             .name = CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
652             .type = QEMU_OPT_STRING,
653             .help = "ID of secret used as password for HTTP proxy auth",
654         },
655         { /* end of list */ }
656     },
657 };
658 
659 
660 static int curl_open(BlockDriverState *bs, QDict *options, int flags,
661                      Error **errp)
662 {
663     BDRVCURLState *s = bs->opaque;
664     CURLState *state = NULL;
665     QemuOpts *opts;
666     Error *local_err = NULL;
667     const char *file;
668     const char *cookie;
669     const char *cookie_secret;
670     double d;
671     const char *secretid;
672     const char *protocol_delimiter;
673     int ret;
674 
675     ret = bdrv_apply_auto_read_only(bs, "curl driver does not support writes",
676                                     errp);
677     if (ret < 0) {
678         return ret;
679     }
680 
681     if (!libcurl_initialized) {
682         ret = curl_global_init(CURL_GLOBAL_ALL);
683         if (ret) {
684             error_setg(errp, "libcurl initialization failed with %d", ret);
685             return -EIO;
686         }
687         libcurl_initialized = true;
688     }
689 
690     qemu_mutex_init(&s->mutex);
691     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
692     qemu_opts_absorb_qdict(opts, options, &local_err);
693     if (local_err) {
694         error_propagate(errp, local_err);
695         goto out_noclean;
696     }
697 
698     s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
699                                           READ_AHEAD_DEFAULT);
700     if ((s->readahead_size & 0x1ff) != 0) {
701         error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
702                    s->readahead_size);
703         goto out_noclean;
704     }
705 
706     s->timeout = qemu_opt_get_number(opts, CURL_BLOCK_OPT_TIMEOUT,
707                                      CURL_TIMEOUT_DEFAULT);
708     if (s->timeout > CURL_TIMEOUT_MAX) {
709         error_setg(errp, "timeout parameter is too large or negative");
710         goto out_noclean;
711     }
712 
713     s->sslverify = qemu_opt_get_bool(opts, CURL_BLOCK_OPT_SSLVERIFY, true);
714 
715     cookie = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE);
716     cookie_secret = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE_SECRET);
717 
718     if (cookie && cookie_secret) {
719         error_setg(errp,
720                    "curl driver cannot handle both cookie and cookie secret");
721         goto out_noclean;
722     }
723 
724     if (cookie_secret) {
725         s->cookie = qcrypto_secret_lookup_as_utf8(cookie_secret, errp);
726         if (!s->cookie) {
727             goto out_noclean;
728         }
729     } else {
730         s->cookie = g_strdup(cookie);
731     }
732 
733     file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
734     if (file == NULL) {
735         error_setg(errp, "curl block driver requires an 'url' option");
736         goto out_noclean;
737     }
738 
739     if (!strstart(file, bs->drv->protocol_name, &protocol_delimiter) ||
740         !strstart(protocol_delimiter, "://", NULL))
741     {
742         error_setg(errp, "%s curl driver cannot handle the URL '%s' (does not "
743                    "start with '%s://')", bs->drv->protocol_name, file,
744                    bs->drv->protocol_name);
745         goto out_noclean;
746     }
747 
748     s->username = g_strdup(qemu_opt_get(opts, CURL_BLOCK_OPT_USERNAME));
749     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PASSWORD_SECRET);
750 
751     if (secretid) {
752         s->password = qcrypto_secret_lookup_as_utf8(secretid, errp);
753         if (!s->password) {
754             goto out_noclean;
755         }
756     }
757 
758     s->proxyusername = g_strdup(
759         qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_USERNAME));
760     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET);
761     if (secretid) {
762         s->proxypassword = qcrypto_secret_lookup_as_utf8(secretid, errp);
763         if (!s->proxypassword) {
764             goto out_noclean;
765         }
766     }
767 
768     trace_curl_open(file);
769     qemu_co_queue_init(&s->free_state_waitq);
770     s->aio_context = bdrv_get_aio_context(bs);
771     s->url = g_strdup(file);
772     qemu_mutex_lock(&s->mutex);
773     state = curl_find_state(s);
774     qemu_mutex_unlock(&s->mutex);
775     if (!state) {
776         goto out_noclean;
777     }
778 
779     // Get file size
780 
781     if (curl_init_state(s, state) < 0) {
782         goto out;
783     }
784 
785     s->accept_range = false;
786     curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
787     curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
788                      curl_header_cb);
789     curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
790     if (curl_easy_perform(state->curl))
791         goto out;
792     if (curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) {
793         goto out;
794     }
795     /* Prior CURL 7.19.4 return value of 0 could mean that the file size is not
796      * know or the size is zero. From 7.19.4 CURL returns -1 if size is not
797      * known and zero if it is really zero-length file. */
798 #if LIBCURL_VERSION_NUM >= 0x071304
799     if (d < 0) {
800         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
801                 "Server didn't report file size.");
802         goto out;
803     }
804 #else
805     if (d <= 0) {
806         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
807                 "Unknown file size or zero-length file.");
808         goto out;
809     }
810 #endif
811 
812     s->len = d;
813 
814     if ((!strncasecmp(s->url, "http://", strlen("http://"))
815         || !strncasecmp(s->url, "https://", strlen("https://")))
816         && !s->accept_range) {
817         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
818                 "Server does not support 'range' (byte ranges).");
819         goto out;
820     }
821     trace_curl_open_size(s->len);
822 
823     qemu_mutex_lock(&s->mutex);
824     curl_clean_state(state);
825     qemu_mutex_unlock(&s->mutex);
826     curl_easy_cleanup(state->curl);
827     state->curl = NULL;
828 
829     curl_attach_aio_context(bs, bdrv_get_aio_context(bs));
830 
831     qemu_opts_del(opts);
832     return 0;
833 
834 out:
835     error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
836     curl_easy_cleanup(state->curl);
837     state->curl = NULL;
838 out_noclean:
839     qemu_mutex_destroy(&s->mutex);
840     g_free(s->cookie);
841     g_free(s->url);
842     g_free(s->username);
843     g_free(s->proxyusername);
844     g_free(s->proxypassword);
845     qemu_opts_del(opts);
846     return -EINVAL;
847 }
848 
849 static void curl_setup_preadv(BlockDriverState *bs, CURLAIOCB *acb)
850 {
851     CURLState *state;
852     int running;
853 
854     BDRVCURLState *s = bs->opaque;
855 
856     uint64_t start = acb->offset;
857     uint64_t end;
858 
859     qemu_mutex_lock(&s->mutex);
860 
861     // In case we have the requested data already (e.g. read-ahead),
862     // we can just call the callback and be done.
863     if (curl_find_buf(s, start, acb->bytes, acb)) {
864         goto out;
865     }
866 
867     // No cache found, so let's start a new request
868     for (;;) {
869         state = curl_find_state(s);
870         if (state) {
871             break;
872         }
873         qemu_co_queue_wait(&s->free_state_waitq, &s->mutex);
874     }
875 
876     if (curl_init_state(s, state) < 0) {
877         curl_clean_state(state);
878         acb->ret = -EIO;
879         goto out;
880     }
881 
882     acb->start = 0;
883     acb->end = MIN(acb->bytes, s->len - start);
884 
885     state->buf_off = 0;
886     g_free(state->orig_buf);
887     state->buf_start = start;
888     state->buf_len = MIN(acb->end + s->readahead_size, s->len - start);
889     end = start + state->buf_len - 1;
890     state->orig_buf = g_try_malloc(state->buf_len);
891     if (state->buf_len && state->orig_buf == NULL) {
892         curl_clean_state(state);
893         acb->ret = -ENOMEM;
894         goto out;
895     }
896     state->acb[0] = acb;
897 
898     snprintf(state->range, 127, "%" PRIu64 "-%" PRIu64, start, end);
899     trace_curl_setup_preadv(acb->bytes, start, state->range);
900     curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
901 
902     curl_multi_add_handle(s->multi, state->curl);
903 
904     /* Tell curl it needs to kick things off */
905     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
906 
907 out:
908     qemu_mutex_unlock(&s->mutex);
909 }
910 
911 static int coroutine_fn curl_co_preadv(BlockDriverState *bs,
912         uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
913 {
914     CURLAIOCB acb = {
915         .co = qemu_coroutine_self(),
916         .ret = -EINPROGRESS,
917         .qiov = qiov,
918         .offset = offset,
919         .bytes = bytes
920     };
921 
922     curl_setup_preadv(bs, &acb);
923     while (acb.ret == -EINPROGRESS) {
924         qemu_coroutine_yield();
925     }
926     return acb.ret;
927 }
928 
929 static void curl_close(BlockDriverState *bs)
930 {
931     BDRVCURLState *s = bs->opaque;
932 
933     trace_curl_close();
934     curl_detach_aio_context(bs);
935     qemu_mutex_destroy(&s->mutex);
936 
937     g_free(s->cookie);
938     g_free(s->url);
939     g_free(s->username);
940     g_free(s->proxyusername);
941     g_free(s->proxypassword);
942 }
943 
944 static int64_t curl_getlength(BlockDriverState *bs)
945 {
946     BDRVCURLState *s = bs->opaque;
947     return s->len;
948 }
949 
950 static BlockDriver bdrv_http = {
951     .format_name                = "http",
952     .protocol_name              = "http",
953 
954     .instance_size              = sizeof(BDRVCURLState),
955     .bdrv_parse_filename        = curl_parse_filename,
956     .bdrv_file_open             = curl_open,
957     .bdrv_close                 = curl_close,
958     .bdrv_getlength             = curl_getlength,
959 
960     .bdrv_co_preadv             = curl_co_preadv,
961 
962     .bdrv_detach_aio_context    = curl_detach_aio_context,
963     .bdrv_attach_aio_context    = curl_attach_aio_context,
964 };
965 
966 static BlockDriver bdrv_https = {
967     .format_name                = "https",
968     .protocol_name              = "https",
969 
970     .instance_size              = sizeof(BDRVCURLState),
971     .bdrv_parse_filename        = curl_parse_filename,
972     .bdrv_file_open             = curl_open,
973     .bdrv_close                 = curl_close,
974     .bdrv_getlength             = curl_getlength,
975 
976     .bdrv_co_preadv             = curl_co_preadv,
977 
978     .bdrv_detach_aio_context    = curl_detach_aio_context,
979     .bdrv_attach_aio_context    = curl_attach_aio_context,
980 };
981 
982 static BlockDriver bdrv_ftp = {
983     .format_name                = "ftp",
984     .protocol_name              = "ftp",
985 
986     .instance_size              = sizeof(BDRVCURLState),
987     .bdrv_parse_filename        = curl_parse_filename,
988     .bdrv_file_open             = curl_open,
989     .bdrv_close                 = curl_close,
990     .bdrv_getlength             = curl_getlength,
991 
992     .bdrv_co_preadv             = curl_co_preadv,
993 
994     .bdrv_detach_aio_context    = curl_detach_aio_context,
995     .bdrv_attach_aio_context    = curl_attach_aio_context,
996 };
997 
998 static BlockDriver bdrv_ftps = {
999     .format_name                = "ftps",
1000     .protocol_name              = "ftps",
1001 
1002     .instance_size              = sizeof(BDRVCURLState),
1003     .bdrv_parse_filename        = curl_parse_filename,
1004     .bdrv_file_open             = curl_open,
1005     .bdrv_close                 = curl_close,
1006     .bdrv_getlength             = curl_getlength,
1007 
1008     .bdrv_co_preadv             = curl_co_preadv,
1009 
1010     .bdrv_detach_aio_context    = curl_detach_aio_context,
1011     .bdrv_attach_aio_context    = curl_attach_aio_context,
1012 };
1013 
1014 static void curl_block_init(void)
1015 {
1016     bdrv_register(&bdrv_http);
1017     bdrv_register(&bdrv_https);
1018     bdrv_register(&bdrv_ftp);
1019     bdrv_register(&bdrv_ftps);
1020 }
1021 
1022 block_init(curl_block_init);
1023