2 * QEMU Block driver for CURL images
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
24 #include "qemu-common.h"
25 #include "block/block_int.h"
26 #include <curl/curl.h>
29 // #define DEBUG_VERBOSE
32 #define DPRINTF(fmt, ...) do { printf(fmt, ## __VA_ARGS__); } while (0)
34 #define DPRINTF(fmt, ...) do { } while (0)
37 #if LIBCURL_VERSION_NUM >= 0x071000
38 /* The multi interface timer callback was introduced in 7.16.0 */
39 #define NEED_CURL_TIMER_CALLBACK
42 #define PROTOCOLS (CURLPROTO_HTTP | CURLPROTO_HTTPS | \
43 CURLPROTO_FTP | CURLPROTO_FTPS | \
46 #define CURL_NUM_STATES 8
47 #define CURL_NUM_ACB 8
48 #define SECTOR_SIZE 512
49 #define READ_AHEAD_SIZE (256 * 1024)
51 #define FIND_RET_NONE 0
53 #define FIND_RET_WAIT 2
57 typedef struct CURLAIOCB {
58 BlockDriverAIOCB common;
69 typedef struct CURLState
71 struct BDRVCURLState *s;
72 CURLAIOCB *acb[CURL_NUM_ACB];
79 char errmsg[CURL_ERROR_SIZE];
83 typedef struct BDRVCURLState {
87 CURLState states[CURL_NUM_STATES];
89 size_t readahead_size;
93 static void curl_clean_state(CURLState *s);
94 static void curl_multi_do(void *arg);
96 #ifdef NEED_CURL_TIMER_CALLBACK
97 static int curl_timer_cb(CURLM *multi, long timeout_ms, void *opaque)
99 BDRVCURLState *s = opaque;
101 DPRINTF("CURL: timer callback timeout_ms %ld\n", timeout_ms);
102 if (timeout_ms == -1) {
103 timer_del(&s->timer);
105 int64_t timeout_ns = (int64_t)timeout_ms * 1000 * 1000;
107 qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ns);
113 static int curl_sock_cb(CURL *curl, curl_socket_t fd, int action,
116 DPRINTF("CURL (AIO): Sock action %d on fd %d\n", action, fd);
119 qemu_aio_set_fd_handler(fd, curl_multi_do, NULL, s);
122 qemu_aio_set_fd_handler(fd, NULL, curl_multi_do, s);
124 case CURL_POLL_INOUT:
125 qemu_aio_set_fd_handler(fd, curl_multi_do, curl_multi_do, s);
127 case CURL_POLL_REMOVE:
128 qemu_aio_set_fd_handler(fd, NULL, NULL, NULL);
135 static size_t curl_header_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
137 BDRVCURLState *s = opaque;
138 size_t realsize = size * nmemb;
139 const char *accept_line = "Accept-Ranges: bytes";
141 if (realsize >= strlen(accept_line)
142 && strncmp((char *)ptr, accept_line, strlen(accept_line)) == 0) {
143 s->accept_range = true;
149 static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
151 CURLState *s = ((CURLState*)opaque);
152 size_t realsize = size * nmemb;
155 DPRINTF("CURL: Just reading %zd bytes\n", realsize);
157 if (!s || !s->orig_buf)
160 if (s->buf_off >= s->buf_len) {
161 /* buffer full, read nothing */
164 realsize = MIN(realsize, s->buf_len - s->buf_off);
165 memcpy(s->orig_buf + s->buf_off, ptr, realsize);
166 s->buf_off += realsize;
168 for(i=0; i<CURL_NUM_ACB; i++) {
169 CURLAIOCB *acb = s->acb[i];
174 if ((s->buf_off >= acb->end)) {
175 qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,
176 acb->end - acb->start);
177 acb->common.cb(acb->common.opaque, 0);
178 qemu_aio_release(acb);
187 static int curl_find_buf(BDRVCURLState *s, size_t start, size_t len,
191 size_t end = start + len;
193 for (i=0; i<CURL_NUM_STATES; i++) {
194 CURLState *state = &s->states[i];
195 size_t buf_end = (state->buf_start + state->buf_off);
196 size_t buf_fend = (state->buf_start + state->buf_len);
198 if (!state->orig_buf)
203 // Does the existing buffer cover our section?
204 if ((start >= state->buf_start) &&
205 (start <= buf_end) &&
206 (end >= state->buf_start) &&
209 char *buf = state->orig_buf + (start - state->buf_start);
211 qemu_iovec_from_buf(acb->qiov, 0, buf, len);
212 acb->common.cb(acb->common.opaque, 0);
217 // Wait for unfinished chunks
218 if ((start >= state->buf_start) &&
219 (start <= buf_fend) &&
220 (end >= state->buf_start) &&
225 acb->start = start - state->buf_start;
226 acb->end = acb->start + len;
228 for (j=0; j<CURL_NUM_ACB; j++) {
229 if (!state->acb[j]) {
231 return FIND_RET_WAIT;
237 return FIND_RET_NONE;
240 static void curl_multi_read(BDRVCURLState *s)
244 /* Try to find done transfers, so we can free the easy
248 msg = curl_multi_info_read(s->multi, &msgs_in_queue);
252 if (msg->msg == CURLMSG_NONE)
258 CURLState *state = NULL;
259 curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,
262 /* ACBs for successful messages get completed in curl_read_cb */
263 if (msg->data.result != CURLE_OK) {
265 for (i = 0; i < CURL_NUM_ACB; i++) {
266 CURLAIOCB *acb = state->acb[i];
272 acb->common.cb(acb->common.opaque, -EIO);
273 qemu_aio_release(acb);
274 state->acb[i] = NULL;
278 curl_clean_state(state);
285 } while(msgs_in_queue);
288 static void curl_multi_do(void *arg)
290 BDRVCURLState *s = (BDRVCURLState *)arg;
299 r = curl_multi_socket_all(s->multi, &running);
300 } while(r == CURLM_CALL_MULTI_PERFORM);
305 static void curl_multi_timeout_do(void *arg)
307 #ifdef NEED_CURL_TIMER_CALLBACK
308 BDRVCURLState *s = (BDRVCURLState *)arg;
315 curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
323 static CURLState *curl_init_state(BDRVCURLState *s)
325 CURLState *state = NULL;
329 for (i=0; i<CURL_NUM_STATES; i++) {
330 for (j=0; j<CURL_NUM_ACB; j++)
331 if (s->states[i].acb[j])
333 if (s->states[i].in_use)
336 state = &s->states[i];
349 state->curl = curl_easy_init();
352 curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
353 curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, 5);
354 curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION, (void *)curl_read_cb);
355 curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
356 curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
357 curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
358 curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
359 curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
360 curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
361 curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
363 /* Restrict supported protocols to avoid security issues in the more
364 * obscure protocols. For example, do not allow POP3/SMTP/IMAP see
367 * Restricting protocols is only supported from 7.19.4 upwards.
369 #if LIBCURL_VERSION_NUM >= 0x071304
370 curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
371 curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
375 curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
385 static void curl_clean_state(CURLState *s)
388 curl_multi_remove_handle(s->s->multi, s->curl);
392 static void curl_parse_filename(const char *filename, QDict *options,
396 #define RA_OPTSTR ":readahead="
402 file = g_strdup(filename);
404 /* Parse a trailing ":readahead=#:" param, if present. */
405 ra = file + strlen(file) - 1;
407 if (parse_state == 0) {
413 } else if (parse_state == 1) {
414 if (*ra > '9' || *ra < '0') {
415 char *opt_start = ra - strlen(RA_OPTSTR) + 1;
416 if (opt_start > file &&
417 strncmp(opt_start, RA_OPTSTR, strlen(RA_OPTSTR)) == 0) {
419 ra -= strlen(RA_OPTSTR) - 1;
421 qdict_put(options, "readahead", qstring_from_str(ra_val));
429 qdict_put(options, "url", qstring_from_str(file));
434 static QemuOptsList runtime_opts = {
436 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
440 .type = QEMU_OPT_STRING,
441 .help = "URL to open",
445 .type = QEMU_OPT_SIZE,
446 .help = "Readahead size",
448 { /* end of list */ }
452 static int curl_open(BlockDriverState *bs, QDict *options, int flags,
455 BDRVCURLState *s = bs->opaque;
456 CURLState *state = NULL;
458 Error *local_err = NULL;
462 static int inited = 0;
464 if (flags & BDRV_O_RDWR) {
465 error_setg(errp, "curl block device does not support writes");
469 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
470 qemu_opts_absorb_qdict(opts, options, &local_err);
472 error_propagate(errp, local_err);
476 s->readahead_size = qemu_opt_get_size(opts, "readahead", READ_AHEAD_SIZE);
477 if ((s->readahead_size & 0x1ff) != 0) {
478 error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
483 file = qemu_opt_get(opts, "url");
485 error_setg(errp, "curl block driver requires an 'url' option");
490 curl_global_init(CURL_GLOBAL_ALL);
494 DPRINTF("CURL: Opening %s\n", file);
495 s->url = g_strdup(file);
496 state = curl_init_state(s);
502 s->accept_range = false;
503 curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
504 curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
506 curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
507 if (curl_easy_perform(state->curl))
509 curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d);
514 if ((!strncasecmp(s->url, "http://", strlen("http://"))
515 || !strncasecmp(s->url, "https://", strlen("https://")))
516 && !s->accept_range) {
517 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
518 "Server does not support 'range' (byte ranges).");
521 DPRINTF("CURL: Size = %zd\n", s->len);
523 curl_clean_state(state);
524 curl_easy_cleanup(state->curl);
527 aio_timer_init(bdrv_get_aio_context(bs), &s->timer,
528 QEMU_CLOCK_REALTIME, SCALE_NS,
529 curl_multi_timeout_do, s);
531 // Now we know the file exists and its size, so let's
532 // initialize the multi interface!
534 s->multi = curl_multi_init();
535 curl_multi_setopt(s->multi, CURLMOPT_SOCKETDATA, s);
536 curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
537 #ifdef NEED_CURL_TIMER_CALLBACK
538 curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
539 curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
547 error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
548 curl_easy_cleanup(state->curl);
556 static void curl_aio_cancel(BlockDriverAIOCB *blockacb)
558 // Do we have to implement canceling? Seems to work without...
561 static const AIOCBInfo curl_aiocb_info = {
562 .aiocb_size = sizeof(CURLAIOCB),
563 .cancel = curl_aio_cancel,
567 static void curl_readv_bh_cb(void *p)
572 BDRVCURLState *s = acb->common.bs->opaque;
574 qemu_bh_delete(acb->bh);
577 size_t start = acb->sector_num * SECTOR_SIZE;
580 // In case we have the requested data already (e.g. read-ahead),
581 // we can just call the callback and be done.
582 switch (curl_find_buf(s, start, acb->nb_sectors * SECTOR_SIZE, acb)) {
584 qemu_aio_release(acb);
592 // No cache found, so let's start a new request
593 state = curl_init_state(s);
595 acb->common.cb(acb->common.opaque, -EIO);
596 qemu_aio_release(acb);
601 acb->end = (acb->nb_sectors * SECTOR_SIZE);
605 g_free(state->orig_buf);
606 state->buf_start = start;
607 state->buf_len = acb->end + s->readahead_size;
608 end = MIN(start + state->buf_len, s->len) - 1;
609 state->orig_buf = g_malloc(state->buf_len);
612 snprintf(state->range, 127, "%zd-%zd", start, end);
613 DPRINTF("CURL (AIO): Reading %d at %zd (%s)\n",
614 (acb->nb_sectors * SECTOR_SIZE), start, state->range);
615 curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
617 curl_multi_add_handle(s->multi, state->curl);
622 static BlockDriverAIOCB *curl_aio_readv(BlockDriverState *bs,
623 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
624 BlockDriverCompletionFunc *cb, void *opaque)
628 acb = qemu_aio_get(&curl_aiocb_info, bs, cb, opaque);
631 acb->sector_num = sector_num;
632 acb->nb_sectors = nb_sectors;
634 acb->bh = qemu_bh_new(curl_readv_bh_cb, acb);
635 qemu_bh_schedule(acb->bh);
639 static void curl_close(BlockDriverState *bs)
641 BDRVCURLState *s = bs->opaque;
644 DPRINTF("CURL: Close\n");
645 for (i=0; i<CURL_NUM_STATES; i++) {
646 if (s->states[i].in_use)
647 curl_clean_state(&s->states[i]);
648 if (s->states[i].curl) {
649 curl_easy_cleanup(s->states[i].curl);
650 s->states[i].curl = NULL;
652 if (s->states[i].orig_buf) {
653 g_free(s->states[i].orig_buf);
654 s->states[i].orig_buf = NULL;
658 curl_multi_cleanup(s->multi);
660 timer_del(&s->timer);
665 static int64_t curl_getlength(BlockDriverState *bs)
667 BDRVCURLState *s = bs->opaque;
671 static BlockDriver bdrv_http = {
672 .format_name = "http",
673 .protocol_name = "http",
675 .instance_size = sizeof(BDRVCURLState),
676 .bdrv_parse_filename = curl_parse_filename,
677 .bdrv_file_open = curl_open,
678 .bdrv_close = curl_close,
679 .bdrv_getlength = curl_getlength,
681 .bdrv_aio_readv = curl_aio_readv,
684 static BlockDriver bdrv_https = {
685 .format_name = "https",
686 .protocol_name = "https",
688 .instance_size = sizeof(BDRVCURLState),
689 .bdrv_parse_filename = curl_parse_filename,
690 .bdrv_file_open = curl_open,
691 .bdrv_close = curl_close,
692 .bdrv_getlength = curl_getlength,
694 .bdrv_aio_readv = curl_aio_readv,
697 static BlockDriver bdrv_ftp = {
698 .format_name = "ftp",
699 .protocol_name = "ftp",
701 .instance_size = sizeof(BDRVCURLState),
702 .bdrv_parse_filename = curl_parse_filename,
703 .bdrv_file_open = curl_open,
704 .bdrv_close = curl_close,
705 .bdrv_getlength = curl_getlength,
707 .bdrv_aio_readv = curl_aio_readv,
710 static BlockDriver bdrv_ftps = {
711 .format_name = "ftps",
712 .protocol_name = "ftps",
714 .instance_size = sizeof(BDRVCURLState),
715 .bdrv_parse_filename = curl_parse_filename,
716 .bdrv_file_open = curl_open,
717 .bdrv_close = curl_close,
718 .bdrv_getlength = curl_getlength,
720 .bdrv_aio_readv = curl_aio_readv,
723 static BlockDriver bdrv_tftp = {
724 .format_name = "tftp",
725 .protocol_name = "tftp",
727 .instance_size = sizeof(BDRVCURLState),
728 .bdrv_parse_filename = curl_parse_filename,
729 .bdrv_file_open = curl_open,
730 .bdrv_close = curl_close,
731 .bdrv_getlength = curl_getlength,
733 .bdrv_aio_readv = curl_aio_readv,
736 static void curl_block_init(void)
738 bdrv_register(&bdrv_http);
739 bdrv_register(&bdrv_https);
740 bdrv_register(&bdrv_ftp);
741 bdrv_register(&bdrv_ftps);
742 bdrv_register(&bdrv_tftp);
745 block_init(curl_block_init);