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