1 /* nbd-client.c - network block device client
3 * Copyright 2010 Rob Landley <rob@landley.net>
7 // This little dance is because a NEWTOY with - in the name tries to do
8 // things like prototype "nbd-client_main" which isn't a valid symbol. So
9 // we hide the underscore name and OLDTOY the name we want.
10 USE_NBD_CLIENT(NEWTOY(nbd_client, "<3>3ns", 0))
11 USE_NBD_CLIENT(OLDTOY(nbd-client, nbd_client, TOYFLAG_USR|TOYFLAG_BIN))
17 usage: nbd-client [-ns] HOST PORT DEVICE
19 -n Do not fork into background
20 -s nbd swap support (lock server into memory)
24 usage: nbd-client [-sSpn] [-b BLKSZ] [-t SECS] [-N name] HOST PORT DEVICE
35 #define FOR_nbd_client
37 #include <linux/nbd.h>
39 void nbd_client_main(void)
41 int sock = -1, nbd, flags;
42 unsigned long timeout = 0;
43 char *host=toys.optargs[0], *port=toys.optargs[1], *device=toys.optargs[2];
46 // Repeat until spanked
48 nbd = xopen(device, O_RDWR);
52 // Find and connect to server
54 sock = xconnect(host, port, AF_UNSPEC, SOCK_STREAM, 0, 0);
56 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &temp, sizeof(int));
60 xreadall(sock, toybuf, 152);
61 if (memcmp(toybuf, "NBDMAGIC\x00\x00\x42\x02\x81\x86\x12\x53", 16))
62 error_exit("bad login %s:%s", host, port);
63 devsize = SWAP_BE64(*(uint64_t *)(toybuf+16));
64 flags = SWAP_BE32(*(int *)(toybuf+24));
66 // Set 4k block size. Everything uses that these days.
67 ioctl(nbd, NBD_SET_BLKSIZE, 4096);
68 ioctl(nbd, NBD_SET_SIZE_BLOCKS, devsize/4096);
69 ioctl(nbd, NBD_CLEAR_SOCK);
71 // If the sucker was exported read only, respect that locally.
72 temp = (flags & 2) ? 1 : 0;
73 xioctl(nbd, BLKROSET, &temp);
75 if (timeout && ioctl(nbd, NBD_SET_TIMEOUT, timeout)<0) break;
76 if (ioctl(nbd, NBD_SET_SOCK, sock) < 0) break;
78 if (toys.optflags & FLAG_s) mlockall(MCL_CURRENT|MCL_FUTURE);
80 // Open the device to force reread of the partition table.
81 if ((toys.optflags & FLAG_n) || !xfork()) {
82 char *s = strrchr(device, '/');
85 sprintf(toybuf, "/sys/block/%.32s/pid", s ? s+1 : device);
86 // Is it up yet? (Give it 10 seconds.)
87 for (i=0; i<100; i++) {
88 temp = open(toybuf, O_RDONLY);
89 if (temp == -1) msleep(100);
95 close(open(device, O_RDONLY));
96 if (!(toys.optflags & FLAG_n)) exit(0);
101 if (daemon(0,0)) perror_exit("daemonize");
103 // Process NBD requests until further notice.
105 if (ioctl(nbd, NBD_DO_IT)>=0 || errno==EBADR) break;
109 // Flush queue and exit.
110 ioctl(nbd, NBD_CLEAR_QUE);
111 ioctl(nbd, NBD_CLEAR_SOCK);
112 if (CFG_TOYBOX_FREE) close(nbd);