Refactor the negotiate() and connected functions
[nbd.git] / nbd-get-status.c
blob2b98881d6c288f88bc2000e37a054da07c77bbf3
1 #include "config.h"
2 #include "lfs.h"
4 #include <stdio.h>
5 #include <netlink/netlink.h>
6 #include <netlink/genl/genl.h>
7 #include <netlink/genl/ctrl.h>
8 #include "cliserv.h"
9 #include "nbd-netlink.h"
11 static struct nla_policy nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
12 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
13 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
16 static struct nl_sock *get_nbd_socket(int *driver_id)
18 struct nl_sock *socket;
19 int id;
21 socket = nl_socket_alloc();
22 if (!socket)
23 err("Couldn't allocate netlink socket\n");
25 if (genl_connect(socket))
26 err("Couldn't connect to the generic netlink socket\n");
27 id = genl_ctrl_resolve(socket, "nbd");
28 if (id < 0)
29 err("Couldn't resolve the nbd netlink family, make sure the nbd module is loaded and your nbd driver supports the netlink interface.\n");
30 if (driver_id)
31 *driver_id = id;
32 return socket;
35 static int callback(struct nl_msg *msg, void *arg)
37 struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
38 struct nlattr *msg_attr[NBD_ATTR_MAX + 1];
39 struct nlattr *attr;
40 int ret, rem;
42 ret = nla_parse(msg_attr, NBD_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
43 genlmsg_attrlen(gnlh, 0), NULL);
44 if (ret)
45 err("Invalid response from get status?\n");
47 nla_for_each_nested(attr, msg_attr[NBD_ATTR_DEVICE_LIST], rem) {
48 struct nlattr *device[NBD_DEVICE_ATTR_MAX + 1];
49 u32 index;
50 uint8_t connected;
52 if (nla_type(attr) != NBD_DEVICE_ITEM)
53 err("Invalid attr type in the device list\n");
54 ret = nla_parse_nested(device, NBD_DEVICE_ATTR_MAX, attr,
55 nbd_device_policy);
56 if (ret)
57 err("Invalid attr device attr\n");
58 index = nla_get_u32(device[NBD_DEVICE_INDEX]);
59 connected = nla_get_u8(device[NBD_DEVICE_CONNECTED]);
60 printf("/dev/nbd%d: %s\n", (int)index,
61 connected ? "connected" : "disconnected");
63 return NL_OK;
66 int main(int argc, char **argv)
68 struct nl_sock *socket;
69 struct nlattr *sock_attr;
70 struct nl_msg *msg;
71 int driver_id;
72 int index = -1;
74 if (argc > 1) {
75 if (sscanf(argv[1], "/dev/nbd%d", &index) != 1)
76 err("Invalid nbd device target\n");
79 socket = get_nbd_socket(&driver_id);
80 nl_socket_modify_cb(socket, NL_CB_VALID, NL_CB_CUSTOM, callback, NULL);
82 msg = nlmsg_alloc();
83 if (!msg)
84 err("Couldn't allocate netlink message\n");
85 genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, driver_id, 0, 0,
86 NBD_CMD_STATUS, 0);
87 if (index >= 0)
88 NLA_PUT_U32(msg, NBD_ATTR_INDEX, index);
89 if (nl_send_sync(socket, msg) < 0)
90 err("Failed to get status\n");
91 return 0;
92 nla_put_failure:
93 err("Failed to create netlink message\n");