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