Statistics
| Branch: | Revision:

root / qemu-nbd.c @ 1e6eec8b

History | View | Annotate | Download (13 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

    
34
#define SOCKET_PATH    "/var/lock/qemu-nbd-%s"
35

    
36
#define NBD_BUFFER_SIZE (1024*1024)
37

    
38
static int verbose;
39

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

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

    
79
struct partition_record
80
{
81
    uint8_t bootable;
82
    uint8_t start_head;
83
    uint32_t start_cylinder;
84
    uint8_t start_sector;
85
    uint8_t system;
86
    uint8_t end_head;
87
    uint8_t end_cylinder;
88
    uint8_t end_sector;
89
    uint32_t start_sector_abs;
90
    uint32_t nb_sectors_abs;
91
};
92

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

    
107
static int find_partition(BlockDriverState *bs, int partition,
108
                          off_t *offset, off_t *size)
109
{
110
    struct partition_record mbr[4];
111
    uint8_t data[512];
112
    int i;
113
    int ext_partnum = 4;
114

    
115
    if (bdrv_read(bs, 0, data, 1))
116
        errx(EINVAL, "error while reading");
117

    
118
    if (data[510] != 0x55 || data[511] != 0xaa) {
119
        errno = -EINVAL;
120
        return -1;
121
    }
122

    
123
    for (i = 0; i < 4; i++) {
124
        read_partition(&data[446 + 16 * i], &mbr[i]);
125

    
126
        if (!mbr[i].nb_sectors_abs)
127
            continue;
128

    
129
        if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
130
            struct partition_record ext[4];
131
            uint8_t data1[512];
132
            int j;
133

    
134
            if (bdrv_read(bs, mbr[i].start_sector_abs, data1, 1))
135
                errx(EINVAL, "error while reading");
136

    
137
            for (j = 0; j < 4; j++) {
138
                read_partition(&data1[446 + 16 * j], &ext[j]);
139
                if (!ext[j].nb_sectors_abs)
140
                    continue;
141

    
142
                if ((ext_partnum + j + 1) == partition) {
143
                    *offset = (uint64_t)ext[j].start_sector_abs << 9;
144
                    *size = (uint64_t)ext[j].nb_sectors_abs << 9;
145
                    return 0;
146
                }
147
            }
148
            ext_partnum += 4;
149
        } else if ((i + 1) == partition) {
150
            *offset = (uint64_t)mbr[i].start_sector_abs << 9;
151
            *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
152
            return 0;
153
        }
154
    }
155

    
156
    errno = -ENOENT;
157
    return -1;
158
}
159

    
160
static void show_parts(const char *device)
161
{
162
    if (fork() == 0) {
163
        int nbd;
164

    
165
        /* linux just needs an open() to trigger
166
         * the partition table update
167
         * but remember to load the module with max_part != 0 :
168
         *     modprobe nbd max_part=63
169
         */
170
        nbd = open(device, O_RDWR);
171
        if (nbd != -1)
172
              close(nbd);
173
        exit(0);
174
    }
175
}
176

    
177
int main(int argc, char **argv)
178
{
179
    BlockDriverState *bs;
180
    off_t dev_offset = 0;
181
    off_t offset = 0;
182
    bool readonly = false;
183
    bool disconnect = false;
184
    const char *bindto = "0.0.0.0";
185
    int port = 1024;
186
    struct sockaddr_in addr;
187
    socklen_t addr_len = sizeof(addr);
188
    off_t fd_size;
189
    char *device = NULL;
190
    char *socket = NULL;
191
    char sockpath[128];
192
    const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
193
    struct option lopt[] = {
194
        { "help", 0, NULL, 'h' },
195
        { "version", 0, NULL, 'V' },
196
        { "bind", 1, NULL, 'b' },
197
        { "port", 1, NULL, 'p' },
198
        { "socket", 1, NULL, 'k' },
199
        { "offset", 1, NULL, 'o' },
200
        { "read-only", 0, NULL, 'r' },
201
        { "partition", 1, NULL, 'P' },
202
        { "connect", 1, NULL, 'c' },
203
        { "disconnect", 0, NULL, 'd' },
204
        { "snapshot", 0, NULL, 's' },
205
        { "nocache", 0, NULL, 'n' },
206
        { "shared", 1, NULL, 'e' },
207
        { "persistent", 0, NULL, 't' },
208
        { "verbose", 0, NULL, 'v' },
209
        { NULL, 0, NULL, 0 }
210
    };
211
    int ch;
212
    int opt_ind = 0;
213
    int li;
214
    char *end;
215
    int flags = 0;
216
    int partition = -1;
217
    int ret;
218
    int shared = 1;
219
    uint8_t *data;
220
    fd_set fds;
221
    int *sharing_fds;
222
    int fd;
223
    int i;
224
    int nb_fds = 0;
225
    int max_fd;
226
    int persistent = 0;
227

    
228
    while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
229
        switch (ch) {
230
        case 's':
231
            flags |= BDRV_O_SNAPSHOT;
232
            break;
233
        case 'n':
234
            flags |= BDRV_O_NOCACHE;
235
            break;
236
        case 'b':
237
            bindto = optarg;
238
            break;
239
        case 'p':
240
            li = strtol(optarg, &end, 0);
241
            if (*end) {
242
                errx(EINVAL, "Invalid port `%s'", optarg);
243
            }
244
            if (li < 1 || li > 65535) {
245
                errx(EINVAL, "Port out of range `%s'", optarg);
246
            }
247
            port = (uint16_t)li;
248
            break;
249
        case 'o':
250
                dev_offset = strtoll (optarg, &end, 0);
251
            if (*end) {
252
                errx(EINVAL, "Invalid offset `%s'", optarg);
253
            }
254
            if (dev_offset < 0) {
255
                errx(EINVAL, "Offset must be positive `%s'", optarg);
256
            }
257
            break;
258
        case 'r':
259
            readonly = true;
260
            break;
261
        case 'P':
262
            partition = strtol(optarg, &end, 0);
263
            if (*end)
264
                errx(EINVAL, "Invalid partition `%s'", optarg);
265
            if (partition < 1 || partition > 8)
266
                errx(EINVAL, "Invalid partition %d", partition);
267
            break;
268
        case 'k':
269
            socket = optarg;
270
            if (socket[0] != '/')
271
                errx(EINVAL, "socket path must be absolute\n");
272
            break;
273
        case 'd':
274
            disconnect = true;
275
            break;
276
        case 'c':
277
            device = optarg;
278
            break;
279
        case 'e':
280
            shared = strtol(optarg, &end, 0);
281
            if (*end) {
282
                errx(EINVAL, "Invalid shared device number '%s'", optarg);
283
            }
284
            if (shared < 1) {
285
                errx(EINVAL, "Shared device number must be greater than 0\n");
286
            }
287
            break;
288
        case 't':
289
            persistent = 1;
290
            break;
291
        case 'v':
292
            verbose = 1;
293
            break;
294
        case 'V':
295
            version(argv[0]);
296
            exit(0);
297
            break;
298
        case 'h':
299
            usage(argv[0]);
300
            exit(0);
301
            break;
302
        case '?':
303
            errx(EINVAL, "Try `%s --help' for more information.",
304
                 argv[0]);
305
        }
306
    }
