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