]> Git Repo - qemu.git/blob - block/curl.c
block/curl: Use BDRV_SECTOR_SIZE
[qemu.git] / block / curl.c
1 /*
2  * QEMU Block driver for CURL images
3  *
4  * Copyright (c) 2009 Alexander Graf <[email protected]>
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 FIND_RET_NONE   0
80 #define FIND_RET_OK     1
81 #define FIND_RET_WAIT   2
82
83 #define CURL_BLOCK_OPT_URL       "url"
84 #define CURL_BLOCK_OPT_READAHEAD "readahead"
85 #define CURL_BLOCK_OPT_SSLVERIFY "sslverify"
86 #define CURL_BLOCK_OPT_TIMEOUT "timeout"
87 #define CURL_BLOCK_OPT_COOKIE    "cookie"
88 #define CURL_BLOCK_OPT_USERNAME "username"
89 #define CURL_BLOCK_OPT_PASSWORD_SECRET "password-secret"
90 #define CURL_BLOCK_OPT_PROXY_USERNAME "proxy-username"
91 #define CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET "proxy-password-secret"
92
93 struct BDRVCURLState;
94
95 typedef struct CURLAIOCB {
96     BlockAIOCB common;
97     QEMUIOVector *qiov;
98
99     int64_t sector_num;
100     int nb_sectors;
101
102     size_t start;
103     size_t end;
104 } CURLAIOCB;
105
106 typedef struct CURLState
107 {
108     struct BDRVCURLState *s;
109     CURLAIOCB *acb[CURL_NUM_ACB];
110     CURL *curl;
111     curl_socket_t sock_fd;
112     char *orig_buf;
113     size_t buf_start;
114     size_t buf_off;
115     size_t buf_len;
116     char range[128];
117     char errmsg[CURL_ERROR_SIZE];
118     char in_use;
119 } CURLState;
120
121 typedef struct BDRVCURLState {
122     CURLM *multi;
123     QEMUTimer timer;
124     size_t len;
125     CURLState states[CURL_NUM_STATES];
126     char *url;
127     size_t readahead_size;
128     bool sslverify;
129     uint64_t timeout;
130     char *cookie;
131     bool accept_range;
132     AioContext *aio_context;
133     char *username;
134     char *password;
135     char *proxyusername;
136     char *proxypassword;
137 } BDRVCURLState;
138
139 static void curl_clean_state(CURLState *s);
140 static void curl_multi_do(void *arg);
141 static void curl_multi_read(void *arg);
142
143 #ifdef NEED_CURL_TIMER_CALLBACK
144 static int curl_timer_cb(CURLM *multi, long timeout_ms, void *opaque)
145 {
146     BDRVCURLState *s = opaque;
147
148     DPRINTF("CURL: timer callback timeout_ms %ld\n", timeout_ms);
149     if (timeout_ms == -1) {
150         timer_del(&s->timer);
151     } else {
152         int64_t timeout_ns = (int64_t)timeout_ms * 1000 * 1000;
153         timer_mod(&s->timer,
154                   qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ns);
155     }
156     return 0;
157 }
158 #endif
159
160 static int curl_sock_cb(CURL *curl, curl_socket_t fd, int action,
161                         void *userp, void *sp)
162 {
163     BDRVCURLState *s;
164     CURLState *state = NULL;
165     curl_easy_getinfo(curl, CURLINFO_PRIVATE, (char **)&state);
166     state->sock_fd = fd;
167     s = state->s;
168
169     DPRINTF("CURL (AIO): Sock action %d on fd %d\n", action, (int)fd);
170     switch (action) {
171         case CURL_POLL_IN:
172             aio_set_fd_handler(s->aio_context, fd, false,
173                                curl_multi_read, NULL, state);
174             break;
175         case CURL_POLL_OUT:
176             aio_set_fd_handler(s->aio_context, fd, false,
177                                NULL, curl_multi_do, state);
178             break;
179         case CURL_POLL_INOUT:
180             aio_set_fd_handler(s->aio_context, fd, false,
181                                curl_multi_read, curl_multi_do, state);
182             break;
183         case CURL_POLL_REMOVE:
184             aio_set_fd_handler(s->aio_context, fd, false,
185                                NULL, NULL, NULL);
186             break;
187     }
188
189     return 0;
190 }
191
192 static size_t curl_header_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
193 {
194     BDRVCURLState *s = opaque;
195     size_t realsize = size * nmemb;
196     const char *accept_line = "Accept-Ranges: bytes";
197
198     if (realsize >= strlen(accept_line)
199         && strncmp((char *)ptr, accept_line, strlen(accept_line)) == 0) {
200         s->accept_range = true;
201     }
202
203     return realsize;
204 }
205
206 static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
207 {
208     CURLState *s = ((CURLState*)opaque);
209     size_t realsize = size * nmemb;
210     int i;
211
212     DPRINTF("CURL: Just reading %zd bytes\n", realsize);
213
214     if (!s || !s->orig_buf)
215         return 0;
216
217     if (s->buf_off >= s->buf_len) {
218         /* buffer full, read nothing */
219         return 0;
220     }
221     realsize = MIN(realsize, s->buf_len - s->buf_off);
222     memcpy(s->orig_buf + s->buf_off, ptr, realsize);
223     s->buf_off += realsize;
224
225     for(i=0; i<CURL_NUM_ACB; i++) {
226         CURLAIOCB *acb = s->acb[i];
227
228         if (!acb)
229             continue;
230
231         if ((s->buf_off >= acb->end)) {
232             qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,
233                                 acb->end - acb->start);
234             acb->common.cb(acb->common.opaque, 0);
235             qemu_aio_unref(acb);
236             s->acb[i] = NULL;
237         }
238     }
239
240     return realsize;
241 }
242
243 static int curl_find_buf(BDRVCURLState *s, size_t start, size_t len,
244                          CURLAIOCB *acb)
245 {
246     int i;
247     size_t end = start + len;
248
249     for (i=0; i<CURL_NUM_STATES; i++) {
250         CURLState *state = &s->states[i];
251         size_t buf_end = (state->buf_start + state->buf_off);
252         size_t buf_fend = (state->buf_start + state->buf_len);
253
254         if (!state->orig_buf)
255             continue;
256         if (!state->buf_off)
257             continue;
258
259         // Does the existing buffer cover our section?
260         if ((start >= state->buf_start) &&
261             (start <= buf_end) &&
262             (end >= state->buf_start) &&
263             (end <= buf_end))
264         {
265             char *buf = state->orig_buf + (start - state->buf_start);
266
267             qemu_iovec_from_buf(acb->qiov, 0, buf, len);
268             acb->common.cb(acb->common.opaque, 0);
269
270             return FIND_RET_OK;
271         }
272
273         // Wait for unfinished chunks
274         if (state->in_use &&
275             (start >= state->buf_start) &&
276             (start <= buf_fend) &&
277             (end >= state->buf_start) &&
278             (end <= buf_fend))
279         {
280             int j;
281
282             acb->start = start - state->buf_start;
283             acb->end = acb->start + len;
284
285             for (j=0; j<CURL_NUM_ACB; j++) {
286                 if (!state->acb[j]) {
287                     state->acb[j] = acb;
288                     return FIND_RET_WAIT;
289                 }
290             }
291         }
292     }
293
294     return FIND_RET_NONE;
295 }
296
297 static void curl_multi_check_completion(BDRVCURLState *s)
298 {
299     int msgs_in_queue;
300
301     /* Try to find done transfers, so we can free the easy
302      * handle again. */
303     for (;;) {
304         CURLMsg *msg;
305         msg = curl_multi_info_read(s->multi, &msgs_in_queue);
306
307         /* Quit when there are no more completions */
308         if (!msg)
309             break;
310
311         if (msg->msg == CURLMSG_DONE) {
312             CURLState *state = NULL;
313             curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,
314                               (char **)&state);
315
316             /* ACBs for successful messages get completed in curl_read_cb */
317             if (msg->data.result != CURLE_OK) {
318                 int i;
319                 static int errcount = 100;
320
321                 /* Don't lose the original error message from curl, since
322                  * it contains extra data.
323                  */
324                 if (errcount > 0) {
325                     error_report("curl: %s", state->errmsg);
326                     if (--errcount == 0) {
327                         error_report("curl: further errors suppressed");
328                     }
329                 }
330
331                 for (i = 0; i < CURL_NUM_ACB; i++) {
332                     CURLAIOCB *acb = state->acb[i];
333
334                     if (acb == NULL) {
335                         continue;
336                     }
337
338                     acb->common.cb(acb->common.opaque, -EPROTO);
339                     qemu_aio_unref(acb);
340                     state->acb[i] = NULL;
341                 }
342             }
343
344             curl_clean_state(state);
345             break;
346         }
347     }
348 }
349
350 static void curl_multi_do(void *arg)
351 {
352     CURLState *s = (CURLState *)arg;
353     int running;
354     int r;
355
356     if (!s->s->multi) {
357         return;
358     }
359
360     do {
361         r = curl_multi_socket_action(s->s->multi, s->sock_fd, 0, &running);
362     } while(r == CURLM_CALL_MULTI_PERFORM);
363
364 }
365
366 static void curl_multi_read(void *arg)
367 {
368     CURLState *s = (CURLState *)arg;
369
370     curl_multi_do(arg);
371     curl_multi_check_completion(s->s);
372 }
373
374 static void curl_multi_timeout_do(void *arg)
375 {
376 #ifdef NEED_CURL_TIMER_CALLBACK
377     BDRVCURLState *s = (BDRVCURLState *)arg;
378     int running;
379
380     if (!s->multi) {
381         return;
382     }
383
384     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
385
386     curl_multi_check_completion(s);
387 #else
388     abort();
389 #endif
390 }
391
392 static CURLState *curl_init_state(BlockDriverState *bs, BDRVCURLState *s)
393 {
394     CURLState *state = NULL;
395     int i, j;
396
397     do {
398         for (i=0; i<CURL_NUM_STATES; i++) {
399             for (j=0; j<CURL_NUM_ACB; j++)
400                 if (s->states[i].acb[j])
401                     continue;
402             if (s->states[i].in_use)
403                 continue;
404
405             state = &s->states[i];
406             state->in_use = 1;
407             break;
408         }
409         if (!state) {
410             aio_poll(bdrv_get_aio_context(bs), true);
411         }
412     } while(!state);
413
414     if (!state->curl) {
415         state->curl = curl_easy_init();
416         if (!state->curl) {
417             return NULL;
418         }
419         curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
420         curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,
421                          (long) s->sslverify);
422         if (s->cookie) {
423             curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);
424         }
425         curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);
426         curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,
427                          (void *)curl_read_cb);
428         curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
429         curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
430         curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
431         curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
432         curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
433         curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
434         curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
435
436         if (s->username) {
437             curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);
438         }
439         if (s->password) {
440             curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);
441         }
442         if (s->proxyusername) {
443             curl_easy_setopt(state->curl,
444                              CURLOPT_PROXYUSERNAME, s->proxyusername);
445         }
446         if (s->proxypassword) {
447             curl_easy_setopt(state->curl,
448                              CURLOPT_PROXYPASSWORD, s->proxypassword);
449         }
450
451         /* Restrict supported protocols to avoid security issues in the more
452          * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see
453          * CVE-2013-0249.
454          *
455          * Restricting protocols is only supported from 7.19.4 upwards.
456          */
457 #if LIBCURL_VERSION_NUM >= 0x071304
458         curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
459         curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
460 #endif
461
462 #ifdef DEBUG_VERBOSE
463         curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
464 #endif
465     }
466
467     state->s = s;
468
469     return state;
470 }
471
472 static void curl_clean_state(CURLState *s)
473 {
474     if (s->s->multi)
475         curl_multi_remove_handle(s->s->multi, s->curl);
476     s->in_use = 0;
477 }
478
479 static void curl_parse_filename(const char *filename, QDict *options,
480                                 Error **errp)
481 {
482     qdict_put(options, CURL_BLOCK_OPT_URL, qstring_from_str(filename));
483 }
484
485 static void curl_detach_aio_context(BlockDriverState *bs)
486 {
487     BDRVCURLState *s = bs->opaque;
488     int i;
489
490     for (i = 0; i < CURL_NUM_STATES; i++) {
491         if (s->states[i].in_use) {
492             curl_clean_state(&s->states[i]);
493         }
494         if (s->states[i].curl) {
495             curl_easy_cleanup(s->states[i].curl);
496             s->states[i].curl = NULL;
497         }
498         g_free(s->states[i].orig_buf);
499         s->states[i].orig_buf = NULL;
500     }
501     if (s->multi) {
502         curl_multi_cleanup(s->multi);
503         s->multi = NULL;
504     }
505
506     timer_del(&s->timer);
507 }
508
509 static void curl_attach_aio_context(BlockDriverState *bs,
510                                     AioContext *new_context)
511 {
512     BDRVCURLState *s = bs->opaque;
513
514     aio_timer_init(new_context, &s->timer,
515                    QEMU_CLOCK_REALTIME, SCALE_NS,
516                    curl_multi_timeout_do, s);
517
518     assert(!s->multi);
519     s->multi = curl_multi_init();
520     s->aio_context = new_context;
521     curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
522 #ifdef NEED_CURL_TIMER_CALLBACK
523     curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
524     curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
525 #endif
526 }
527
528 static QemuOptsList runtime_opts = {
529     .name = "curl",
530     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
531     .desc = {
532         {
533             .name = CURL_BLOCK_OPT_URL,
534             .type = QEMU_OPT_STRING,
535             .help = "URL to open",
536         },
537         {
538             .name = CURL_BLOCK_OPT_READAHEAD,
539             .type = QEMU_OPT_SIZE,
540             .help = "Readahead size",
541         },
542         {
543             .name = CURL_BLOCK_OPT_SSLVERIFY,
544             .type = QEMU_OPT_BOOL,
545             .help = "Verify SSL certificate"
546         },
547         {
548             .name = CURL_BLOCK_OPT_TIMEOUT,
549             .type = QEMU_OPT_NUMBER,
550             .help = "Curl timeout"
551         },
552         {
553             .name = CURL_BLOCK_OPT_COOKIE,
554             .type = QEMU_OPT_STRING,
555             .help = "Pass the cookie or list of cookies with each request"
556         },
557         {
558             .name = CURL_BLOCK_OPT_USERNAME,
559             .type = QEMU_OPT_STRING,
560             .help = "Username for HTTP auth"
561         },
562         {
563             .name = CURL_BLOCK_OPT_PASSWORD_SECRET,
564             .type = QEMU_OPT_STRING,
565             .help = "ID of secret used as password for HTTP auth",
566         },
567         {
568             .name = CURL_BLOCK_OPT_PROXY_USERNAME,
569             .type = QEMU_OPT_STRING,
570             .help = "Username for HTTP proxy auth"
571         },
572         {
573             .name = CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET,
574             .type = QEMU_OPT_STRING,
575             .help = "ID of secret used as password for HTTP proxy auth",
576         },
577         { /* end of list */ }
578     },
579 };
580
581
582 static int curl_open(BlockDriverState *bs, QDict *options, int flags,
583                      Error **errp)
584 {
585     BDRVCURLState *s = bs->opaque;
586     CURLState *state = NULL;
587     QemuOpts *opts;
588     Error *local_err = NULL;
589     const char *file;
590     const char *cookie;
591     double d;
592     const char *secretid;
593
594     static int inited = 0;
595
596     if (flags & BDRV_O_RDWR) {
597         error_setg(errp, "curl block device does not support writes");
598         return -EROFS;
599     }
600
601     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
602     qemu_opts_absorb_qdict(opts, options, &local_err);
603     if (local_err) {
604         error_propagate(errp, local_err);
605         goto out_noclean;
606     }
607
608     s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
609                                           READ_AHEAD_DEFAULT);
610     if ((s->readahead_size & 0x1ff) != 0) {
611         error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
612                    s->readahead_size);
613         goto out_noclean;
614     }
615
616     s->timeout = qemu_opt_get_number(opts, CURL_BLOCK_OPT_TIMEOUT,
617                                      CURL_TIMEOUT_DEFAULT);
618     if (s->timeout > CURL_TIMEOUT_MAX) {
619         error_setg(errp, "timeout parameter is too large or negative");
620         goto out_noclean;
621     }
622
623     s->sslverify = qemu_opt_get_bool(opts, CURL_BLOCK_OPT_SSLVERIFY, true);
624
625     cookie = qemu_opt_get(opts, CURL_BLOCK_OPT_COOKIE);
626     s->cookie = g_strdup(cookie);
627
628     file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
629     if (file == NULL) {
630         error_setg(errp, "curl block driver requires an 'url' option");
631         goto out_noclean;
632     }
633
634     s->username = g_strdup(qemu_opt_get(opts, CURL_BLOCK_OPT_USERNAME));
635     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PASSWORD_SECRET);
636
637     if (secretid) {
638         s->password = qcrypto_secret_lookup_as_utf8(secretid, errp);
639         if (!s->password) {
640             goto out_noclean;
641         }
642     }
643
644     s->proxyusername = g_strdup(
645         qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_USERNAME));
646     secretid = qemu_opt_get(opts, CURL_BLOCK_OPT_PROXY_PASSWORD_SECRET);
647     if (secretid) {
648         s->proxypassword = qcrypto_secret_lookup_as_utf8(secretid, errp);
649         if (!s->proxypassword) {
650             goto out_noclean;
651         }
652     }
653
654     if (!inited) {
655         curl_global_init(CURL_GLOBAL_ALL);
656         inited = 1;
657     }
658
659     DPRINTF("CURL: Opening %s\n", file);
660     s->aio_context = bdrv_get_aio_context(bs);
661     s->url = g_strdup(file);
662     state = curl_init_state(bs, s);
663     if (!state)
664         goto out_noclean;
665
666     // Get file size
667
668     s->accept_range = false;
669     curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
670     curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
671                      curl_header_cb);
672     curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
673     if (curl_easy_perform(state->curl))
674         goto out;
675     if (curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) {
676         goto out;
677     }
678     /* Prior CURL 7.19.4 return value of 0 could mean that the file size is not
679      * know or the size is zero. From 7.19.4 CURL returns -1 if size is not
680      * known and zero if it is realy zero-length file. */
681 #if LIBCURL_VERSION_NUM >= 0x071304
682     if (d < 0) {
683         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
684                 "Server didn't report file size.");
685         goto out;
686     }
687 #else
688     if (d <= 0) {
689         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
690                 "Unknown file size or zero-length file.");
691         goto out;
692     }
693 #endif
694
695     s->len = (size_t)d;
696
697     if ((!strncasecmp(s->url, "http://", strlen("http://"))
698         || !strncasecmp(s->url, "https://", strlen("https://")))
699         && !s->accept_range) {
700         pstrcpy(state->errmsg, CURL_ERROR_SIZE,
701                 "Server does not support 'range' (byte ranges).");
702         goto out;
703     }
704     DPRINTF("CURL: Size = %zd\n", s->len);
705
706     curl_clean_state(state);
707     curl_easy_cleanup(state->curl);
708     state->curl = NULL;
709
710     curl_attach_aio_context(bs, bdrv_get_aio_context(bs));
711
712     qemu_opts_del(opts);
713     return 0;
714
715 out:
716     error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
717     curl_easy_cleanup(state->curl);
718     state->curl = NULL;
719 out_noclean:
720     g_free(s->cookie);
721     g_free(s->url);
722     qemu_opts_del(opts);
723     return -EINVAL;
724 }
725
726 static const AIOCBInfo curl_aiocb_info = {
727     .aiocb_size         = sizeof(CURLAIOCB),
728 };
729
730
731 static void curl_readv_bh_cb(void *p)
732 {
733     CURLState *state;
734     int running;
735
736     CURLAIOCB *acb = p;
737     BDRVCURLState *s = acb->common.bs->opaque;
738
739     size_t start = acb->sector_num * BDRV_SECTOR_SIZE;
740     size_t end;
741
742     // In case we have the requested data already (e.g. read-ahead),
743     // we can just call the callback and be done.
744     switch (curl_find_buf(s, start, acb->nb_sectors * BDRV_SECTOR_SIZE, acb)) {
745         case FIND_RET_OK:
746             qemu_aio_unref(acb);
747             // fall through
748         case FIND_RET_WAIT:
749             return;
750         default:
751             break;
752     }
753
754     // No cache found, so let's start a new request
755     state = curl_init_state(acb->common.bs, s);
756     if (!state) {
757         acb->common.cb(acb->common.opaque, -EIO);
758         qemu_aio_unref(acb);
759         return;
760     }
761
762     acb->start = 0;
763     acb->end = (acb->nb_sectors * BDRV_SECTOR_SIZE);
764
765     state->buf_off = 0;
766     g_free(state->orig_buf);
767     state->buf_start = start;
768     state->buf_len = acb->end + s->readahead_size;
769     end = MIN(start + state->buf_len, s->len) - 1;
770     state->orig_buf = g_try_malloc(state->buf_len);
771     if (state->buf_len && state->orig_buf == NULL) {
772         curl_clean_state(state);
773         acb->common.cb(acb->common.opaque, -ENOMEM);
774         qemu_aio_unref(acb);
775         return;
776     }
777     state->acb[0] = acb;
778
779     snprintf(state->range, 127, "%zd-%zd", start, end);
780     DPRINTF("CURL (AIO): Reading %llu at %zd (%s)\n",
781             (acb->nb_sectors * BDRV_SECTOR_SIZE), start, state->range);
782     curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);
783
784     curl_multi_add_handle(s->multi, state->curl);
785
786     /* Tell curl it needs to kick things off */
787     curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);
788 }
789
790 static BlockAIOCB *curl_aio_readv(BlockDriverState *bs,
791         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
792         BlockCompletionFunc *cb, void *opaque)
793 {
794     CURLAIOCB *acb;
795
796     acb = qemu_aio_get(&curl_aiocb_info, bs, cb, opaque);
797
798     acb->qiov = qiov;
799     acb->sector_num = sector_num;
800     acb->nb_sectors = nb_sectors;
801
802     aio_bh_schedule_oneshot(bdrv_get_aio_context(bs), curl_readv_bh_cb, acb);
803     return &acb->common;
804 }
805
806 static void curl_close(BlockDriverState *bs)
807 {
808     BDRVCURLState *s = bs->opaque;
809
810     DPRINTF("CURL: Close\n");
811     curl_detach_aio_context(bs);
812
813     g_free(s->cookie);
814     g_free(s->url);
815 }
816
817 static int64_t curl_getlength(BlockDriverState *bs)
818 {
819     BDRVCURLState *s = bs->opaque;
820     return s->len;
821 }
822
823 static BlockDriver bdrv_http = {
824     .format_name                = "http",
825     .protocol_name              = "http",
826
827     .instance_size              = sizeof(BDRVCURLState),
828     .bdrv_parse_filename        = curl_parse_filename,
829     .bdrv_file_open             = curl_open,
830     .bdrv_close                 = curl_close,
831     .bdrv_getlength             = curl_getlength,
832
833     .bdrv_aio_readv             = curl_aio_readv,
834
835     .bdrv_detach_aio_context    = curl_detach_aio_context,
836     .bdrv_attach_aio_context    = curl_attach_aio_context,
837 };
838
839 static BlockDriver bdrv_https = {
840     .format_name                = "https",
841     .protocol_name              = "https",
842
843     .instance_size              = sizeof(BDRVCURLState),
844     .bdrv_parse_filename        = curl_parse_filename,
845     .bdrv_file_open             = curl_open,
846     .bdrv_close                 = curl_close,
847     .bdrv_getlength             = curl_getlength,
848
849     .bdrv_aio_readv             = curl_aio_readv,
850
851     .bdrv_detach_aio_context    = curl_detach_aio_context,
852     .bdrv_attach_aio_context    = curl_attach_aio_context,
853 };
854
855 static BlockDriver bdrv_ftp = {
856     .format_name                = "ftp",
857     .protocol_name              = "ftp",
858
859     .instance_size              = sizeof(BDRVCURLState),
860     .bdrv_parse_filename        = curl_parse_filename,
861     .bdrv_file_open             = curl_open,
862     .bdrv_close                 = curl_close,
863     .bdrv_getlength             = curl_getlength,
864
865     .bdrv_aio_readv             = curl_aio_readv,
866
867     .bdrv_detach_aio_context    = curl_detach_aio_context,
868     .bdrv_attach_aio_context    = curl_attach_aio_context,
869 };
870
871 static BlockDriver bdrv_ftps = {
872     .format_name                = "ftps",
873     .protocol_name              = "ftps",
874
875     .instance_size              = sizeof(BDRVCURLState),
876     .bdrv_parse_filename        = curl_parse_filename,
877     .bdrv_file_open             = curl_open,
878     .bdrv_close                 = curl_close,
879     .bdrv_getlength             = curl_getlength,
880
881     .bdrv_aio_readv             = curl_aio_readv,
882
883     .bdrv_detach_aio_context    = curl_detach_aio_context,
884     .bdrv_attach_aio_context    = curl_attach_aio_context,
885 };
886
887 static void curl_block_init(void)
888 {
889     bdrv_register(&bdrv_http);
890     bdrv_register(&bdrv_https);
891     bdrv_register(&bdrv_ftp);
892     bdrv_register(&bdrv_ftps);
893 }
894
895 block_init(curl_block_init);
This page took 0.07183 seconds and 4 git commands to generate.