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