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