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