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