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