]> git.proxmox.com Git - mirror_qemu.git/blame - block/curl.c
curl: Report only ready sockets
[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,
9dbad87d 188 curl_multi_do, NULL, NULL, socket);
769ce76d
AG
189 break;
190 case CURL_POLL_OUT:
dca21ef2 191 aio_set_fd_handler(s->aio_context, fd, false,
9dbad87d 192 NULL, curl_multi_do, NULL, socket);
769ce76d
AG
193 break;
194 case CURL_POLL_INOUT:
dca21ef2 195 aio_set_fd_handler(s->aio_context, fd, false,
9dbad87d 196 curl_multi_do, curl_multi_do, NULL, socket);
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. */
9abaf9fc 395static void curl_multi_do_locked(CURLSocket *socket)
031fd1be 396{
9abaf9fc 397 BDRVCURLState *s = socket->state->s;
031fd1be
PM
398 int running;
399 int r;
400
9abaf9fc 401 if (!s->multi) {
031fd1be
PM
402 return;
403 }
404
9abaf9fc
HR
405 do {
406 r = curl_multi_socket_action(s->multi, socket->fd, 0, &running);
407 } while (r == CURLM_CALL_MULTI_PERFORM);
838ef602
MB
408}
409
9d456654
PB
410static void curl_multi_do(void *arg)
411{
9dbad87d
HR
412 CURLSocket *socket = arg;
413 BDRVCURLState *s = socket->state->s;
9d456654 414
9dbad87d
HR
415 qemu_mutex_lock(&s->mutex);
416 curl_multi_do_locked(socket);
417 curl_multi_check_completion(s);
418 qemu_mutex_unlock(&s->mutex);
031fd1be
PM
419}
420
421static void curl_multi_timeout_do(void *arg)
422{
423#ifdef NEED_CURL_TIMER_CALLBACK
424 BDRVCURLState *s = (BDRVCURLState *)arg;
425 int running;
426
427 if (!s->multi) {
428 return;
429 }
430
ba3186c4 431 qemu_mutex_lock(&s->mutex);
031fd1be
PM
432 curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
433
838ef602 434 curl_multi_check_completion(s);
ba3186c4 435 qemu_mutex_unlock(&s->mutex);
031fd1be
PM
436#else
437 abort();
438#endif
439}
440
456af346 441/* Called with s->mutex held. */
3ce6a729 442static CURLState *curl_find_state(BDRVCURLState *s)
769ce76d
AG
443{
444 CURLState *state = NULL;
3ce6a729 445 int i;
769ce76d 446
3ce6a729
PB
447 for (i = 0; i < CURL_NUM_STATES; i++) {
448 if (!s->states[i].in_use) {
769ce76d
AG
449 state = &s->states[i];
450 state->in_use = 1;
451 break;
452 }
3ce6a729
PB
453 }
454 return state;
455}
769ce76d 456
3ce6a729
PB
457static int curl_init_state(BDRVCURLState *s, CURLState *state)
458{
9e550b32
MB
459 if (!state->curl) {
460 state->curl = curl_easy_init();
461 if (!state->curl) {
3ce6a729 462 return -EIO;
9e550b32
MB
463 }
464 curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
97a3ea57
MB
465 curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,
466 (long) s->sslverify);
637fa44a
RJ
467 curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYHOST,
468 s->sslverify ? 2L : 0L);
a94f83d9
RJ
469 if (s->cookie) {
470 curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);
471 }
f76faeda 472 curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);
9e550b32
MB
473 curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,
474 (void *)curl_read_cb);
475 curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
476 curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
477 curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
478 curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
479 curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
480 curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
481 curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
482
1bff9606
DB
483 if (s->username) {
484 curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);
485 }
486 if (s->password) {
487 curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);
488 }
489 if (s->proxyusername) {
490 curl_easy_setopt(state->curl,
491 CURLOPT_PROXYUSERNAME, s->proxyusername);
492 }
493 if (s->proxypassword) {
494 curl_easy_setopt(state->curl,
495 CURLOPT_PROXYPASSWORD, s->proxypassword);
496 }
497
9e550b32
MB
498 /* Restrict supported protocols to avoid security issues in the more
499 * obscure protocols. For example, do not allow POP3/SMTP/IMAP see
500 * CVE-2013-0249.
501 *
502 * Restricting protocols is only supported from 7.19.4 upwards.
503 */
8a8f5840 504#if LIBCURL_VERSION_NUM >= 0x071304
9e550b32
MB
505 curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
506 curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
8a8f5840 507#endif
fb6d1bbd 508
769ce76d 509#ifdef DEBUG_VERBOSE
9e550b32 510 curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
769ce76d 511#endif
9e550b32 512 }
769ce76d 513
ff5ca166 514 QLIST_INIT(&state->sockets);
769ce76d
AG
515 state->s = s;
516
3ce6a729 517 return 0;
769ce76d
AG
518}
519
456af346 520/* Called with s->mutex held. */
769ce76d
AG
521static void curl_clean_state(CURLState *s)
522{
675a7756
PB
523 int j;
524 for (j = 0; j < CURL_NUM_ACB; j++) {
525 assert(!s->acb[j]);
526 }
527
769ce76d
AG
528 if (s->s->multi)
529 curl_multi_remove_handle(s->s->multi, s->curl);
ff5ca166
HR
530
531 while (!QLIST_EMPTY(&s->sockets)) {
532 CURLSocket *socket = QLIST_FIRST(&s->sockets);
533
534 QLIST_REMOVE(socket, next);
535 g_free(socket);
536 }
537
769ce76d 538 s->in_use = 0;
2bb5c936 539
709f2132 540 qemu_co_enter_next(&s->s->free_state_waitq, &s->s->mutex);
769ce76d
AG
541}
542
8e6d58cd
KW
543static void curl_parse_filename(const char *filename, QDict *options,
544 Error **errp)
769ce76d 545{
46f5ac20 546 qdict_put_str(options, CURL_BLOCK_OPT_URL, filename);
8e6d58cd
KW
547}
548
63f0f45f
SH
549static void curl_detach_aio_context(BlockDriverState *bs)
550{
551 BDRVCURLState *s = bs->opaque;
552 int i;
553
456af346 554 qemu_mutex_lock(&s->mutex);
63f0f45f
SH
555 for (i = 0; i < CURL_NUM_STATES; i++) {
556 if (s->states[i].in_use) {
557 curl_clean_state(&s->states[i]);
558 }
559 if (s->states[i].curl) {
560 curl_easy_cleanup(s->states[i].curl);
561 s->states[i].curl = NULL;
562 }
f7047c2d
MA
563 g_free(s->states[i].orig_buf);
564 s->states[i].orig_buf = NULL;
63f0f45f
SH
565 }
566 if (s->multi) {
567 curl_multi_cleanup(s->multi);
568 s->multi = NULL;
569 }
456af346 570 qemu_mutex_unlock(&s->mutex);
63f0f45f
SH
571
572 timer_del(&s->timer);
573}
574
575static void curl_attach_aio_context(BlockDriverState *bs,
576 AioContext *new_context)
577{
578 BDRVCURLState *s = bs->opaque;
579
580 aio_timer_init(new_context, &s->timer,
581 QEMU_CLOCK_REALTIME, SCALE_NS,
582 curl_multi_timeout_do, s);
583
584 assert(!s->multi);
585 s->multi = curl_multi_init();
586 s->aio_context = new_context;
587 curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
588#ifdef NEED_CURL_TIMER_CALLBACK
589 curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
590 curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
591#endif
592}
593
8e6d58cd
KW
594static QemuOptsList runtime_opts = {
595 .name = "curl",
596 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
597 .desc = {
598 {
e3542c67 599 .name = CURL_BLOCK_OPT_URL,
8e6d58cd
KW
600 .type = QEMU_OPT_STRING,
601 .help = "URL to open",
602 },
603 {
e3542c67 604 .name = CURL_BLOCK_OPT_READAHEAD,
8e6d58cd
KW
605 .type = QEMU_OPT_SIZE,
606 .help = "Readahead size",
607 },
97a3ea57
MB
608 {
609 .name = CURL_BLOCK_OPT_SSLVERIFY,
610 .type = QEMU_OPT_BOOL,
611 .help = "Verify SSL certificate"
612 },
212aefaa
DHB
613 {
614 .name = CURL_BLOCK_OPT_TIMEOUT,
615 .type = QEMU_OPT_NUMBER,
616 .help = "Curl timeout"
617 },
a94f83d9
RJ
618 {
619 .name = CURL_BLOCK_OPT_COOKIE,
620 .type = QEMU_OPT_STRING,
621 .help = "Pass the cookie or list of cookies with each request"
622 },
327c8ebd
PK
623 {
624 .name = CURL_BLOCK_OPT_COOKIE_SECRET,
625 .type = QEMU_OPT_STRING,
626 .help = "ID of secret used as cookie passed with each request"
627 },
1bff9606
DB
628 {
629 .name = CURL_BLOCK_OPT_USERNAME,
630 .type = QEMU_OPT_STRING,
631 .help = "Username for HTTP auth"
632 },
633 {
634 .name = CURL_BLOCK_OPT_PASSWORD_SECRET,
635 .type = QEMU_OPT_STRING,
636 .help = "ID of secret used as password for HTTP auth",
637 },
638 {
639 .name = CURL_BLOCK_OPT_PROXY_USERNAME,
640 .type = QEMU_OPT_STRING,
641 .help = "Username for HTTP proxy auth"
642 },
643 {
644 .name = CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
645 .type = QEMU_OPT_STRING,
646 .help = "ID of secret used as password for HTTP proxy auth",
647 },
8e6d58cd
KW
648 { /* end of list */ }
649 },
650};
651
1bff9606 652
015a1036
HR
653static int curl_open(BlockDriverState *bs, QDict *options, int flags,
654 Error **errp)
8e6d58cd
KW
655{
656 BDRVCURLState *s = bs->opaque;
657 CURLState *state = NULL;
658 QemuOpts *opts;
659 Error *local_err = NULL;
660 const char *file;
a94f83d9 661 const char *cookie;
327c8ebd 662 const char *cookie_secret;
8e6d58cd 663 double d;
1bff9606 664 const char *secretid;
34634ca2 665 const char *protocol_delimiter;
2d25964d 666 int ret;
8e6d58cd 667
6ceef36a
KW
668 ret = bdrv_apply_auto_read_only(bs, "curl driver does not support writes",
669 errp);
670 if (ret < 0) {
671 return ret;
a7cea2ba
RJ
672 }
673
2d25964d
JC
674 if (!libcurl_initialized) {
675 ret = curl_global_init(CURL_GLOBAL_ALL);
676 if (ret) {
677 error_setg(errp, "libcurl initialization failed with %d", ret);
678 return -EIO;
679 }
680 libcurl_initialized = true;
681 }
682
456af346 683 qemu_mutex_init(&s->mutex);
87ea75d5 684 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
8e6d58cd 685 qemu_opts_absorb_qdict(opts, options, &local_err);
84d18f06 686 if (local_err) {
2a94fee3 687 error_propagate(errp, local_err);
8e6d58cd
KW
688 goto out_noclean;
689 }
690
e3542c67 691 s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
712b64e8 692 CURL_BLOCK_OPT_READAHEAD_DEFAULT);
c76f4952 693 if ((s->readahead_size & 0x1ff) != 0) {
2a94fee3
PB
694 error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
695 s->readahead_size);
c76f4952
N
696 goto out_noclean;
697 }
698
212aefaa 699 s->timeout = qemu_opt_get_number(opts, CURL_BLOCK_OPT_TIMEOUT,
712b64e8 700 CURL_BLOCK_OPT_TIMEOUT_DEFAULT);
f76faeda
RJ
701 if (s->timeout > CURL_TIMEOUT_MAX) {
702 error_setg(errp, "timeout parameter is too large or negative");
703 goto out_noclean;
704 }
212aefaa 705
712b64e8
HR
706 s->sslverify = qemu_opt_get_bool(opts, CURL_BLOCK_OPT_SSLVERIFY,
707 CURL_BLOCK_OPT_SSLVERIFY_DEFAULT);
97a3ea57 708
a94f83d9 709 cookie = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE);
327c8ebd
PK
710 cookie_secret = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE_SECRET);
711
712 if (cookie && cookie_secret) {
713 error_setg(errp,
714 "curl driver cannot handle both cookie and cookie secret");
715 goto out_noclean;
716 }
717
718 if (cookie_secret) {
719 s->cookie = qcrypto_secret_lookup_as_utf8(cookie_secret, errp);
720 if (!s->cookie) {
721 goto out_noclean;
722 }
723 } else {
724 s->cookie = g_strdup(cookie);
725 }
a94f83d9 726
e3542c67 727 file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
8e6d58cd 728 if (file == NULL) {
2a94fee3 729 error_setg(errp, "curl block driver requires an 'url' option");
8e6d58cd
KW
730 goto out_noclean;
731 }
732
34634ca2
HR
733 if (!strstart(file, bs->drv->protocol_name, &protocol_delimiter) ||
734 !strstart(protocol_delimiter, "://", NULL))
735 {
736 error_setg(errp, "%s curl driver cannot handle the URL '%s' (does not "
737 "start with '%s://')", bs->drv->protocol_name, file,
738 bs->drv->protocol_name);
739 goto out_noclean;
740 }
741
1bff9606
DB
742 s->username = g_strdup(qemu_opt_get(opts, CURL_BLOCK_OPT_USERNAME));
743 secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PASSWORD_SECRET);
744
745 if (secretid) {
746 s->password = qcrypto_secret_lookup_as_utf8(secretid, errp);
747 if (!s->password) {
748 goto out_noclean;
749 }
750 }
751
752 s->proxyusername = g_strdup(
753 qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_USERNAME));
754 secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET);
755 if (secretid) {
756 s->proxypassword = qcrypto_secret_lookup_as_utf8(secretid, errp);
757 if (!s->proxypassword) {
758 goto out_noclean;
759 }
760 }
761
ed2a66de 762 trace_curl_open(file);
709f2132 763 qemu_co_queue_init(&s->free_state_waitq);
63f0f45f 764 s->aio_context = bdrv_get_aio_context(bs);
8e6d58cd 765 s->url = g_strdup(file);
456af346 766 qemu_mutex_lock(&s->mutex);
3ce6a729 767 state = curl_find_state(s);
456af346 768 qemu_mutex_unlock(&s->mutex);
3ce6a729 769 if (!state) {
769ce76d 770 goto out_noclean;
3ce6a729 771 }
769ce76d
AG
772
773 // Get file size
774
3ce6a729
PB
775 if (curl_init_state(s, state) < 0) {
776 goto out;
777 }
778
3494d650 779 s->accept_range = false;
769ce76d 780 curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
3494d650
FZ
781 curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
782 curl_header_cb);
783 curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
769ce76d
AG
784 if (curl_easy_perform(state->curl))
785 goto out;
a41c4578 786 if (curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) {
769ce76d 787 goto out;
a41c4578
TG
788 }
789 /* Prior CURL 7.19.4 return value of 0 could mean that the file size is not
790 * know or the size is zero. From 7.19.4 CURL returns -1 if size is not
50d6a8a3 791 * known and zero if it is really zero-length file. */
a41c4578
TG
792#if LIBCURL_VERSION_NUM >= 0x071304
793 if (d < 0) {
794 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
795 "Server didn't report file size.");
796 goto out;
797 }
798#else
799 if (d <= 0) {
800 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
801 "Unknown file size or zero-length file.");
802 goto out;
803 }
804#endif
805
2125e5ea 806 s->len = d;
a41c4578 807
3494d650
FZ
808 if ((!strncasecmp(s->url, "http://", strlen("http://"))
809 || !strncasecmp(s->url, "https://", strlen("https://")))
810 && !s->accept_range) {
811 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
812 "Server does not support 'range' (byte ranges).");
813 goto out;
814 }
ed2a66de 815 trace_curl_open_size(s->len);
769ce76d 816
456af346 817 qemu_mutex_lock(&s->mutex);
769ce76d 818 curl_clean_state(state);
456af346 819 qemu_mutex_unlock(&s->mutex);
769ce76d
AG
820 curl_easy_cleanup(state->curl);
821 state->curl = NULL;
822
63f0f45f 823 curl_attach_aio_context(bs, bdrv_get_aio_context(bs));
769ce76d 824
8e6d58cd 825 qemu_opts_del(opts);
769ce76d
AG
826 return 0;
827
828out:
acd7fdc6 829 error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
769ce76d
AG
830 curl_easy_cleanup(state->curl);
831 state->curl = NULL;
832out_noclean:
456af346 833 qemu_mutex_destroy(&s->mutex);
a94f83d9 834 g_free(s->cookie);
8e6d58cd 835 g_free(s->url);
996922de
JC
836 g_free(s->username);
837 g_free(s->proxyusername);
838 g_free(s->proxypassword);
8e6d58cd 839 qemu_opts_del(opts);
769ce76d
AG
840 return -EINVAL;
841}
842
28256d82 843static void curl_setup_preadv(BlockDriverState *bs, CURLAIOCB *acb)
769ce76d 844{
769ce76d 845 CURLState *state;
b69cdef8 846 int running;
769ce76d 847
1919631e 848 BDRVCURLState *s = bs->opaque;
769ce76d 849
2125e5ea
PB
850 uint64_t start = acb->offset;
851 uint64_t end;
769ce76d 852
ba3186c4 853 qemu_mutex_lock(&s->mutex);
1919631e 854
769ce76d
AG
855 // In case we have the requested data already (e.g. read-ahead),
856 // we can just call the callback and be done.
28256d82
PB
857 if (curl_find_buf(s, start, acb->bytes, acb)) {
858 goto out;
769ce76d
AG
859 }
860
861 // No cache found, so let's start a new request
3ce6a729
PB
862 for (;;) {
863 state = curl_find_state(s);
864 if (state) {
865 break;
866 }
709f2132 867 qemu_co_queue_wait(&s->free_state_waitq, &s->mutex);
3ce6a729
PB
868 }
869
870 if (curl_init_state(s, state) < 0) {
871 curl_clean_state(state);
28256d82 872 acb->ret = -EIO;
1919631e 873 goto out;
363c3c85 874 }
769ce76d
AG
875
876 acb->start = 0;
2125e5ea 877 acb->end = MIN(acb->bytes, s->len - start);
769ce76d
AG
878
879 state->buf_off = 0;
f7047c2d 880 g_free(state->orig_buf);
769ce76d 881 state->buf_start = start;
4e504535
HR
882 state->buf_len = MIN(acb->end + s->readahead_size, s->len - start);
883 end = start + state->buf_len - 1;
8dc7a772
KW
884 state->orig_buf = g_try_malloc(state->buf_len);
885 if (state->buf_len && state->orig_buf == NULL) {
886 curl_clean_state(state);
28256d82 887 acb->ret = -ENOMEM;
1919631e 888 goto out;
8dc7a772 889 }
769ce76d
AG
890 state->acb[0] = acb;
891
2125e5ea 892 snprintf(state->range, 127, "%" PRIu64 "-%" PRIu64, start, end);
ed2a66de 893 trace_curl_setup_preadv(acb->bytes, start, state->range);
769ce76d
AG
894 curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
895
896 curl_multi_add_handle(s->multi, state->curl);
769ce76d 897
b69cdef8
MB
898 /* Tell curl it needs to kick things off */
899 curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
1919631e
PB
900
901out:
ba3186c4 902 qemu_mutex_unlock(&s->mutex);
363c3c85
NT
903}
904
28256d82
PB
905static int coroutine_fn curl_co_preadv(BlockDriverState *bs,
906 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
363c3c85 907{
28256d82
PB
908 CURLAIOCB acb = {
909 .co = qemu_coroutine_self(),
910 .ret = -EINPROGRESS,
911 .qiov = qiov,
912 .offset = offset,
913 .bytes = bytes
914 };
915
916 curl_setup_preadv(bs, &acb);
917 while (acb.ret == -EINPROGRESS) {
918 qemu_coroutine_yield();
919 }
920 return acb.ret;
769ce76d
AG
921}
922
769ce76d
AG
923static void curl_close(BlockDriverState *bs)
924{
925 BDRVCURLState *s = bs->opaque;
769ce76d 926
ed2a66de 927 trace_curl_close();
63f0f45f 928 curl_detach_aio_context(bs);
ba3186c4 929 qemu_mutex_destroy(&s->mutex);
031fd1be 930
a94f83d9 931 g_free(s->cookie);
45724d6d 932 g_free(s->url);
996922de
JC
933 g_free(s->username);
934 g_free(s->proxyusername);
935 g_free(s->proxypassword);
769ce76d
AG
936}
937
938static int64_t curl_getlength(BlockDriverState *bs)
939{
940 BDRVCURLState *s = bs->opaque;
941 return s->len;
942}
943
937c007b
HR
944static void curl_refresh_filename(BlockDriverState *bs)
945{
946 BDRVCURLState *s = bs->opaque;
947
948 /* "readahead" and "timeout" do not change the guest-visible data,
949 * so ignore them */
950 if (s->sslverify != CURL_BLOCK_OPT_SSLVERIFY_DEFAULT ||
951 s->cookie || s->username || s->password || s->proxyusername ||
952 s->proxypassword)
953 {
954 return;
955 }
956
957 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), s->url);
958}
959
960
2654267c
HR
961static const char *const curl_strong_runtime_opts[] = {
962 CURL_BLOCK_OPT_URL,
963 CURL_BLOCK_OPT_SSLVERIFY,
964 CURL_BLOCK_OPT_COOKIE,
965 CURL_BLOCK_OPT_COOKIE_SECRET,
966 CURL_BLOCK_OPT_USERNAME,
967 CURL_BLOCK_OPT_PASSWORD_SECRET,
968 CURL_BLOCK_OPT_PROXY_USERNAME,
969 CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
970
971 NULL
972};
973
769ce76d 974static BlockDriver bdrv_http = {
63f0f45f
SH
975 .format_name = "http",
976 .protocol_name = "http",
977
978 .instance_size = sizeof(BDRVCURLState),
979 .bdrv_parse_filename = curl_parse_filename,
980 .bdrv_file_open = curl_open,
981 .bdrv_close = curl_close,
982 .bdrv_getlength = curl_getlength,
769ce76d 983
28256d82 984 .bdrv_co_preadv = curl_co_preadv,
769ce76d 985
63f0f45f
SH
986 .bdrv_detach_aio_context = curl_detach_aio_context,
987 .bdrv_attach_aio_context = curl_attach_aio_context,
2654267c 988
937c007b 989 .bdrv_refresh_filename = curl_refresh_filename,
2654267c 990 .strong_runtime_opts = curl_strong_runtime_opts,
769ce76d
AG
991};
992
993static BlockDriver bdrv_https = {
63f0f45f
SH
994 .format_name = "https",
995 .protocol_name = "https",
769ce76d 996
63f0f45f
SH
997 .instance_size = sizeof(BDRVCURLState),
998 .bdrv_parse_filename = curl_parse_filename,
999 .bdrv_file_open = curl_open,
1000 .bdrv_close = curl_close,
1001 .bdrv_getlength = curl_getlength,
769ce76d 1002
28256d82 1003 .bdrv_co_preadv = curl_co_preadv,
63f0f45f
SH
1004
1005 .bdrv_detach_aio_context = curl_detach_aio_context,
1006 .bdrv_attach_aio_context = curl_attach_aio_context,
2654267c 1007
937c007b 1008 .bdrv_refresh_filename = curl_refresh_filename,
2654267c 1009 .strong_runtime_opts = curl_strong_runtime_opts,
769ce76d
AG
1010};
1011
1012static BlockDriver bdrv_ftp = {
63f0f45f
SH
1013 .format_name = "ftp",
1014 .protocol_name = "ftp",
1015
1016 .instance_size = sizeof(BDRVCURLState),
1017 .bdrv_parse_filename = curl_parse_filename,
1018 .bdrv_file_open = curl_open,
1019 .bdrv_close = curl_close,
1020 .bdrv_getlength = curl_getlength,
769ce76d 1021
28256d82 1022 .bdrv_co_preadv = curl_co_preadv,
769ce76d 1023
63f0f45f
SH
1024 .bdrv_detach_aio_context = curl_detach_aio_context,
1025 .bdrv_attach_aio_context = curl_attach_aio_context,
2654267c 1026
937c007b 1027 .bdrv_refresh_filename = curl_refresh_filename,
2654267c 1028 .strong_runtime_opts = curl_strong_runtime_opts,
769ce76d
AG
1029};
1030
1031static BlockDriver bdrv_ftps = {
63f0f45f
SH
1032 .format_name = "ftps",
1033 .protocol_name = "ftps",
769ce76d 1034
63f0f45f
SH
1035 .instance_size = sizeof(BDRVCURLState),
1036 .bdrv_parse_filename = curl_parse_filename,
1037 .bdrv_file_open = curl_open,
1038 .bdrv_close = curl_close,
1039 .bdrv_getlength = curl_getlength,
769ce76d 1040
28256d82 1041 .bdrv_co_preadv = curl_co_preadv,
63f0f45f
SH
1042
1043 .bdrv_detach_aio_context = curl_detach_aio_context,
1044 .bdrv_attach_aio_context = curl_attach_aio_context,
2654267c 1045
937c007b 1046 .bdrv_refresh_filename = curl_refresh_filename,
2654267c 1047 .strong_runtime_opts = curl_strong_runtime_opts,
769ce76d
AG
1048};
1049
769ce76d
AG
1050static void curl_block_init(void)
1051{
1052 bdrv_register(&bdrv_http);
1053 bdrv_register(&bdrv_https);
1054 bdrv_register(&bdrv_ftp);
1055 bdrv_register(&bdrv_ftps);
769ce76d
AG
1056}
1057
1058block_init(curl_block_init);