]> git.proxmox.com Git - mirror_qemu.git/blame - block/curl.c
e1000e: Fix ICR "Other" causes clear logic
[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
AG
78
79#define FIND_RET_NONE 0
80#define FIND_RET_OK 1
81#define FIND_RET_WAIT 2
82
e3542c67
MB
83#define CURL_BLOCK_OPT_URL "url"
84#define CURL_BLOCK_OPT_READAHEAD "readahead"
97a3ea57 85#define CURL_BLOCK_OPT_SSLVERIFY "sslverify"
212aefaa 86#define CURL_BLOCK_OPT_TIMEOUT "timeout"
a94f83d9 87#define CURL_BLOCK_OPT_COOKIE "cookie"
1bff9606
DB
88#define CURL_BLOCK_OPT_USERNAME "username"
89#define CURL_BLOCK_OPT_PASSWORD_SECRET "password-secret"
90#define CURL_BLOCK_OPT_PROXY_USERNAME "proxy-username"
91#define CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET "proxy-password-secret"
e3542c67 92
769ce76d
AG
93struct BDRVCURLState;
94
95typedef struct CURLAIOCB {
7c84b1b8 96 BlockAIOCB common;
769ce76d 97 QEMUIOVector *qiov;
363c3c85
NT
98
99 int64_t sector_num;
100 int nb_sectors;
101
769ce76d
AG
102 size_t start;
103 size_t end;
104} CURLAIOCB;
105
ff5ca166
HR
106typedef struct CURLSocket {
107 int fd;
108 QLIST_ENTRY(CURLSocket) next;
109} CURLSocket;
110
769ce76d
AG
111typedef struct CURLState
112{
113 struct BDRVCURLState *s;
114 CURLAIOCB *acb[CURL_NUM_ACB];
115 CURL *curl;
ff5ca166 116 QLIST_HEAD(, CURLSocket) sockets;
769ce76d
AG
117 char *orig_buf;
118 size_t buf_start;
119 size_t buf_off;
120 size_t buf_len;
121 char range[128];
122 char errmsg[CURL_ERROR_SIZE];
123 char in_use;
124} CURLState;
125
126typedef struct BDRVCURLState {
127 CURLM *multi;
031fd1be 128 QEMUTimer timer;
769ce76d
AG
129 size_t len;
130 CURLState states[CURL_NUM_STATES];
131 char *url;
c76f4952 132 size_t readahead_size;
97a3ea57 133 bool sslverify;
f76faeda 134 uint64_t timeout;
a94f83d9 135 char *cookie;
3494d650 136 bool accept_range;
63f0f45f 137 AioContext *aio_context;
ba3186c4 138 QemuMutex mutex;
1bff9606
DB
139 char *username;
140 char *password;
141 char *proxyusername;
142 char *proxypassword;
769ce76d
AG
143} BDRVCURLState;
144
145static void curl_clean_state(CURLState *s);
146static void curl_multi_do(void *arg);
838ef602 147static void curl_multi_read(void *arg);
769ce76d 148
031fd1be 149#ifdef NEED_CURL_TIMER_CALLBACK
4b519b9f 150/* Called from curl_multi_do_locked, with s->mutex held. */
031fd1be
PM
151static int curl_timer_cb(CURLM *multi, long timeout_ms, void *opaque)
152{
153 BDRVCURLState *s = opaque;
154
155 DPRINTF("CURL: timer callback timeout_ms %ld\n", timeout_ms);
156 if (timeout_ms == -1) {
157 timer_del(&s->timer);
158 } else {
159 int64_t timeout_ns = (int64_t)timeout_ms * 1000 * 1000;
160 timer_mod(&s->timer,
161 qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ns);
162 }
163 return 0;
164}
165#endif
166
4b519b9f 167/* Called from curl_multi_do_locked, with s->mutex held. */
769ce76d 168static int curl_sock_cb(CURL *curl, curl_socket_t fd, int action,
63f0f45f 169 void *userp, void *sp)
769ce76d 170{
63f0f45f 171 BDRVCURLState *s;
838ef602 172 CURLState *state = NULL;
ff5ca166
HR
173 CURLSocket *socket;
174
838ef602 175 curl_easy_getinfo(curl, CURLINFO_PRIVATE, (char **)&state);
63f0f45f 176 s = state->s;
838ef602 177
ff5ca166
HR
178 QLIST_FOREACH(socket, &state->sockets, next) {
179 if (socket->fd == fd) {
180 if (action == CURL_POLL_REMOVE) {
181 QLIST_REMOVE(socket, next);
182 g_free(socket);
183 }
184 break;
185 }
186 }
187 if (!socket) {
188 socket = g_new0(CURLSocket, 1);
189 socket->fd = fd;
190 QLIST_INSERT_HEAD(&state->sockets, socket, next);
191 }
192 socket = NULL;
193
92b6a160 194 DPRINTF("CURL (AIO): Sock action %d on fd %d\n", action, (int)fd);
769ce76d
AG
195 switch (action) {
196 case CURL_POLL_IN:
dca21ef2 197 aio_set_fd_handler(s->aio_context, fd, false,
f6a51c84 198 curl_multi_read, NULL, NULL, state);
769ce76d
AG
199 break;
200 case CURL_POLL_OUT:
dca21ef2 201 aio_set_fd_handler(s->aio_context, fd, false,
f6a51c84 202 NULL, curl_multi_do, NULL, state);
769ce76d
AG
203 break;
204 case CURL_POLL_INOUT:
dca21ef2 205 aio_set_fd_handler(s->aio_context, fd, false,
f6a51c84 206 curl_multi_read, curl_multi_do, NULL, state);
769ce76d
AG
207 break;
208 case CURL_POLL_REMOVE:
dca21ef2 209 aio_set_fd_handler(s->aio_context, fd, false,
f6a51c84 210 NULL, NULL, NULL, NULL);
769ce76d
AG
211 break;
212 }
213
214 return 0;
215}
216
4b519b9f 217/* Called from curl_multi_do_locked, with s->mutex held. */
3494d650 218static size_t curl_header_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
769ce76d 219{
3494d650 220 BDRVCURLState *s = opaque;
769ce76d 221 size_t realsize = size * nmemb;
3494d650 222 const char *accept_line = "Accept-Ranges: bytes";
769ce76d 223
3494d650
FZ
224 if (realsize >= strlen(accept_line)
225 && strncmp((char *)ptr, accept_line, strlen(accept_line)) == 0) {
226 s->accept_range = true;
0bfcd599 227 }
769ce76d
AG
228
229 return realsize;
230}
231
4b519b9f 232/* Called from curl_multi_do_locked, with s->mutex held. */
769ce76d
AG
233static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
234{
235 CURLState *s = ((CURLState*)opaque);
236 size_t realsize = size * nmemb;
237 int i;
238
0bfcd599 239 DPRINTF("CURL: Just reading %zd bytes\n", realsize);
769ce76d 240
4e767657
HR
241 if (!s || !s->orig_buf) {
242 goto read_end;
243 }
769ce76d 244
6d4b9e55
FZ
245 if (s->buf_off >= s->buf_len) {
246 /* buffer full, read nothing */
4e767657 247 goto read_end;
6d4b9e55
FZ
248 }
249 realsize = MIN(realsize, s->buf_len - s->buf_off);
769ce76d
AG
250 memcpy(s->orig_buf + s->buf_off, ptr, realsize);
251 s->buf_off += realsize;
252
253 for(i=0; i<CURL_NUM_ACB; i++) {
254 CURLAIOCB *acb = s->acb[i];
255
256 if (!acb)
257 continue;
258
259 if ((s->buf_off >= acb->end)) {
4e504535
HR
260 size_t request_length = acb->nb_sectors * BDRV_SECTOR_SIZE;
261
03396148
MT
262 qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,
263 acb->end - acb->start);
4e504535
HR
264
265 if (acb->end - acb->start < request_length) {
266 size_t offset = acb->end - acb->start;
267 qemu_iovec_memset(acb->qiov, offset, 0,
268 request_length - offset);
269 }
270
4b519b9f 271 qemu_mutex_unlock(&s->s->mutex);
769ce76d 272 acb->common.cb(acb->common.opaque, 0);
4b519b9f 273 qemu_mutex_lock(&s->s->mutex);
8007429a 274 qemu_aio_unref(acb);
769ce76d
AG
275 s->acb[i] = NULL;
276 }
277 }
278
4e767657
HR
279read_end:
280 /* curl will error out if we do not return this value */
281 return size * nmemb;
769ce76d
AG
282}
283
c79bef68 284/* Called with s->mutex held. */
769ce76d
AG
285static int curl_find_buf(BDRVCURLState *s, size_t start, size_t len,
286 CURLAIOCB *acb)
287{
288 int i;
289 size_t end = start + len;
4e504535
HR
290 size_t clamped_end = MIN(end, s->len);
291 size_t clamped_len = clamped_end - start;
769ce76d
AG
292
293 for (i=0; i<CURL_NUM_STATES; i++) {
294 CURLState *state = &s->states[i];
295 size_t buf_end = (state->buf_start + state->buf_off);
296 size_t buf_fend = (state->buf_start + state->buf_len);
297
298 if (!state->orig_buf)
299 continue;
300 if (!state->buf_off)
301 continue;
302
303 // Does the existing buffer cover our section?
304 if ((start >= state->buf_start) &&
305 (start <= buf_end) &&
4e504535
HR
306 (clamped_end >= state->buf_start) &&
307 (clamped_end <= buf_end))
769ce76d
AG
308 {
309 char *buf = state->orig_buf + (start - state->buf_start);
310
4e504535
HR
311 qemu_iovec_from_buf(acb->qiov, 0, buf, clamped_len);
312 if (clamped_len < len) {
313 qemu_iovec_memset(acb->qiov, clamped_len, 0, len - clamped_len);
314 }
769ce76d
AG
315 return FIND_RET_OK;
316 }
317
318 // Wait for unfinished chunks
b7079df4
MB
319 if (state->in_use &&
320 (start >= state->buf_start) &&
769ce76d 321 (start <= buf_fend) &&
4e504535
HR
322 (clamped_end >= state->buf_start) &&
323 (clamped_end <= buf_fend))
769ce76d
AG
324 {
325 int j;
326
327 acb->start = start - state->buf_start;
4e504535 328 acb->end = acb->start + clamped_len;
769ce76d
AG
329
330 for (j=0; j<CURL_NUM_ACB; j++) {
331 if (!state->acb[j]) {
332 state->acb[j] = acb;
333 return FIND_RET_WAIT;
334 }
335 }
336 }
337 }
338
339 return FIND_RET_NONE;
340}
341
ba3186c4 342/* Called with s->mutex held. */
838ef602 343static void curl_multi_check_completion(BDRVCURLState *s)
769ce76d 344{
769ce76d
AG
345 int msgs_in_queue;
346
769ce76d
AG
347 /* Try to find done transfers, so we can free the easy
348 * handle again. */
1f2cead3 349 for (;;) {
769ce76d
AG
350 CURLMsg *msg;
351 msg = curl_multi_info_read(s->multi, &msgs_in_queue);
352
1f2cead3 353 /* Quit when there are no more completions */
769ce76d
AG
354 if (!msg)
355 break;
769ce76d 356
1f2cead3
MB
357 if (msg->msg == CURLMSG_DONE) {
358 CURLState *state = NULL;
359 curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,
360 (char **)&state);
361
362 /* ACBs for successful messages get completed in curl_read_cb */
363 if (msg->data.result != CURLE_OK) {
364 int i;
796a060b
RJ
365 static int errcount = 100;
366
367 /* Don't lose the original error message from curl, since
368 * it contains extra data.
369 */
370 if (errcount > 0) {
371 error_report("curl: %s", state->errmsg);
372 if (--errcount == 0) {
373 error_report("curl: further errors suppressed");
374 }
375 }
376
1f2cead3
MB
377 for (i = 0; i < CURL_NUM_ACB; i++) {
378 CURLAIOCB *acb = state->acb[i];
379
380 if (acb == NULL) {
381 continue;
f785a5ae 382 }
f785a5ae 383
ba3186c4 384 qemu_mutex_unlock(&s->mutex);
eb048026 385 acb->common.cb(acb->common.opaque, -EIO);
ba3186c4 386 qemu_mutex_lock(&s->mutex);
8007429a 387 qemu_aio_unref(acb);
1f2cead3
MB
388 state->acb[i] = NULL;
389 }
769ce76d 390 }
1f2cead3
MB
391
392 curl_clean_state(state);
393 break;
769ce76d 394 }
1f2cead3 395 }
769ce76d
AG
396}
397
ba3186c4 398/* Called with s->mutex held. */
9d456654 399static void curl_multi_do_locked(CURLState *s)
031fd1be 400{
ff5ca166 401 CURLSocket *socket, *next_socket;
031fd1be
PM
402 int running;
403 int r;
404
838ef602 405 if (!s->s->multi) {
031fd1be
PM
406 return;
407 }
408
ff5ca166
HR
409 /* Need to use _SAFE because curl_multi_socket_action() may trigger
410 * curl_sock_cb() which might modify this list */
411 QLIST_FOREACH_SAFE(socket, &s->sockets, next, next_socket) {
412 do {
413 r = curl_multi_socket_action(s->s->multi, socket->fd, 0, &running);
414 } while (r == CURLM_CALL_MULTI_PERFORM);
415 }
838ef602
MB
416}
417
9d456654
PB
418static void curl_multi_do(void *arg)
419{
420 CURLState *s = (CURLState *)arg;
421
ba3186c4 422 qemu_mutex_lock(&s->s->mutex);
9d456654 423 curl_multi_do_locked(s);
ba3186c4 424 qemu_mutex_unlock(&s->s->mutex);
9d456654
PB
425}
426
838ef602
MB
427static void curl_multi_read(void *arg)
428{
429 CURLState *s = (CURLState *)arg;
430
ba3186c4 431 qemu_mutex_lock(&s->s->mutex);
9d456654 432 curl_multi_do_locked(s);
838ef602 433 curl_multi_check_completion(s->s);
ba3186c4 434 qemu_mutex_unlock(&s->s->mutex);
031fd1be
PM
435}
436
437static void curl_multi_timeout_do(void *arg)
438{
439#ifdef NEED_CURL_TIMER_CALLBACK
440 BDRVCURLState *s = (BDRVCURLState *)arg;
441 int running;
442
443 if (!s->multi) {
444 return;
445 }
446
ba3186c4 447 qemu_mutex_lock(&s->mutex);
031fd1be
PM
448 curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
449
838ef602 450 curl_multi_check_completion(s);
ba3186c4 451 qemu_mutex_unlock(&s->mutex);
031fd1be
PM
452#else
453 abort();
454#endif
455}
456
c79bef68 457/* Called with s->mutex held. */
a2f468e4 458static CURLState *curl_init_state(BlockDriverState *bs, BDRVCURLState *s)
769ce76d
AG
459{
460 CURLState *state = NULL;
461 int i, j;
462
463 do {
464 for (i=0; i<CURL_NUM_STATES; i++) {
465 for (j=0; j<CURL_NUM_ACB; j++)
466 if (s->states[i].acb[j])
467 continue;
468 if (s->states[i].in_use)
469 continue;
470
471 state = &s->states[i];
472 state->in_use = 1;
473 break;
474 }
475 if (!state) {
c79bef68 476 qemu_mutex_unlock(&s->mutex);
a2f468e4 477 aio_poll(bdrv_get_aio_context(bs), true);
c79bef68 478 qemu_mutex_lock(&s->mutex);
769ce76d
AG
479 }
480 } while(!state);
481
9e550b32
MB
482 if (!state->curl) {
483 state->curl = curl_easy_init();
484 if (!state->curl) {
485 return NULL;
486 }
487 curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
97a3ea57
MB
488 curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,
489 (long) s->sslverify);
a94f83d9
RJ
490 if (s->cookie) {
491 curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);
492 }
f76faeda 493 curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);
9e550b32
MB
494 curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,
495 (void *)curl_read_cb);
496 curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
497 curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
498 curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
499 curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
500 curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
501 curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
502 curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
503
1bff9606
DB
504 if (s->username) {
505 curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);
506 }
507 if (s->password) {
508 curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);
509 }
510 if (s->proxyusername) {
511 curl_easy_setopt(state->curl,
512 CURLOPT_PROXYUSERNAME, s->proxyusername);
513 }
514 if (s->proxypassword) {
515 curl_easy_setopt(state->curl,
516 CURLOPT_PROXYPASSWORD, s->proxypassword);
517 }
518
9e550b32
MB
519 /* Restrict supported protocols to avoid security issues in the more
520 * obscure protocols. For example, do not allow POP3/SMTP/IMAP see
521 * CVE-2013-0249.
522 *
523 * Restricting protocols is only supported from 7.19.4 upwards.
524 */
8a8f5840 525#if LIBCURL_VERSION_NUM >= 0x071304
9e550b32
MB
526 curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
527 curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
8a8f5840 528#endif
fb6d1bbd 529
769ce76d 530#ifdef DEBUG_VERBOSE
9e550b32 531 curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
769ce76d 532#endif
9e550b32 533 }
769ce76d 534
ff5ca166 535 QLIST_INIT(&state->sockets);
769ce76d
AG
536 state->s = s;
537
538 return state;
539}
540
c79bef68 541/* Called with s->mutex held. */
769ce76d
AG
542static void curl_clean_state(CURLState *s)
543{
f00c08cb
PB
544 int j;
545 for (j = 0; j < CURL_NUM_ACB; j++) {
546 assert(!s->acb[j]);
547 }
548
769ce76d
AG
549 if (s->s->multi)
550 curl_multi_remove_handle(s->s->multi, s->curl);
ff5ca166
HR
551
552 while (!QLIST_EMPTY(&s->sockets)) {
553 CURLSocket *socket = QLIST_FIRST(&s->sockets);
554
555 QLIST_REMOVE(socket, next);
556 g_free(socket);
557 }
558
769ce76d
AG
559 s->in_use = 0;
560}
561
8e6d58cd
KW
562static void curl_parse_filename(const char *filename, QDict *options,
563 Error **errp)
769ce76d 564{
e59084b5 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
c79bef68 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 }
c79bef68 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 },
1bff9606
DB
642 {
643 .name = CURL_BLOCK_OPT_USERNAME,
644 .type = QEMU_OPT_STRING,
645 .help = "Username for HTTP auth"
646 },
647 {
648 .name = CURL_BLOCK_OPT_PASSWORD_SECRET,
649 .type = QEMU_OPT_STRING,
650 .help = "ID of secret used as password for HTTP auth",
651 },
652 {
653 .name = CURL_BLOCK_OPT_PROXY_USERNAME,
654 .type = QEMU_OPT_STRING,
655 .help = "Username for HTTP proxy auth"
656 },
657 {
658 .name = CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
659 .type = QEMU_OPT_STRING,
660 .help = "ID of secret used as password for HTTP proxy auth",
661 },
8e6d58cd
KW
662 { /* end of list */ }
663 },
664};
665
1bff9606 666
015a1036
HR
667static int curl_open(BlockDriverState *bs, QDict *options, int flags,
668 Error **errp)
8e6d58cd
KW
669{
670 BDRVCURLState *s = bs->opaque;
671 CURLState *state = NULL;
672 QemuOpts *opts;
673 Error *local_err = NULL;
674 const char *file;
a94f83d9 675 const char *cookie;
8e6d58cd 676 double d;
1bff9606 677 const char *secretid;
34634ca2 678 const char *protocol_delimiter;
8e6d58cd
KW
679
680 static int inited = 0;
681
a7cea2ba 682 if (flags & BDRV_O_RDWR) {
2a94fee3 683 error_setg(errp, "curl block device does not support writes");
a7cea2ba
RJ
684 return -EROFS;
685 }
686
c79bef68 687 qemu_mutex_init(&s->mutex);
87ea75d5 688 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
8e6d58cd 689 qemu_opts_absorb_qdict(opts, options, &local_err);
84d18f06 690 if (local_err) {
2a94fee3 691 error_propagate(errp, local_err);
8e6d58cd
KW
692 goto out_noclean;
693 }
694
e3542c67
MB
695 s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
696 READ_AHEAD_DEFAULT);
c76f4952 697 if ((s->readahead_size & 0x1ff) != 0) {
2a94fee3
PB
698 error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
699 s->readahead_size);
c76f4952
N
700 goto out_noclean;
701 }
702
212aefaa
DHB
703 s->timeout = qemu_opt_get_number(opts, CURL_BLOCK_OPT_TIMEOUT,
704 CURL_TIMEOUT_DEFAULT);
f76faeda
RJ
705 if (s->timeout > CURL_TIMEOUT_MAX) {
706 error_setg(errp, "timeout parameter is too large or negative");
707 goto out_noclean;
708 }
212aefaa 709
97a3ea57
MB
710 s->sslverify = qemu_opt_get_bool(opts, CURL_BLOCK_OPT_SSLVERIFY, true);
711
a94f83d9
RJ
712 cookie = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE);
713 s->cookie = g_strdup(cookie);
714
e3542c67 715 file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
8e6d58cd 716 if (file == NULL) {
2a94fee3 717 error_setg(errp, "curl block driver requires an 'url' option");
8e6d58cd
KW
718 goto out_noclean;
719 }
720
34634ca2
HR
721 if (!strstart(file, bs->drv->protocol_name, &protocol_delimiter) ||
722 !strstart(protocol_delimiter, "://", NULL))
723 {
724 error_setg(errp, "%s curl driver cannot handle the URL '%s' (does not "
725 "start with '%s://')", bs->drv->protocol_name, file,
726 bs->drv->protocol_name);
727 goto out_noclean;
728 }
729
1bff9606
DB
730 s->username = g_strdup(qemu_opt_get(opts, CURL_BLOCK_OPT_USERNAME));
731 secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PASSWORD_SECRET);
732
733 if (secretid) {
734 s->password = qcrypto_secret_lookup_as_utf8(secretid, errp);
735 if (!s->password) {
736 goto out_noclean;
737 }
738 }
739
740 s->proxyusername = g_strdup(
741 qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_USERNAME));
742 secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET);
743 if (secretid) {
744 s->proxypassword = qcrypto_secret_lookup_as_utf8(secretid, errp);
745 if (!s->proxypassword) {
746 goto out_noclean;
747 }
748 }
749
769ce76d
AG
750 if (!inited) {
751 curl_global_init(CURL_GLOBAL_ALL);
752 inited = 1;
753 }
754
d0f2c4c6 755 DPRINTF("CURL: Opening %s\n", file);
63f0f45f 756 s->aio_context = bdrv_get_aio_context(bs);
8e6d58cd 757 s->url = g_strdup(file);
c79bef68 758 qemu_mutex_lock(&s->mutex);
a2f468e4 759 state = curl_init_state(bs, s);
c79bef68 760 qemu_mutex_unlock(&s->mutex);
769ce76d
AG
761 if (!state)
762 goto out_noclean;
763
764 // Get file size
765
3494d650 766 s->accept_range = false;
769ce76d 767 curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
3494d650
FZ
768 curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
769 curl_header_cb);
770 curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
769ce76d
AG
771 if (curl_easy_perform(state->curl))
772 goto out;
a41c4578 773 if (curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) {
769ce76d 774 goto out;
a41c4578
TG
775 }
776 /* Prior CURL 7.19.4 return value of 0 could mean that the file size is not
777 * know or the size is zero. From 7.19.4 CURL returns -1 if size is not
778 * known and zero if it is realy zero-length file. */
779#if LIBCURL_VERSION_NUM >= 0x071304
780 if (d < 0) {
781 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
782 "Server didn't report file size.");
783 goto out;
784 }
785#else
786 if (d <= 0) {
787 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
788 "Unknown file size or zero-length file.");
789 goto out;
790 }
791#endif
792
793 s->len = (size_t)d;
794
3494d650
FZ
795 if ((!strncasecmp(s->url, "http://", strlen("http://"))
796 || !strncasecmp(s->url, "https://", strlen("https://")))
797 && !s->accept_range) {
798 pstrcpy(state->errmsg, CURL_ERROR_SIZE,
799 "Server does not support 'range' (byte ranges).");
800 goto out;
801 }
0bfcd599 802 DPRINTF("CURL: Size = %zd\n", s->len);
769ce76d 803
c79bef68 804 qemu_mutex_lock(&s->mutex);
769ce76d 805 curl_clean_state(state);
c79bef68 806 qemu_mutex_unlock(&s->mutex);
769ce76d
AG
807 curl_easy_cleanup(state->curl);
808 state->curl = NULL;
809
63f0f45f 810 curl_attach_aio_context(bs, bdrv_get_aio_context(bs));
769ce76d 811
8e6d58cd 812 qemu_opts_del(opts);
769ce76d
AG
813 return 0;
814
815out:
acd7fdc6 816 error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
769ce76d
AG
817 curl_easy_cleanup(state->curl);
818 state->curl = NULL;
819out_noclean:
c79bef68 820 qemu_mutex_destroy(&s->mutex);
a94f83d9 821 g_free(s->cookie);
8e6d58cd
KW
822 g_free(s->url);
823 qemu_opts_del(opts);
769ce76d
AG
824 return -EINVAL;
825}
826
d7331bed 827static const AIOCBInfo curl_aiocb_info = {
c16b5a2c 828 .aiocb_size = sizeof(CURLAIOCB),
c16b5a2c
CH
829};
830
363c3c85
NT
831
832static void curl_readv_bh_cb(void *p)
769ce76d 833{
769ce76d 834 CURLState *state;
b69cdef8 835 int running;
1919631e 836 int ret = -EINPROGRESS;
769ce76d 837
363c3c85 838 CURLAIOCB *acb = p;
1919631e
PB
839 BlockDriverState *bs = acb->common.bs;
840 BDRVCURLState *s = bs->opaque;
769ce76d 841
9054d9f6 842 size_t start = acb->sector_num * BDRV_SECTOR_SIZE;
363c3c85 843 size_t end;
769ce76d 844
ba3186c4 845 qemu_mutex_lock(&s->mutex);
1919631e 846
769ce76d
AG
847 // In case we have the requested data already (e.g. read-ahead),
848 // we can just call the callback and be done.
9054d9f6 849 switch (curl_find_buf(s, start, acb->nb_sectors * BDRV_SECTOR_SIZE, acb)) {
769ce76d 850 case FIND_RET_OK:
4b519b9f
PB
851 ret = 0;
852 goto out;
769ce76d 853 case FIND_RET_WAIT:
1919631e 854 goto out;
769ce76d
AG
855 default:
856 break;
857 }
858
859 // No cache found, so let's start a new request
a2f468e4 860 state = curl_init_state(acb->common.bs, s);
363c3c85 861 if (!state) {
1919631e
PB
862 ret = -EIO;
863 goto out;
363c3c85 864 }
769ce76d
AG
865
866 acb->start = 0;
4e504535 867 acb->end = MIN(acb->nb_sectors * BDRV_SECTOR_SIZE, s->len - start);
769ce76d
AG
868
869 state->buf_off = 0;
f7047c2d 870 g_free(state->orig_buf);
769ce76d 871 state->buf_start = start;
4e504535
HR
872 state->buf_len = MIN(acb->end + s->readahead_size, s->len - start);
873 end = start + state->buf_len - 1;
8dc7a772
KW
874 state->orig_buf = g_try_malloc(state->buf_len);
875 if (state->buf_len && state->orig_buf == NULL) {
876 curl_clean_state(state);
1919631e
PB
877 ret = -ENOMEM;
878 goto out;
8dc7a772 879 }
769ce76d
AG
880 state->acb[0] = acb;
881
0bfcd599 882 snprintf(state->range, 127, "%zd-%zd", start, end);
9054d9f6
HR
883 DPRINTF("CURL (AIO): Reading %llu at %zd (%s)\n",
884 (acb->nb_sectors * BDRV_SECTOR_SIZE), start, state->range);
769ce76d
AG
885 curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
886
887 curl_multi_add_handle(s->multi, state->curl);
769ce76d 888
b69cdef8
MB
889 /* Tell curl it needs to kick things off */
890 curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
1919631e
PB
891
892out:
ba3186c4 893 qemu_mutex_unlock(&s->mutex);
1919631e
PB
894 if (ret != -EINPROGRESS) {
895 acb->common.cb(acb->common.opaque, ret);
896 qemu_aio_unref(acb);
897 }
363c3c85
NT
898}
899
7c84b1b8 900static BlockAIOCB *curl_aio_readv(BlockDriverState *bs,
363c3c85 901 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
097310b5 902 BlockCompletionFunc *cb, void *opaque)
363c3c85
NT
903{
904 CURLAIOCB *acb;
905
d7331bed 906 acb = qemu_aio_get(&curl_aiocb_info, bs, cb, opaque);
363c3c85 907
363c3c85
NT
908 acb->qiov = qiov;
909 acb->sector_num = sector_num;
910 acb->nb_sectors = nb_sectors;
911
fffb6e12 912 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs), curl_readv_bh_cb, acb);
769ce76d
AG
913 return &acb->common;
914}
915
769ce76d
AG
916static void curl_close(BlockDriverState *bs)
917{
918 BDRVCURLState *s = bs->opaque;
769ce76d 919
d0f2c4c6 920 DPRINTF("CURL: Close\n");
63f0f45f 921 curl_detach_aio_context(bs);
ba3186c4 922 qemu_mutex_destroy(&s->mutex);
031fd1be 923
a94f83d9 924 g_free(s->cookie);
45724d6d 925 g_free(s->url);
769ce76d
AG
926}
927
928static int64_t curl_getlength(BlockDriverState *bs)
929{
930 BDRVCURLState *s = bs->opaque;
931 return s->len;
932}
933
934static BlockDriver bdrv_http = {
63f0f45f
SH
935 .format_name = "http",
936 .protocol_name = "http",
937
938 .instance_size = sizeof(BDRVCURLState),
939 .bdrv_parse_filename = curl_parse_filename,
940 .bdrv_file_open = curl_open,
941 .bdrv_close = curl_close,
942 .bdrv_getlength = curl_getlength,
769ce76d 943
63f0f45f 944 .bdrv_aio_readv = curl_aio_readv,
769ce76d 945
63f0f45f
SH
946 .bdrv_detach_aio_context = curl_detach_aio_context,
947 .bdrv_attach_aio_context = curl_attach_aio_context,
769ce76d
AG
948};
949
950static BlockDriver bdrv_https = {
63f0f45f
SH
951 .format_name = "https",
952 .protocol_name = "https",
769ce76d 953
63f0f45f
SH
954 .instance_size = sizeof(BDRVCURLState),
955 .bdrv_parse_filename = curl_parse_filename,
956 .bdrv_file_open = curl_open,
957 .bdrv_close = curl_close,
958 .bdrv_getlength = curl_getlength,
769ce76d 959
63f0f45f
SH
960 .bdrv_aio_readv = curl_aio_readv,
961
962 .bdrv_detach_aio_context = curl_detach_aio_context,
963 .bdrv_attach_aio_context = curl_attach_aio_context,
769ce76d
AG
964};
965
966static BlockDriver bdrv_ftp = {
63f0f45f
SH
967 .format_name = "ftp",
968 .protocol_name = "ftp",
969
970 .instance_size = sizeof(BDRVCURLState),
971 .bdrv_parse_filename = curl_parse_filename,
972 .bdrv_file_open = curl_open,
973 .bdrv_close = curl_close,
974 .bdrv_getlength = curl_getlength,
769ce76d 975
63f0f45f 976 .bdrv_aio_readv = curl_aio_readv,
769ce76d 977
63f0f45f
SH
978 .bdrv_detach_aio_context = curl_detach_aio_context,
979 .bdrv_attach_aio_context = curl_attach_aio_context,
769ce76d
AG
980};
981
982static BlockDriver bdrv_ftps = {
63f0f45f
SH
983 .format_name = "ftps",
984 .protocol_name = "ftps",
769ce76d 985
63f0f45f
SH
986 .instance_size = sizeof(BDRVCURLState),
987 .bdrv_parse_filename = curl_parse_filename,
988 .bdrv_file_open = curl_open,
989 .bdrv_close = curl_close,
990 .bdrv_getlength = curl_getlength,
769ce76d 991
63f0f45f
SH
992 .bdrv_aio_readv = curl_aio_readv,
993
994 .bdrv_detach_aio_context = curl_detach_aio_context,
995 .bdrv_attach_aio_context = curl_attach_aio_context,
769ce76d
AG
996};
997
769ce76d
AG
998static void curl_block_init(void)
999{
1000 bdrv_register(&bdrv_http);
1001 bdrv_register(&bdrv_https);
1002 bdrv_register(&bdrv_ftp);
1003 bdrv_register(&bdrv_ftps);
769ce76d
AG
1004}
1005
1006block_init(curl_block_init);