curl: strengthen assertion in curl_clean_state
[qemu/ar7.git] / block / curl.c
blob562340f4365181c88b614ebbcda37f82b24bb01e
1 /*
2 * QEMU Block driver for CURL images
4 * Copyright (c) 2009 Alexander Graf <agraf@suse.de>
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
22 * THE SOFTWARE.
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"
35 // #define DEBUG_CURL
36 // #define DEBUG_VERBOSE
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)
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
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)
65 return curl_multi_socket(multi_handle, sockfd, running_handles);
67 #define curl_multi_socket_action __curl_multi_socket_action
68 #endif
70 #define PROTOCOLS (CURLPROTO_HTTP | CURLPROTO_HTTPS | \
71 CURLPROTO_FTP | CURLPROTO_FTPS)
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
79 #define FIND_RET_NONE 0
80 #define FIND_RET_OK 1
81 #define FIND_RET_WAIT 2
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_COOKIE_SECRET "cookie-secret"
89 #define CURL_BLOCK_OPT_USERNAME "username"
90 #define CURL_BLOCK_OPT_PASSWORD_SECRET "password-secret"
91 #define CURL_BLOCK_OPT_PROXY_USERNAME "proxy-username"
92 #define CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET "proxy-password-secret"
94 struct BDRVCURLState;
96 typedef struct CURLAIOCB {
97 BlockAIOCB common;
98 QEMUIOVector *qiov;
100 int64_t sector_num;
101 int nb_sectors;
103 size_t start;
104 size_t end;
105 } CURLAIOCB;
107 typedef struct CURLSocket {
108 int fd;
109 QLIST_ENTRY(CURLSocket) next;
110 } CURLSocket;
112 typedef struct CURLState
114 struct BDRVCURLState *s;
115 CURLAIOCB *acb[CURL_NUM_ACB];
116 CURL *curl;
117 QLIST_HEAD(, CURLSocket) sockets;
118 char *orig_buf;
119 size_t buf_start;
120 size_t buf_off;
121 size_t buf_len;
122 char range[128];
123 char errmsg[CURL_ERROR_SIZE];
124 char in_use;
125 } CURLState;
127 typedef struct BDRVCURLState {
128 CURLM *multi;
129 QEMUTimer timer;
130 size_t len;
131 CURLState states[CURL_NUM_STATES];
132 char *url;
133 size_t readahead_size;
134 bool sslverify;
135 uint64_t timeout;
136 char *cookie;
137 bool accept_range;
138 AioContext *aio_context;
139 QemuMutex mutex;
140 char *username;
141 char *password;
142 char *proxyusername;
143 char *proxypassword;
144 } BDRVCURLState;
146 static void curl_clean_state(CURLState *s);
147 static void curl_multi_do(void *arg);
148 static void curl_multi_read(void *arg);
150 #ifdef NEED_CURL_TIMER_CALLBACK
151 static int curl_timer_cb(CURLM *multi, long timeout_ms, void *opaque)
153 BDRVCURLState *s = opaque;
155 DPRINTF("CURL: timer callback timeout_ms %ld\n", timeout_ms);
156 if (timeout_ms == -1) {
157 timer_del(&s->timer);
158 } else {
159 int64_t timeout_ns = (int64_t)timeout_ms * 1000 * 1000;
160 timer_mod(&s->timer,
161 qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ns);
163 return 0;
165 #endif
167 static int curl_sock_cb(CURL *curl, curl_socket_t fd, int action,
168 void *userp, void *sp)
170 BDRVCURLState *s;
171 CURLState *state = NULL;
172 CURLSocket *socket;
174 curl_easy_getinfo(curl, CURLINFO_PRIVATE, (char **)&state);
175 s = state->s;
177 QLIST_FOREACH(socket, &state->sockets, next) {
178 if (socket->fd == fd) {
179 if (action == CURL_POLL_REMOVE) {
180 QLIST_REMOVE(socket, next);
181 g_free(socket);
183 break;
186 if (!socket) {
187 socket = g_new0(CURLSocket, 1);
188 socket->fd = fd;
189 QLIST_INSERT_HEAD(&state->sockets, socket, next);
191 socket = NULL;
193 DPRINTF("CURL (AIO): Sock action %d on fd %d\n", action, (int)fd);
194 switch (action) {
195 case CURL_POLL_IN:
196 aio_set_fd_handler(s->aio_context, fd, false,
197 curl_multi_read, NULL, NULL, state);
198 break;
199 case CURL_POLL_OUT:
200 aio_set_fd_handler(s->aio_context, fd, false,
201 NULL, curl_multi_do, NULL, state);
202 break;
203 case CURL_POLL_INOUT:
204 aio_set_fd_handler(s->aio_context, fd, false,
205 curl_multi_read, curl_multi_do, NULL, state);
206 break;
207 case CURL_POLL_REMOVE:
208 aio_set_fd_handler(s->aio_context, fd, false,
209 NULL, NULL, NULL, NULL);
210 break;
213 return 0;
216 static size_t curl_header_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
218 BDRVCURLState *s = opaque;
219 size_t realsize = size * nmemb;
220 const char *accept_line = "Accept-Ranges: bytes";
222 if (realsize >= strlen(accept_line)
223 && strncmp((char *)ptr, accept_line, strlen(accept_line)) == 0) {
224 s->accept_range = true;
227 return realsize;
230 static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
232 CURLState *s = ((CURLState*)opaque);
233 size_t realsize = size * nmemb;
234 int i;
236 DPRINTF("CURL: Just reading %zd bytes\n", realsize);
238 if (!s || !s->orig_buf) {
239 goto read_end;
242 if (s->buf_off >= s->buf_len) {
243 /* buffer full, read nothing */
244 goto read_end;
246 realsize = MIN(realsize, s->buf_len - s->buf_off);
247 memcpy(s->orig_buf + s->buf_off, ptr, realsize);
248 s->buf_off += realsize;
250 for(i=0; i<CURL_NUM_ACB; i++) {
251 CURLAIOCB *acb = s->acb[i];
253 if (!acb)
254 continue;
256 if ((s->buf_off >= acb->end)) {
257 size_t request_length = acb->nb_sectors * BDRV_SECTOR_SIZE;
259 qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,
260 acb->end - acb->start);
262 if (acb->end - acb->start < request_length) {
263 size_t offset = acb->end - acb->start;
264 qemu_iovec_memset(acb->qiov, offset, 0,
265 request_length - offset);
268 acb->common.cb(acb->common.opaque, 0);
269 qemu_aio_unref(acb);
270 s->acb[i] = NULL;
274 read_end:
275 /* curl will error out if we do not return this value */
276 return size * nmemb;
279 static int curl_find_buf(BDRVCURLState *s, size_t start, size_t len,
280 CURLAIOCB *acb)
282 int i;
283 size_t end = start + len;
284 size_t clamped_end = MIN(end, s->len);
285 size_t clamped_len = clamped_end - start;
287 for (i=0; i<CURL_NUM_STATES; i++) {
288 CURLState *state = &s->states[i];
289 size_t buf_end = (state->buf_start + state->buf_off);
290 size_t buf_fend = (state->buf_start + state->buf_len);
292 if (!state->orig_buf)
293 continue;
294 if (!state->buf_off)
295 continue;
297 // Does the existing buffer cover our section?
298 if ((start >= state->buf_start) &&
299 (start <= buf_end) &&
300 (clamped_end >= state->buf_start) &&
301 (clamped_end <= buf_end))
303 char *buf = state->orig_buf + (start - state->buf_start);
305 qemu_iovec_from_buf(acb->qiov, 0, buf, clamped_len);
306 if (clamped_len < len) {
307 qemu_iovec_memset(acb->qiov, clamped_len, 0, len - clamped_len);
309 acb->common.cb(acb->common.opaque, 0);
311 return FIND_RET_OK;
314 // Wait for unfinished chunks
315 if (state->in_use &&
316 (start >= state->buf_start) &&
317 (start <= buf_fend) &&
318 (clamped_end >= state->buf_start) &&
319 (clamped_end <= buf_fend))
321 int j;
323 acb->start = start - state->buf_start;
324 acb->end = acb->start + clamped_len;
326 for (j=0; j<CURL_NUM_ACB; j++) {
327 if (!state->acb[j]) {
328 state->acb[j] = acb;
329 return FIND_RET_WAIT;
335 return FIND_RET_NONE;
338 /* Called with s->mutex held. */
339 static void curl_multi_check_completion(BDRVCURLState *s)
341 int msgs_in_queue;
343 /* Try to find done transfers, so we can free the easy
344 * handle again. */
345 for (;;) {
346 CURLMsg *msg;
347 msg = curl_multi_info_read(s->multi, &msgs_in_queue);
349 /* Quit when there are no more completions */
350 if (!msg)
351 break;
353 if (msg->msg == CURLMSG_DONE) {
354 CURLState *state = NULL;
355 curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,
356 (char **)&state);
358 /* ACBs for successful messages get completed in curl_read_cb */
359 if (msg->data.result != CURLE_OK) {
360 int i;
361 static int errcount = 100;
363 /* Don't lose the original error message from curl, since
364 * it contains extra data.
366 if (errcount > 0) {
367 error_report("curl: %s", state->errmsg);
368 if (--errcount == 0) {
369 error_report("curl: further errors suppressed");
373 for (i = 0; i < CURL_NUM_ACB; i++) {
374 CURLAIOCB *acb = state->acb[i];
376 if (acb == NULL) {
377 continue;
380 qemu_mutex_unlock(&s->mutex);
381 acb->common.cb(acb->common.opaque, -EIO);
382 qemu_mutex_lock(&s->mutex);
383 qemu_aio_unref(acb);
384 state->acb[i] = NULL;
388 curl_clean_state(state);
389 break;
394 /* Called with s->mutex held. */
395 static void curl_multi_do_locked(CURLState *s)
397 CURLSocket *socket, *next_socket;
398 int running;
399 int r;
401 if (!s->s->multi) {
402 return;
405 /* Need to use _SAFE because curl_multi_socket_action() may trigger
406 * curl_sock_cb() which might modify this list */
407 QLIST_FOREACH_SAFE(socket, &s->sockets, next, next_socket) {
408 do {
409 r = curl_multi_socket_action(s->s->multi, socket->fd, 0, &running);
410 } while (r == CURLM_CALL_MULTI_PERFORM);
414 static void curl_multi_do(void *arg)
416 CURLState *s = (CURLState *)arg;
418 qemu_mutex_lock(&s->s->mutex);
419 curl_multi_do_locked(s);
420 qemu_mutex_unlock(&s->s->mutex);
423 static void curl_multi_read(void *arg)
425 CURLState *s = (CURLState *)arg;
427 qemu_mutex_lock(&s->s->mutex);
428 curl_multi_do_locked(s);
429 curl_multi_check_completion(s->s);
430 qemu_mutex_unlock(&s->s->mutex);
433 static void curl_multi_timeout_do(void *arg)
435 #ifdef NEED_CURL_TIMER_CALLBACK
436 BDRVCURLState *s = (BDRVCURLState *)arg;
437 int running;
439 if (!s->multi) {
440 return;
443 qemu_mutex_lock(&s->mutex);
444 curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
446 curl_multi_check_completion(s);
447 qemu_mutex_unlock(&s->mutex);
448 #else
449 abort();
450 #endif
453 static CURLState *curl_init_state(BlockDriverState *bs, BDRVCURLState *s)
455 CURLState *state = NULL;
456 int i, j;
458 do {
459 for (i=0; i<CURL_NUM_STATES; i++) {
460 for (j=0; j<CURL_NUM_ACB; j++)
461 if (s->states[i].acb[j])
462 continue;
463 if (s->states[i].in_use)
464 continue;
466 state = &s->states[i];
467 state->in_use = 1;
468 break;
470 if (!state) {
471 aio_poll(bdrv_get_aio_context(bs), true);
473 } while(!state);
475 if (!state->curl) {
476 state->curl = curl_easy_init();
477 if (!state->curl) {
478 return NULL;
480 curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
481 curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,
482 (long) s->sslverify);
483 if (s->cookie) {
484 curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);
486 curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);
487 curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,
488 (void *)curl_read_cb);
489 curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
490 curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
491 curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
492 curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
493 curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
494 curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
495 curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
497 if (s->username) {
498 curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);
500 if (s->password) {
501 curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);
503 if (s->proxyusername) {
504 curl_easy_setopt(state->curl,
505 CURLOPT_PROXYUSERNAME, s->proxyusername);
507 if (s->proxypassword) {
508 curl_easy_setopt(state->curl,
509 CURLOPT_PROXYPASSWORD, s->proxypassword);
512 /* Restrict supported protocols to avoid security issues in the more
513 * obscure protocols. For example, do not allow POP3/SMTP/IMAP see
514 * CVE-2013-0249.
516 * Restricting protocols is only supported from 7.19.4 upwards.
518 #if LIBCURL_VERSION_NUM >= 0x071304
519 curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
520 curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
521 #endif
523 #ifdef DEBUG_VERBOSE
524 curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
525 #endif
528 QLIST_INIT(&state->sockets);
529 state->s = s;
531 return state;
534 static void curl_clean_state(CURLState *s)
536 int j;
537 for (j = 0; j < CURL_NUM_ACB; j++) {
538 assert(!s->acb[j]);
541 if (s->s->multi)
542 curl_multi_remove_handle(s->s->multi, s->curl);
544 while (!QLIST_EMPTY(&s->sockets)) {
545 CURLSocket *socket = QLIST_FIRST(&s->sockets);
547 QLIST_REMOVE(socket, next);
548 g_free(socket);
551 s->in_use = 0;
554 static void curl_parse_filename(const char *filename, QDict *options,
555 Error **errp)
557 qdict_put_str(options, CURL_BLOCK_OPT_URL, filename);
560 static void curl_detach_aio_context(BlockDriverState *bs)
562 BDRVCURLState *s = bs->opaque;
563 int i;
565 for (i = 0; i < CURL_NUM_STATES; i++) {
566 if (s->states[i].in_use) {
567 curl_clean_state(&s->states[i]);
569 if (s->states[i].curl) {
570 curl_easy_cleanup(s->states[i].curl);
571 s->states[i].curl = NULL;
573 g_free(s->states[i].orig_buf);
574 s->states[i].orig_buf = NULL;
576 if (s->multi) {
577 curl_multi_cleanup(s->multi);
578 s->multi = NULL;
581 timer_del(&s->timer);
584 static void curl_attach_aio_context(BlockDriverState *bs,
585 AioContext *new_context)
587 BDRVCURLState *s = bs->opaque;
589 aio_timer_init(new_context, &s->timer,
590 QEMU_CLOCK_REALTIME, SCALE_NS,
591 curl_multi_timeout_do, s);
593 assert(!s->multi);
594 s->multi = curl_multi_init();
595 s->aio_context = new_context;
596 curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
597 #ifdef NEED_CURL_TIMER_CALLBACK
598 curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
599 curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
600 #endif
603 static QemuOptsList runtime_opts = {
604 .name = "curl",
605 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
606 .desc = {
608 .name = CURL_BLOCK_OPT_URL,
609 .type = QEMU_OPT_STRING,
610 .help = "URL to open",
613 .name = CURL_BLOCK_OPT_READAHEAD,
614 .type = QEMU_OPT_SIZE,
615 .help = "Readahead size",
618 .name = CURL_BLOCK_OPT_SSLVERIFY,
619 .type = QEMU_OPT_BOOL,
620 .help = "Verify SSL certificate"
623 .name = CURL_BLOCK_OPT_TIMEOUT,
624 .type = QEMU_OPT_NUMBER,
625 .help = "Curl timeout"
628 .name = CURL_BLOCK_OPT_COOKIE,
629 .type = QEMU_OPT_STRING,
630 .help = "Pass the cookie or list of cookies with each request"
633 .name = CURL_BLOCK_OPT_COOKIE_SECRET,
634 .type = QEMU_OPT_STRING,
635 .help = "ID of secret used as cookie passed with each request"
638 .name = CURL_BLOCK_OPT_USERNAME,
639 .type = QEMU_OPT_STRING,
640 .help = "Username for HTTP auth"
643 .name = CURL_BLOCK_OPT_PASSWORD_SECRET,
644 .type = QEMU_OPT_STRING,
645 .help = "ID of secret used as password for HTTP auth",
648 .name = CURL_BLOCK_OPT_PROXY_USERNAME,
649 .type = QEMU_OPT_STRING,
650 .help = "Username for HTTP proxy auth"
653 .name = CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
654 .type = QEMU_OPT_STRING,
655 .help = "ID of secret used as password for HTTP proxy auth",
657 { /* end of list */ }
662 static int curl_open(BlockDriverState *bs, QDict *options, int flags,
663 Error **errp)
665 BDRVCURLState *s = bs->opaque;
666 CURLState *state = NULL;
667 QemuOpts *opts;
668 Error *local_err = NULL;
669 const char *file;
670 const char *cookie;
671 const char *cookie_secret;
672 double d;
673 const char *secretid;
674 const char *protocol_delimiter;
676 static int inited = 0;
678 if (flags & BDRV_O_RDWR) {
679 error_setg(errp, "curl block device does not support writes");
680 return -EROFS;
683 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
684 qemu_opts_absorb_qdict(opts, options, &local_err);
685 if (local_err) {
686 error_propagate(errp, local_err);
687 goto out_noclean;
690 s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
691 READ_AHEAD_DEFAULT);
692 if ((s->readahead_size & 0x1ff) != 0) {
693 error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
694 s->readahead_size);
695 goto out_noclean;
698 s->timeout = qemu_opt_get_number(opts, CURL_BLOCK_OPT_TIMEOUT,
699 CURL_TIMEOUT_DEFAULT);
700 if (s->timeout > CURL_TIMEOUT_MAX) {
701 error_setg(errp, "timeout parameter is too large or negative");
702 goto out_noclean;
705 s->sslverify = qemu_opt_get_bool(opts, CURL_BLOCK_OPT_SSLVERIFY, true);
707 cookie = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE);
708 cookie_secret = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE_SECRET);
710 if (cookie && cookie_secret) {
711 error_setg(errp,
712 "curl driver cannot handle both cookie and cookie secret");
713 goto out_noclean;
716 if (cookie_secret) {
717 s->cookie = qcrypto_secret_lookup_as_utf8(cookie_secret, errp);
718 if (!s->cookie) {
719 goto out_noclean;
721 } else {
722 s->cookie = g_strdup(cookie);
725 file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
726 if (file == NULL) {
727 error_setg(errp, "curl block driver requires an 'url' option");
728 goto out_noclean;
731 if (!strstart(file, bs->drv->protocol_name, &protocol_delimiter) ||
732 !strstart(protocol_delimiter, "://", NULL))
734 error_setg(errp, "%s curl driver cannot handle the URL '%s' (does not "
735 "start with '%s://')", bs->drv->protocol_name, file,
736 bs->drv->protocol_name);
737 goto out_noclean;
740 s->username = g_strdup(qemu_opt_get(opts, CURL_BLOCK_OPT_USERNAME));
741 secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PASSWORD_SECRET);
743 if (secretid) {
744 s->password = qcrypto_secret_lookup_as_utf8(secretid, errp);
745 if (!s->password) {
746 goto out_noclean;
750 s->proxyusername = g_strdup(
751 qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_USERNAME));
752 secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET);
753 if (secretid) {
754 s->proxypassword = qcrypto_secret_lookup_as_utf8(secretid, errp);
755 if (!s->proxypassword) {
756 goto out_noclean;
760 if (!inited) {
761 curl_global_init(CURL_GLOBAL_ALL);
762 inited = 1;
765 DPRINTF("CURL: Opening %s\n", file);
766 s->aio_context = bdrv_get_aio_context(bs);
767 s->url = g_strdup(file);
768 state = curl_init_state(bs, s);
769 if (!state)
770 goto out_noclean;
772 // Get file size
774 s->accept_range = false;
775 curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
776 curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
777 curl_header_cb);
778 curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
779 if (curl_easy_perform(state->curl))
780 goto out;
781 if (curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) {
782 goto out;
784 /* Prior CURL 7.19.4 return value of 0 could mean that the file size is not
785 * know or the size is zero. From 7.19.4 CURL returns -1 if size is not
786 * known and zero if it is realy zero-length file. */
787 #if LIBCURL_VERSION_NUM >= 0x071304
788 if (d < 0) {
789 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
790 "Server didn't report file size.");
791 goto out;
793 #else
794 if (d <= 0) {
795 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
796 "Unknown file size or zero-length file.");
797 goto out;
799 #endif
801 s->len = (size_t)d;
803 if ((!strncasecmp(s->url, "http://", strlen("http://"))
804 || !strncasecmp(s->url, "https://", strlen("https://")))
805 && !s->accept_range) {
806 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
807 "Server does not support 'range' (byte ranges).");
808 goto out;
810 DPRINTF("CURL: Size = %zd\n", s->len);
812 curl_clean_state(state);
813 curl_easy_cleanup(state->curl);
814 state->curl = NULL;
816 qemu_mutex_init(&s->mutex);
817 curl_attach_aio_context(bs, bdrv_get_aio_context(bs));
819 qemu_opts_del(opts);
820 return 0;
822 out:
823 error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
824 curl_easy_cleanup(state->curl);
825 state->curl = NULL;
826 out_noclean:
827 g_free(s->cookie);
828 g_free(s->url);
829 qemu_opts_del(opts);
830 return -EINVAL;
833 static const AIOCBInfo curl_aiocb_info = {
834 .aiocb_size = sizeof(CURLAIOCB),
838 static void curl_readv_bh_cb(void *p)
840 CURLState *state;
841 int running;
842 int ret = -EINPROGRESS;
844 CURLAIOCB *acb = p;
845 BlockDriverState *bs = acb->common.bs;
846 BDRVCURLState *s = bs->opaque;
848 size_t start = acb->sector_num * BDRV_SECTOR_SIZE;
849 size_t end;
851 qemu_mutex_lock(&s->mutex);
853 // In case we have the requested data already (e.g. read-ahead),
854 // we can just call the callback and be done.
855 switch (curl_find_buf(s, start, acb->nb_sectors * BDRV_SECTOR_SIZE, acb)) {
856 case FIND_RET_OK:
857 qemu_aio_unref(acb);
858 // fall through
859 case FIND_RET_WAIT:
860 goto out;
861 default:
862 break;
865 // No cache found, so let's start a new request
866 state = curl_init_state(acb->common.bs, s);
867 if (!state) {
868 ret = -EIO;
869 goto out;
872 acb->start = 0;
873 acb->end = MIN(acb->nb_sectors * BDRV_SECTOR_SIZE, s->len - start);
875 state->buf_off = 0;
876 g_free(state->orig_buf);
877 state->buf_start = start;
878 state->buf_len = MIN(acb->end + s->readahead_size, s->len - start);
879 end = start + state->buf_len - 1;
880 state->orig_buf = g_try_malloc(state->buf_len);
881 if (state->buf_len && state->orig_buf == NULL) {
882 curl_clean_state(state);
883 ret = -ENOMEM;
884 goto out;
886 state->acb[0] = acb;
888 snprintf(state->range, 127, "%zd-%zd", start, end);
889 DPRINTF("CURL (AIO): Reading %llu at %zd (%s)\n",
890 (acb->nb_sectors * BDRV_SECTOR_SIZE), start, state->range);
891 curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
893 curl_multi_add_handle(s->multi, state->curl);
895 /* Tell curl it needs to kick things off */
896 curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
898 out:
899 qemu_mutex_unlock(&s->mutex);
900 if (ret != -EINPROGRESS) {
901 acb->common.cb(acb->common.opaque, ret);
902 qemu_aio_unref(acb);
906 static BlockAIOCB *curl_aio_readv(BlockDriverState *bs,
907 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
908 BlockCompletionFunc *cb, void *opaque)
910 CURLAIOCB *acb;
912 acb = qemu_aio_get(&curl_aiocb_info, bs, cb, opaque);
914 acb->qiov = qiov;
915 acb->sector_num = sector_num;
916 acb->nb_sectors = nb_sectors;
918 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs), curl_readv_bh_cb, acb);
919 return &acb->common;
922 static void curl_close(BlockDriverState *bs)
924 BDRVCURLState *s = bs->opaque;
926 DPRINTF("CURL: Close\n");
927 curl_detach_aio_context(bs);
928 qemu_mutex_destroy(&s->mutex);
930 g_free(s->cookie);
931 g_free(s->url);
934 static int64_t curl_getlength(BlockDriverState *bs)
936 BDRVCURLState *s = bs->opaque;
937 return s->len;
940 static BlockDriver bdrv_http = {
941 .format_name = "http",
942 .protocol_name = "http",
944 .instance_size = sizeof(BDRVCURLState),
945 .bdrv_parse_filename = curl_parse_filename,
946 .bdrv_file_open = curl_open,
947 .bdrv_close = curl_close,
948 .bdrv_getlength = curl_getlength,
950 .bdrv_aio_readv = curl_aio_readv,
952 .bdrv_detach_aio_context = curl_detach_aio_context,
953 .bdrv_attach_aio_context = curl_attach_aio_context,
956 static BlockDriver bdrv_https = {
957 .format_name = "https",
958 .protocol_name = "https",
960 .instance_size = sizeof(BDRVCURLState),
961 .bdrv_parse_filename = curl_parse_filename,
962 .bdrv_file_open = curl_open,
963 .bdrv_close = curl_close,
964 .bdrv_getlength = curl_getlength,
966 .bdrv_aio_readv = curl_aio_readv,
968 .bdrv_detach_aio_context = curl_detach_aio_context,
969 .bdrv_attach_aio_context = curl_attach_aio_context,
972 static BlockDriver bdrv_ftp = {
973 .format_name = "ftp",
974 .protocol_name = "ftp",
976 .instance_size = sizeof(BDRVCURLState),
977 .bdrv_parse_filename = curl_parse_filename,
978 .bdrv_file_open = curl_open,
979 .bdrv_close = curl_close,
980 .bdrv_getlength = curl_getlength,
982 .bdrv_aio_readv = curl_aio_readv,
984 .bdrv_detach_aio_context = curl_detach_aio_context,
985 .bdrv_attach_aio_context = curl_attach_aio_context,
988 static BlockDriver bdrv_ftps = {
989 .format_name = "ftps",
990 .protocol_name = "ftps",
992 .instance_size = sizeof(BDRVCURLState),
993 .bdrv_parse_filename = curl_parse_filename,
994 .bdrv_file_open = curl_open,
995 .bdrv_close = curl_close,
996 .bdrv_getlength = curl_getlength,
998 .bdrv_aio_readv = curl_aio_readv,
1000 .bdrv_detach_aio_context = curl_detach_aio_context,
1001 .bdrv_attach_aio_context = curl_attach_aio_context,
1004 static void curl_block_init(void)
1006 bdrv_register(&bdrv_http);
1007 bdrv_register(&bdrv_https);
1008 bdrv_register(&bdrv_ftp);
1009 bdrv_register(&bdrv_ftps);
1012 block_init(curl_block_init);