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