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