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