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