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