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