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