307

    
308
    if ((argc - optind) != 1) {
309
        errx(EINVAL, "Invalid number of argument.\n"
310
             "Try `%s --help' for more information.",
311
             argv[0]);
312
    }
313

    
314
    if (disconnect) {
315
        fd = open(argv[optind], O_RDWR);
316
        if (fd == -1)
317
            errx(errno, "Cannot open %s", argv[optind]);
318

    
319
        nbd_disconnect(fd);
320

    
321
        close(fd);
322

    
323
        printf("%s disconnected\n", argv[optind]);
324

    
325
        return 0;
326
    }
327

    
328
    bdrv_init();
329

    
330
    bs = bdrv_new("hda");
331
    if (bs == NULL)
332
        return 1;
333

    
334
    if (bdrv_open(bs, argv[optind], flags) == -1)
335
        return 1;
336

    
337
    fd_size = bs->total_sectors * 512;
338

    
339
    if (partition != -1 &&
340
        find_partition(bs, partition, &dev_offset, &fd_size))
341
        errx(errno, "Could not find partition %d", partition);
342

    
343
    if (device) {
344
        pid_t pid;
345
        int sock;
346

    
347
        if (!verbose) {
348
            /* detach client and server */
349
            if (daemon(0, 0) == -1) {
350
                errx(errno, "Failed to daemonize");
351
            }
352
        }
353

    
354
        if (socket == NULL) {
355
            sprintf(sockpath, SOCKET_PATH, basename(device));
356
            socket = sockpath;
357
        }
358

    
359
        pid = fork();
360
        if (pid < 0)
361
            return 1;
362
        if (pid != 0) {
363
            off_t size;
364
            size_t blocksize;
365

    
366
            ret = 0;
367
            bdrv_close(bs);
368

    
369
            do {
370
                sock = unix_socket_outgoing(socket);
371
                if (sock == -1) {
372
                    if (errno != ENOENT && errno != ECONNREFUSED)
373
                        goto out;
374
                    sleep(1);        /* wait children */
375
                }
376
            } while (sock == -1);
377

    
378
            fd = open(device, O_RDWR);
379
            if (fd == -1) {
380
                ret = 1;
381
                goto out;
382
            }
383

    
384
            ret = nbd_receive_negotiate(sock, &size, &blocksize);
385
            if (ret == -1) {
386
                ret = 1;
387
                goto out;
388
            }
389

    
390
            ret = nbd_init(fd, sock, size, blocksize);
391
            if (ret == -1) {
392
                ret = 1;
393
                goto out;
394
            }
395

    
396
            printf("NBD device %s is now connected to file %s\n",
397
                    device, argv[optind]);
398

    
399
            /* update partition table */
400

    
401
            show_parts(device);
402

    
403
            nbd_client(fd, sock);
404
            close(fd);
405
 out:
406
            kill(pid, SIGTERM);
407
            unlink(socket);
408

    
409
            return ret;
410
        }
411
        /* children */
412
    }
