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