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