Statistics
| Branch: | Revision:

root / qemu-nbd.c @ 3777b09f

History | View | Annotate | Download (16.2 kB)

1
/*
2
 *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
3
 *
4
 *  Network Block Device
5
 *
6
 *  This program is free software; you can redistribute it and/or modify
7
 *  it under the terms of the GNU General Public License as published by
8
 *  the Free Software Foundation; under version 2 of the License.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program; if not, see <http://www.gnu.org/licenses/>.
17
 */
18

    
19
#include "qemu-common.h"
20
#include "block_int.h"
21
#include "nbd.h"
22

    
23
#include <stdarg.h>
24
#include <stdio.h>
25
#include <getopt.h>
26
#include <err.h>
27
#include <sys/types.h>
28
#include <sys/socket.h>
29
#include <netinet/in.h>
30
#include <netinet/tcp.h>
31
#include <arpa/inet.h>
32
#include <signal.h>
33
#include <libgen.h>
34
#include <pthread.h>
35

    
36
#define SOCKET_PATH    "/var/lock/qemu-nbd-%s"
37

    
38
static int sigterm_wfd;
39
static int verbose;
40
static char *device;
41
static char *srcpath;
42
static char *sockpath;
43

    
44
static void usage(const char *name)
45
{
46
    printf(
47
"Usage: %s [OPTIONS] FILE\n"
48
"QEMU Disk Network Block Device Server\n"
49
"\n"
50
"  -p, --port=PORT      port to listen on (default `%d')\n"
51
"  -o, --offset=OFFSET  offset into the image\n"
52
"  -b, --bind=IFACE     interface to bind to (default `0.0.0.0')\n"
53
"  -k, --socket=PATH    path to the unix socket\n"
54
"                       (default '"SOCKET_PATH"')\n"
55
"  -r, --read-only      export read-only\n"
56
"  -P, --partition=NUM  only expose partition NUM\n"
57
"  -s, --snapshot       use snapshot file\n"
58
"  -n, --nocache        disable host cache\n"
59
"  -c, --connect=DEV    connect FILE to the local NBD device DEV\n"
60
"  -d, --disconnect     disconnect the specified device\n"
61
"  -e, --shared=NUM     device can be shared by NUM clients (default '1')\n"
62
"  -t, --persistent     don't exit on the last connection\n"
63
"  -v, --verbose        display extra debugging information\n"
64
"  -h, --help           display this help and exit\n"
65
"  -V, --version        output version information and exit\n"
66
"\n"
67
"Report bugs to <anthony@codemonkey.ws>\n"
68
    , name, NBD_DEFAULT_PORT, "DEVICE");
69
}
70

    
71
static void version(const char *name)
72
{
73
    printf(
74
"%s version 0.0.1\n"
75
"Written by Anthony Liguori.\n"
76
"\n"
77
"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
78
"This is free software; see the source for copying conditions.  There is NO\n"
79
"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
80
    , name);
81
}
82

    
83
struct partition_record
84
{
85
    uint8_t bootable;
86
    uint8_t start_head;
87
    uint32_t start_cylinder;
88
    uint8_t start_sector;
89
    uint8_t system;
90
    uint8_t end_head;
91
    uint8_t end_cylinder;
92
    uint8_t end_sector;
93
    uint32_t start_sector_abs;
94
    uint32_t nb_sectors_abs;
95
};
96

    
97
static void read_partition(uint8_t *p, struct partition_record *r)
98
{
99
    r->bootable = p[0];
100
    r->start_head = p[1];
101
    r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
102
    r->start_sector = p[2] & 0x3f;
103
    r->system = p[4];
104
    r->end_head = p[5];
105
    r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
106
    r->end_sector = p[6] & 0x3f;
107
    r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
108
    r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
109
}
110

    
111
static int find_partition(BlockDriverState *bs, int partition,
112
                          off_t *offset, off_t *size)
113
{
114
    struct partition_record mbr[4];
115
    uint8_t data[512];
116
    int i;
117
    int ext_partnum = 4;
118
    int ret;
119

    
120
    if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
121
        errno = -ret;
122
        err(EXIT_FAILURE, "error while reading");
123
    }
124

    
125
    if (data[510] != 0x55 || data[511] != 0xaa) {
126
        errno = -EINVAL;
127
        return -1;
128
    }
129

    
130
    for (i = 0; i < 4; i++) {
131
        read_partition(&data[446 + 16 * i], &mbr[i]);
132

    
133
        if (!mbr[i].nb_sectors_abs)
134
            continue;
135

    
136
        if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
137
            struct partition_record ext[4];
138
            uint8_t data1[512];
139
            int j;
140

    
141
            if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
142
                errno = -ret;
143
                err(EXIT_FAILURE, "error while reading");
144
            }