413

    
414
    sharing_fds = qemu_malloc((shared + 1) * sizeof(int));
415

    
416
    if (socket) {
417
        sharing_fds[0] = unix_socket_incoming(socket);
418
    } else {
419
        sharing_fds[0] = tcp_socket_incoming(bindto, port);
420
    }
421

    
422
    if (sharing_fds[0] == -1)
423
        return 1;
424
    max_fd = sharing_fds[0];
425
    nb_fds++;
426

    
427
    data = qemu_memalign(512, NBD_BUFFER_SIZE);
428
    if (data == NULL)
429
        errx(ENOMEM, "Cannot allocate data buffer");
430

    
431
    do {
432

    
433
        FD_ZERO(&fds);
434
        for (i = 0; i < nb_fds; i++)
435
            FD_SET(sharing_fds[i], &fds);
436

    
437
        ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
438
        if (ret == -1)
439
            break;
440

    
441
        if (FD_ISSET(sharing_fds[0], &fds))
442
            ret--;
443
        for (i = 1; i < nb_fds && ret; i++) {
444
            if (FD_ISSET(sharing_fds[i], &fds)) {
445
                if (nbd_trip(bs, sharing_fds[i], fd_size, dev_offset,
446
                    &offset, readonly, data, NBD_BUFFER_SIZE) != 0) {
447
                    close(sharing_fds[i]);
448
                    nb_fds--;
449
                    sharing_fds[i] = sharing_fds[nb_fds];
450
                    i--;
451
                }
452
                ret--;
453
            }
454
        }
455
        /* new connection ? */
456
        if (FD_ISSET(sharing_fds[0], &fds)) {
457
            if (nb_fds < shared + 1) {
458
                sharing_fds[nb_fds] = accept(sharing_fds[0],
459
                                             (struct sockaddr *)&addr,
460
                                             &addr_len);
461
                if (sharing_fds[nb_fds] != -1 &&
462
                    nbd_negotiate(sharing_fds[nb_fds], fd_size) != -1) {
463
                        if (sharing_fds[nb_fds] > max_fd)
464
                            max_fd = sharing_fds[nb_fds];
465
                        nb_fds++;
466
                }
467
            }
468
        }
469
    } while (persistent || nb_fds > 1);
470
    qemu_free(data);
471

    
472
    close(sharing_fds[0]);
473
    bdrv_close(bs);
474
    qemu_free(sharing_fds);
475
    if (socket)
476
        unlink(socket);
477

    
478
    return 0;
479
}