Statistics
| Branch: | Revision:

root / qemu-nbd.c @ af49bbbe

History | View | Annotate | Download (16 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 NBDExport *exp;
40
static int verbose;
41
static char *device;
42
static char *srcpath;
43
static char *sockpath;
44

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
246
int main(int argc, char **argv)
247
{
248
    BlockDriverState *bs;
249
    off_t dev_offset = 0;
250
    uint32_t nbdflags = 0;
251
    bool disconnect = false;
252
    const char *bindto = "0.0.0.0";
253
    int port = NBD_DEFAULT_PORT;
254
    struct sockaddr_in addr;
255
    socklen_t addr_len = sizeof(addr);
256
    off_t fd_size;
257
    const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
258
    struct option lopt[] = {
259
        { "help", 0, NULL, 'h' },
260
        { "version", 0, NULL, 'V' },
261
        { "bind", 1, NULL, 'b' },
262
        { "port", 1, NULL, 'p' },
263
        { "socket", 1, NULL, 'k' },
264
        { "offset", 1, NULL, 'o' },
265
        { "read-only", 0, NULL, 'r' },
266
        { "partition", 1, NULL, 'P' },
267
        { "connect", 1, NULL, 'c' },
268
        { "disconnect", 0, NULL, 'd' },
269
        { "snapshot", 0, NULL, 's' },
270
        { "nocache", 0, NULL, 'n' },
271
        { "shared", 1, NULL, 'e' },
272
        { "persistent", 0, NULL, 't' },
273
        { "verbose", 0, NULL, 'v' },
274
        { NULL, 0, NULL, 0 }
275
    };
276
    int ch;
277
    int opt_ind = 0;
278
    int li;
279
    char *end;
280
    int flags = BDRV_O_RDWR;
281
    int partition = -1;
282
    int ret;
283
    int shared = 1;
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
    exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags);
493
    sharing_fds = g_malloc((shared + 1) * sizeof(int));
494

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

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

    
504
    if (device) {
505
        int ret;
506

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

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

    
520
    do {
521
        FD_ZERO(&fds);
522
        FD_SET(sigterm_fd[0], &fds);
523
        for (i = 0; i < nb_fds; i++)
524
            FD_SET(sharing_fds[i], &fds);
525

    
526
        do {
527
            ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
528
        } while (ret == -1 && errno == EINTR);
529
        if (ret == -1 || FD_ISSET(sigterm_fd[0], &fds)) {
530
            break;
531
        }
532

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

    
562
    close(sharing_fds[0]);
563
    nbd_export_close(exp);
564
    g_free(sharing_fds);
565
    if (sockpath) {
566
        unlink(sockpath);
567
    }
568

    
569
    if (device) {
570
        void *ret;
571
        pthread_join(client_thread, &ret);
572
        exit(ret != NULL);
573
    } else {
574
        exit(EXIT_SUCCESS);
575
    }
576
}