145

    
146
            for (j = 0; j < 4; j++) {
147
                read_partition(&data1[446 + 16 * j], &ext[j]);
148
                if (!ext[j].nb_sectors_abs)
149
                    continue;
150

    
151
                if ((ext_partnum + j + 1) == partition) {
152
                    *offset = (uint64_t)ext[j].start_sector_abs << 9;
153
                    *size = (uint64_t)ext[j].nb_sectors_abs << 9;
154
                    return 0;
155
                }
156
            }
157
            ext_partnum += 4;
158
        } else if ((i + 1) == partition) {
159
            *offset = (uint64_t)mbr[i].start_sector_abs << 9;
160
            *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
161
            return 0;
162
        }
163
    }
164

    
165
    errno = -ENOENT;
166
    return -1;
167
}
168

    
169
static void termsig_handler(int signum)
170
{
171
    static int sigterm_reported;
172
    if (!sigterm_reported) {
173
        sigterm_reported = (write(sigterm_wfd, "", 1) == 1);
174
    }
175
}
176

    
177
static void *show_parts(void *arg)
178
{
179
    int nbd;
180

    
181
    /* linux just needs an open() to trigger
182
     * the partition table update
183
     * but remember to load the module with max_part != 0 :
184
     *     modprobe nbd max_part=63
185
     */
186
    nbd = open(device, O_RDWR);
187
    if (nbd != -1) {
188
        close(nbd);
189
    }
190
    return NULL;
191
}
192

    
193
static void *nbd_client_thread(void *arg)
194
{
195
    int fd = *(int *)arg;
196
    off_t size;
197
    size_t blocksize;
198
    uint32_t nbdflags;
199
    int sock;
200
    int ret;
201
    pthread_t show_parts_thread;
202

    
203
    do {
204
        sock = unix_socket_outgoing(sockpath);
205
        if (sock == -1) {
206
            goto out;
207
        }
208
    } while (sock == -1);
209

    
210
    ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
211
                                &size, &blocksize);
212
    if (ret == -1) {
213
        goto out;
214
    }
215

    
216
    ret = nbd_init(fd, sock, nbdflags, size, blocksize);
217
    if (ret == -1) {
218
        goto out;
219
    }
220

    
221
    /* update partition table */
222
    pthread_create(&show_parts_thread, NULL, show_parts, NULL);
223

    
224
    if (verbose) {
225
        fprintf(stderr, "NBD device %s is now connected to %s\n",
226
                device, srcpath);
227
    } else {
228
        /* Close stderr so that the qemu-nbd process exits.  */
229
        dup2(STDOUT_FILENO, STDERR_FILENO);
230
    }
231

    
232
    ret = nbd_client(fd);
233
    if (ret) {
234
        goto out;
235
    }
236
    close(fd);
237
    kill(getpid(), SIGTERM);
238
    return (void *) EXIT_SUCCESS;
239

    
240
out:
241
    kill(getpid(), SIGTERM);
242
    return (void *) EXIT_FAILURE;
