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