243
}
244

    
245
int main(int argc, char **argv)
246
{
247
    BlockDriverState *bs;
248
    off_t dev_offset = 0;
249
    uint32_t nbdflags = 0;
250
    bool disconnect = false;
251
    const char *bindto = "0.0.0.0";
252
    int port = NBD_DEFAULT_PORT;
253
    struct sockaddr_in addr;
254
    socklen_t addr_len = sizeof(addr);
255
    off_t fd_size;
256
    const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
257
    struct option lopt[] = {
258
        { "help", 0, NULL, 'h' },
259
        { "version", 0, NULL, 'V' },
260
        { "bind", 1, NULL, 'b' },
261
        { "port", 1, NULL, 'p' },
262
        { "socket", 1, NULL, 'k' },
263
        { "offset", 1, NULL, 'o' },
264
        { "read-only", 0, NULL, 'r' },
265
        { "partition", 1, NULL, 'P' },
266
        { "connect", 1, NULL, 'c' },
267
        { "disconnect", 0, NULL, 'd' },
268
        { "snapshot", 0, NULL, 's' },
269
        { "nocache", 0, NULL, 'n' },
270
        { "shared", 1, NULL, 'e' },
271
        { "persistent", 0, NULL, 't' },
272
        { "verbose", 0, NULL, 'v' },
273
        { NULL, 0, NULL, 0 }
274
    };
275
    int ch;
276
    int opt_ind = 0;
277
    int li;
278
    char *end;
279
    int flags = BDRV_O_RDWR;
280
    int partition = -1;
281
    int ret;
282
    int shared = 1;
283
    uint8_t *data;
284
    fd_set fds;
285
    int *sharing_fds;
286
    int fd;
287
    int i;
288
    int nb_fds = 0;
289
    int max_fd;
290
    int persistent = 0;
291
    pthread_t client_thread;
292

    
293
    /* The client thread uses SIGTERM to interrupt the server.  A signal
294
     * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
295
     */
296
    struct sigaction sa_sigterm;
297
    int sigterm_fd[2];
298
    if (qemu_pipe(sigterm_fd) == -1) {
299
        err(EXIT_FAILURE, "Error setting up communication pipe");
300
    }
301

    
302
    sigterm_wfd = sigterm_fd[1];
303
    memset(&sa_sigterm, 0, sizeof(sa_sigterm));
304
    sa_sigterm.sa_handler = termsig_handler;
305
    sigaction(SIGTERM, &sa_sigterm, NULL);
306

    
307
    while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
308
        switch (ch) {
309
        case 's':
310
            flags |= BDRV_O_SNAPSHOT;
311
            break;
312
        case 'n':
313
            flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
314
            break;
315
        case 'b':
316
            bindto = optarg;
317
            break;
318
        case 'p':
319
            li = strtol(optarg, &end, 0);
320
            if (*end) {
321
                errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
322
            }
323
            if (li < 1 || li > 65535) {
324
                errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
325
            }
326
            port = (uint16_t)li;
327
            break;
328
        case 'o':
329
                dev_offset = strtoll (optarg, &end, 0);
330
            if (*end) {
331
                errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
332
            }
333
            if (dev_offset < 0) {
334
                errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
335
            }
336
            break;
337
        case 'r':
338
            nbdflags |= NBD_FLAG_READ_ONLY;
339
            flags &= ~BDRV_O_RDWR;
340
            break;
341
        case 'P':
342
            partition = strtol(optarg, &end, 0);
343
            if (*end)
344
                errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
345
            if (partition < 1 || partition > 8)
346
                errx(EXIT_FAILURE, "Invalid partition %d", partition);
347
            break;
348
        case 'k':
349
            sockpath = optarg;
350
            if (sockpath[0] != '/')
351
                errx(EXIT_FAILURE, "socket path must be absolute\n");
352
            break;
353
        case 'd':
354
            disconnect = true;
355
            break;
356
        case 'c':
357
            device = optarg;
358
            break;
359
        case 'e':
360
            shared = strtol(optarg, &end, 0);
361
            if (*end) {
362
                errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
363
            }
364
            if (shared < 1) {
365
                errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
366
            }
367
            break;
368
        case 't':
369
            persistent = 1;
370
            break;
371
        case 'v':
372
            verbose = 1;
373
            break;
374
        case 'V':
375
            version(argv[0]);
376
            exit(0);
377
            break;
378
        case 'h':
379
            usage(argv[0]);
380
            exit(0);
381
            break;
382
        case '?':
383
            errx(EXIT_FAILURE, "Try `%s --help' for more information.",
384
                 argv[0]);
385
        }
386
    }
387

    
388
    if ((argc - optind) != 1) {
389
        errx(EXIT_FAILURE, "Invalid number of argument.\n"
390
             "Try `%s --help' for more information.",
391
             argv[0]);
392
    }
393

    
394
    if (disconnect) {
395
        fd = open(argv[optind], O_RDWR);
396
        if (fd == -1)
397
            err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
398

    
399
        nbd_disconnect(fd);
400

    
401
        close(fd);
402

    
403
        printf("%s disconnected\n", argv[optind]);
404

    
405
        return 0;
406
    }
407

    
408
    if (device && !verbose) {
409
        int stderr_fd[2];
410
        pid_t pid;
411
        int ret;
412

    
413
        if (qemu_pipe(stderr_fd) == -1) {
414
            err(EXIT_FAILURE, "Error setting up communication pipe");
415
        }
416

    
417
        /* Now daemonize, but keep a communication channel open to
418
         * print errors and exit with the proper status code.
419
         */
420
        pid = fork();
421
        if (pid == 0) {
422
            close(stderr_fd[0]);
423
            ret = qemu_daemon(0, 0);
424

    
425
            /* Temporarily redirect stderr to the parent's pipe...  */
426
            dup2(stderr_fd[1], STDERR_FILENO);
427
            if (ret == -1) {
428
                err(EXIT_FAILURE, "Failed to daemonize");
429
            }
430

    
431
            /* ... close the descriptor we inherited and go on.  */
432
            close(stderr_fd[1]);
433
        } else {
434
            bool errors = false;
435
            char *buf;
436

    
437
            /* In the parent.  Print error messages from the child until
438
             * it closes the pipe.
439
             */
440
            close(stderr_fd[1]);
441
            buf = g_malloc(1024);
442
            while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
443
                errors = true;
444
                ret = qemu_write_full(STDERR_FILENO, buf, ret);
445
                if (ret == -1) {
446
                    exit(EXIT_FAILURE);
447
                }
448
            }
449
            if (ret == -1) {
450
                err(EXIT_FAILURE, "Cannot read from daemon");
451
            }
452

    
453
            /* Usually the daemon should not print any message.
454
             * Exit with zero status in that case.
455
             */
456
            exit(errors);
457
        }
458
    }
459

    
460
    if (device) {
461
        /* Open before spawning new threads.  In the future, we may
462
         * drop privileges after opening.
463
         */
464
        fd = open(device, O_RDWR);
465
        if (fd == -1) {
466
            err(EXIT_FAILURE, "Failed to open %s", device);
467
        }
468

    
469
        if (sockpath == NULL) {
470
            sockpath = g_malloc(128);
471
            snprintf(sockpath, 128, SOCKET_PATH, basename(device));
472
        }
473
    }
474

    
475
    bdrv_init();
476
    atexit(bdrv_close_all);
477

    
478
    bs = bdrv_new("hda");
479
    srcpath = argv[optind];
480
    if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
481
        errno = -ret;
482
        err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
483
    }
484

    
485
    fd_size = bs->total_sectors * 512;
486

    
487
    if (partition != -1 &&
488
        find_partition(bs, partition, &dev_offset, &fd_size)) {
489
        err(EXIT_FAILURE, "Could not find partition %d", partition);
490
    }
491

    
492
    sharing_fds = g_malloc((shared + 1) * sizeof(int));
493

    
494
    if (sockpath) {
495
        sharing_fds[0] = unix_socket_incoming(sockpath);
496
    } else {
497
        sharing_fds[0] = tcp_socket_incoming(bindto, port);
498
    }
499

    
500
    if (sharing_fds[0] == -1)
501
        return 1;
502

    
503
    if (device) {
504
        int ret;
505

    
506
        ret = pthread_create(&client_thread, NULL, nbd_client_thread, &fd);
507
        if (ret != 0) {
508
            errx(EXIT_FAILURE, "Failed to create client thread: %s",
509
                 strerror(ret));
510
        }
511
    } else {
512
        /* Shut up GCC warnings.  */
513
        memset(&client_thread, 0, sizeof(client_thread));
514
    }
515

    
516
    max_fd = sharing_fds[0];
517
    nb_fds++;
518

    
519
    data = qemu_blockalign(bs, NBD_BUFFER_SIZE);
520
    if (data == NULL) {
521
        errx(EXIT_FAILURE, "Cannot allocate data buffer");
522
    }
523

    
524
    do {
525
        FD_ZERO(&fds);
526
        FD_SET(sigterm_fd[0], &fds);
527
        for (i = 0; i < nb_fds; i++)
528
            FD_SET(sharing_fds[i], &fds);
529

    
530
        do {
531
            ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
532
        } while (ret == -1 && errno == EINTR);
533
        if (ret == -1 || FD_ISSET(sigterm_fd[0], &fds)) {
534
            break;
535
        }
536

    
537
        if (FD_ISSET(sharing_fds[0], &fds))
538
            ret--;
539
        for (i = 1; i < nb_fds && ret; i++) {
540
            if (FD_ISSET(sharing_fds[i], &fds)) {
541
                if (nbd_trip(bs, sharing_fds[i], fd_size, dev_offset,
542
                             nbdflags, data) != 0) {
543
                    close(sharing_fds[i]);
544
                    nb_fds--;
545
                    sharing_fds[i] = sharing_fds[nb_fds];
546
                    i--;
547
                }
548
                ret--;
549
            }
550
        }
551
        /* new connection ? */
552
        if (FD_ISSET(sharing_fds[0], &fds)) {
553
            if (nb_fds < shared + 1) {
554
                sharing_fds[nb_fds] = accept(sharing_fds[0],
555
                                             (struct sockaddr *)&addr,
556
                                             &addr_len);
557
                if (sharing_fds[nb_fds] != -1 &&
558
                    nbd_negotiate(sharing_fds[nb_fds], fd_size, nbdflags) != -1) {
559
                        if (sharing_fds[nb_fds] > max_fd)
560
                            max_fd = sharing_fds[nb_fds];
561
                        nb_fds++;
562
                }
563
            }
564
        }
565
    } while (persistent || nb_fds > 1);
566
    qemu_vfree(data);
567

    
568
    close(sharing_fds[0]);
569
    g_free(sharing_fds);
570
    if (sockpath) {
571
        unlink(sockpath);
572
    }
573

    
574
    if (device) {
575
        void *ret;
576
        pthread_join(client_thread, &ret);
577
        exit(ret != NULL);
578
    } else {
579
        exit(EXIT_SUCCESS);
580
    }
581
}