xref: /linux/tools/net/ynl/lib/ynl.c (revision e7d759f31ca295d589f7420719c311870bb3166f)
1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 #include <errno.h>
3 #include <poll.h>
4 #include <string.h>
5 #include <stdlib.h>
6 #include <linux/types.h>
7 
8 #include <libmnl/libmnl.h>
9 #include <linux/genetlink.h>
10 
11 #include "ynl.h"
12 
13 #define ARRAY_SIZE(arr)		(sizeof(arr) / sizeof(*arr))
14 
15 #define __yerr_msg(yse, _msg...)					\
16 	({								\
17 		struct ynl_error *_yse = (yse);				\
18 									\
19 		if (_yse) {						\
20 			snprintf(_yse->msg, sizeof(_yse->msg) - 1,  _msg); \
21 			_yse->msg[sizeof(_yse->msg) - 1] = 0;		\
22 		}							\
23 	})
24 
25 #define __yerr_code(yse, _code...)		\
26 	({					\
27 		struct ynl_error *_yse = (yse);	\
28 						\
29 		if (_yse) {			\
30 			_yse->code = _code;	\
31 		}				\
32 	})
33 
34 #define __yerr(yse, _code, _msg...)		\
35 	({					\
36 		__yerr_msg(yse, _msg);		\
37 		__yerr_code(yse, _code);	\
38 	})
39 
40 #define __perr(yse, _msg)		__yerr(yse, errno, _msg)
41 
42 #define yerr_msg(_ys, _msg...)		__yerr_msg(&(_ys)->err, _msg)
43 #define yerr(_ys, _code, _msg...)	__yerr(&(_ys)->err, _code, _msg)
44 #define perr(_ys, _msg)			__yerr(&(_ys)->err, errno, _msg)
45 
46 /* -- Netlink boiler plate */
47 static int
48 ynl_err_walk_report_one(struct ynl_policy_nest *policy, unsigned int type,
49 			char *str, int str_sz, int *n)
50 {
51 	if (!policy) {
52 		if (*n < str_sz)
53 			*n += snprintf(str, str_sz, "!policy");
54 		return 1;
55 	}
56 
57 	if (type > policy->max_attr) {
58 		if (*n < str_sz)
59 			*n += snprintf(str, str_sz, "!oob");
60 		return 1;
61 	}
62 
63 	if (!policy->table[type].name) {
64 		if (*n < str_sz)
65 			*n += snprintf(str, str_sz, "!name");
66 		return 1;
67 	}
68 
69 	if (*n < str_sz)
70 		*n += snprintf(str, str_sz - *n,
71 			       ".%s", policy->table[type].name);
72 	return 0;
73 }
74 
75 static int
76 ynl_err_walk(struct ynl_sock *ys, void *start, void *end, unsigned int off,
77 	     struct ynl_policy_nest *policy, char *str, int str_sz,
78 	     struct ynl_policy_nest **nest_pol)
79 {
80 	unsigned int astart_off, aend_off;
81 	const struct nlattr *attr;
82 	unsigned int data_len;
83 	unsigned int type;
84 	bool found = false;
85 	int n = 0;
86 
87 	if (!policy) {
88 		if (n < str_sz)
89 			n += snprintf(str, str_sz, "!policy");
90 		return n;
91 	}
92 
93 	data_len = end - start;
94 
95 	mnl_attr_for_each_payload(start, data_len) {
96 		astart_off = (char *)attr - (char *)start;
97 		aend_off = astart_off + mnl_attr_get_payload_len(attr);
98 		if (aend_off <= off)
99 			continue;
100 
101 		found = true;
102 		break;
103 	}
104 	if (!found)
105 		return 0;
106 
107 	off -= astart_off;
108 
109 	type = mnl_attr_get_type(attr);
110 
111 	if (ynl_err_walk_report_one(policy, type, str, str_sz, &n))
112 		return n;
113 
114 	if (!off) {
115 		if (nest_pol)
116 			*nest_pol = policy->table[type].nest;
117 		return n;
118 	}
119 
120 	if (!policy->table[type].nest) {
121 		if (n < str_sz)
122 			n += snprintf(str, str_sz, "!nest");
123 		return n;
124 	}
125 
126 	off -= sizeof(struct nlattr);
127 	start =  mnl_attr_get_payload(attr);
128 	end = start + mnl_attr_get_payload_len(attr);
129 
130 	return n + ynl_err_walk(ys, start, end, off, policy->table[type].nest,
131 				&str[n], str_sz - n, nest_pol);
132 }
133 
134 #define NLMSGERR_ATTR_MISS_TYPE (NLMSGERR_ATTR_POLICY + 1)
135 #define NLMSGERR_ATTR_MISS_NEST (NLMSGERR_ATTR_POLICY + 2)
136 #define NLMSGERR_ATTR_MAX (NLMSGERR_ATTR_MAX + 2)
137 
138 static int
139 ynl_ext_ack_check(struct ynl_sock *ys, const struct nlmsghdr *nlh,
140 		  unsigned int hlen)
141 {
142 	const struct nlattr *tb[NLMSGERR_ATTR_MAX + 1] = {};
143 	char miss_attr[sizeof(ys->err.msg)];
144 	char bad_attr[sizeof(ys->err.msg)];
145 	const struct nlattr *attr;
146 	const char *str = NULL;
147 
148 	if (!(nlh->nlmsg_flags & NLM_F_ACK_TLVS)) {
149 		yerr_msg(ys, "%s", strerror(ys->err.code));
150 		return MNL_CB_OK;
151 	}
152 
153 	mnl_attr_for_each(attr, nlh, hlen) {
154 		unsigned int len, type;
155 
156 		len = mnl_attr_get_payload_len(attr);
157 		type = mnl_attr_get_type(attr);
158 
159 		if (type > NLMSGERR_ATTR_MAX)
160 			continue;
161 
162 		tb[type] = attr;
163 
164 		switch (type) {
165 		case NLMSGERR_ATTR_OFFS:
166 		case NLMSGERR_ATTR_MISS_TYPE:
167 		case NLMSGERR_ATTR_MISS_NEST:
168 			if (len != sizeof(__u32))
169 				return MNL_CB_ERROR;
170 			break;
171 		case NLMSGERR_ATTR_MSG:
172 			str = mnl_attr_get_payload(attr);
173 			if (str[len - 1])
174 				return MNL_CB_ERROR;
175 			break;
176 		default:
177 			break;
178 		}
179 	}
180 
181 	bad_attr[0] = '\0';
182 	miss_attr[0] = '\0';
183 
184 	if (tb[NLMSGERR_ATTR_OFFS]) {
185 		unsigned int n, off;
186 		void *start, *end;
187 
188 		ys->err.attr_offs = mnl_attr_get_u32(tb[NLMSGERR_ATTR_OFFS]);
189 
190 		n = snprintf(bad_attr, sizeof(bad_attr), "%sbad attribute: ",
191 			     str ? " (" : "");
192 
193 		start = mnl_nlmsg_get_payload_offset(ys->nlh,
194 						     ys->family->hdr_len);
195 		end = mnl_nlmsg_get_payload_tail(ys->nlh);
196 
197 		off = ys->err.attr_offs;
198 		off -= sizeof(struct nlmsghdr);
199 		off -= ys->family->hdr_len;
200 
201 		n += ynl_err_walk(ys, start, end, off, ys->req_policy,
202 				  &bad_attr[n], sizeof(bad_attr) - n, NULL);
203 
204 		if (n >= sizeof(bad_attr))
205 			n = sizeof(bad_attr) - 1;
206 		bad_attr[n] = '\0';
207 	}
208 	if (tb[NLMSGERR_ATTR_MISS_TYPE]) {
209 		struct ynl_policy_nest *nest_pol = NULL;
210 		unsigned int n, off, type;
211 		void *start, *end;
212 		int n2;
213 
214 		type = mnl_attr_get_u32(tb[NLMSGERR_ATTR_MISS_TYPE]);
215 
216 		n = snprintf(miss_attr, sizeof(miss_attr), "%smissing attribute: ",
217 			     bad_attr[0] ? ", " : (str ? " (" : ""));
218 
219 		start = mnl_nlmsg_get_payload_offset(ys->nlh,
220 						     ys->family->hdr_len);
221 		end = mnl_nlmsg_get_payload_tail(ys->nlh);
222 
223 		nest_pol = ys->req_policy;
224 		if (tb[NLMSGERR_ATTR_MISS_NEST]) {
225 			off = mnl_attr_get_u32(tb[NLMSGERR_ATTR_MISS_NEST]);
226 			off -= sizeof(struct nlmsghdr);
227 			off -= ys->family->hdr_len;
228 
229 			n += ynl_err_walk(ys, start, end, off, ys->req_policy,
230 					  &miss_attr[n], sizeof(miss_attr) - n,
231 					  &nest_pol);
232 		}
233 
234 		n2 = 0;
235 		ynl_err_walk_report_one(nest_pol, type, &miss_attr[n],
236 					sizeof(miss_attr) - n, &n2);
237 		n += n2;
238 
239 		if (n >= sizeof(miss_attr))
240 			n = sizeof(miss_attr) - 1;
241 		miss_attr[n] = '\0';
242 	}
243 
244 	/* Implicitly depend on ys->err.code already set */
245 	if (str)
246 		yerr_msg(ys, "Kernel %s: '%s'%s%s%s",
247 			 ys->err.code ? "error" : "warning",
248 			 str, bad_attr, miss_attr,
249 			 bad_attr[0] || miss_attr[0] ? ")" : "");
250 	else if (bad_attr[0] || miss_attr[0])
251 		yerr_msg(ys, "Kernel %s: %s%s",
252 			 ys->err.code ? "error" : "warning",
253 			 bad_attr, miss_attr);
254 	else
255 		yerr_msg(ys, "%s", strerror(ys->err.code));
256 
257 	return MNL_CB_OK;
258 }
259 
260 static int ynl_cb_error(const struct nlmsghdr *nlh, void *data)
261 {
262 	const struct nlmsgerr *err = mnl_nlmsg_get_payload(nlh);
263 	struct ynl_parse_arg *yarg = data;
264 	unsigned int hlen;
265 	int code;
266 
267 	code = err->error >= 0 ? err->error : -err->error;
268 	yarg->ys->err.code = code;
269 	errno = code;
270 
271 	hlen = sizeof(*err);
272 	if (!(nlh->nlmsg_flags & NLM_F_CAPPED))
273 		hlen += mnl_nlmsg_get_payload_len(&err->msg);
274 
275 	ynl_ext_ack_check(yarg->ys, nlh, hlen);
276 
277 	return code ? MNL_CB_ERROR : MNL_CB_STOP;
278 }
279 
280 static int ynl_cb_done(const struct nlmsghdr *nlh, void *data)
281 {
282 	struct ynl_parse_arg *yarg = data;
283 	int err;
284 
285 	err = *(int *)NLMSG_DATA(nlh);
286 	if (err < 0) {
287 		yarg->ys->err.code = -err;
288 		errno = -err;
289 
290 		ynl_ext_ack_check(yarg->ys, nlh, sizeof(int));
291 
292 		return MNL_CB_ERROR;
293 	}
294 	return MNL_CB_STOP;
295 }
296 
297 static int ynl_cb_noop(const struct nlmsghdr *nlh, void *data)
298 {
299 	return MNL_CB_OK;
300 }
301 
302 mnl_cb_t ynl_cb_array[NLMSG_MIN_TYPE] = {
303 	[NLMSG_NOOP]	= ynl_cb_noop,
304 	[NLMSG_ERROR]	= ynl_cb_error,
305 	[NLMSG_DONE]	= ynl_cb_done,
306 	[NLMSG_OVERRUN]	= ynl_cb_noop,
307 };
308 
309 /* Attribute validation */
310 
311 int ynl_attr_validate(struct ynl_parse_arg *yarg, const struct nlattr *attr)
312 {
313 	struct ynl_policy_attr *policy;
314 	unsigned int type, len;
315 	unsigned char *data;
316 
317 	data = mnl_attr_get_payload(attr);
318 	len = mnl_attr_get_payload_len(attr);
319 	type = mnl_attr_get_type(attr);
320 	if (type > yarg->rsp_policy->max_attr) {
321 		yerr(yarg->ys, YNL_ERROR_INTERNAL,
322 		     "Internal error, validating unknown attribute");
323 		return -1;
324 	}
325 
326 	policy = &yarg->rsp_policy->table[type];
327 
328 	switch (policy->type) {
329 	case YNL_PT_REJECT:
330 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
331 		     "Rejected attribute (%s)", policy->name);
332 		return -1;
333 	case YNL_PT_IGNORE:
334 		break;
335 	case YNL_PT_U8:
336 		if (len == sizeof(__u8))
337 			break;
338 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
339 		     "Invalid attribute (u8 %s)", policy->name);
340 		return -1;
341 	case YNL_PT_U16:
342 		if (len == sizeof(__u16))
343 			break;
344 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
345 		     "Invalid attribute (u16 %s)", policy->name);
346 		return -1;
347 	case YNL_PT_U32:
348 		if (len == sizeof(__u32))
349 			break;
350 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
351 		     "Invalid attribute (u32 %s)", policy->name);
352 		return -1;
353 	case YNL_PT_U64:
354 		if (len == sizeof(__u64))
355 			break;
356 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
357 		     "Invalid attribute (u64 %s)", policy->name);
358 		return -1;
359 	case YNL_PT_UINT:
360 		if (len == sizeof(__u32) || len == sizeof(__u64))
361 			break;
362 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
363 		     "Invalid attribute (uint %s)", policy->name);
364 		return -1;
365 	case YNL_PT_FLAG:
366 		/* Let flags grow into real attrs, why not.. */
367 		break;
368 	case YNL_PT_NEST:
369 		if (!len || len >= sizeof(*attr))
370 			break;
371 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
372 		     "Invalid attribute (nest %s)", policy->name);
373 		return -1;
374 	case YNL_PT_BINARY:
375 		if (!policy->len || len == policy->len)
376 			break;
377 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
378 		     "Invalid attribute (binary %s)", policy->name);
379 		return -1;
380 	case YNL_PT_NUL_STR:
381 		if ((!policy->len || len <= policy->len) && !data[len - 1])
382 			break;
383 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
384 		     "Invalid attribute (string %s)", policy->name);
385 		return -1;
386 	case YNL_PT_BITFIELD32:
387 		if (len == sizeof(struct nla_bitfield32))
388 			break;
389 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
390 		     "Invalid attribute (bitfield32 %s)", policy->name);
391 		return -1;
392 	default:
393 		yerr(yarg->ys, YNL_ERROR_ATTR_INVALID,
394 		     "Invalid attribute (unknown %s)", policy->name);
395 		return -1;
396 	}
397 
398 	return 0;
399 }
400 
401 /* Generic code */
402 
403 static void ynl_err_reset(struct ynl_sock *ys)
404 {
405 	ys->err.code = 0;
406 	ys->err.attr_offs = 0;
407 	ys->err.msg[0] = 0;
408 }
409 
410 struct nlmsghdr *ynl_msg_start(struct ynl_sock *ys, __u32 id, __u16 flags)
411 {
412 	struct nlmsghdr *nlh;
413 
414 	ynl_err_reset(ys);
415 
416 	nlh = ys->nlh = mnl_nlmsg_put_header(ys->tx_buf);
417 	nlh->nlmsg_type	= id;
418 	nlh->nlmsg_flags = flags;
419 	nlh->nlmsg_seq = ++ys->seq;
420 
421 	return nlh;
422 }
423 
424 struct nlmsghdr *
425 ynl_gemsg_start(struct ynl_sock *ys, __u32 id, __u16 flags,
426 		__u8 cmd, __u8 version)
427 {
428 	struct genlmsghdr gehdr;
429 	struct nlmsghdr *nlh;
430 	void *data;
431 
432 	nlh = ynl_msg_start(ys, id, flags);
433 
434 	memset(&gehdr, 0, sizeof(gehdr));
435 	gehdr.cmd = cmd;
436 	gehdr.version = version;
437 
438 	data = mnl_nlmsg_put_extra_header(nlh, sizeof(gehdr));
439 	memcpy(data, &gehdr, sizeof(gehdr));
440 
441 	return nlh;
442 }
443 
444 void ynl_msg_start_req(struct ynl_sock *ys, __u32 id)
445 {
446 	ynl_msg_start(ys, id, NLM_F_REQUEST | NLM_F_ACK);
447 }
448 
449 void ynl_msg_start_dump(struct ynl_sock *ys, __u32 id)
450 {
451 	ynl_msg_start(ys, id, NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP);
452 }
453 
454 struct nlmsghdr *
455 ynl_gemsg_start_req(struct ynl_sock *ys, __u32 id, __u8 cmd, __u8 version)
456 {
457 	return ynl_gemsg_start(ys, id, NLM_F_REQUEST | NLM_F_ACK, cmd, version);
458 }
459 
460 struct nlmsghdr *
461 ynl_gemsg_start_dump(struct ynl_sock *ys, __u32 id, __u8 cmd, __u8 version)
462 {
463 	return ynl_gemsg_start(ys, id, NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP,
464 			       cmd, version);
465 }
466 
467 int ynl_recv_ack(struct ynl_sock *ys, int ret)
468 {
469 	if (!ret) {
470 		yerr(ys, YNL_ERROR_EXPECT_ACK,
471 		     "Expecting an ACK but nothing received");
472 		return -1;
473 	}
474 
475 	ret = mnl_socket_recvfrom(ys->sock, ys->rx_buf, MNL_SOCKET_BUFFER_SIZE);
476 	if (ret < 0) {
477 		perr(ys, "Socket receive failed");
478 		return ret;
479 	}
480 	return mnl_cb_run(ys->rx_buf, ret, ys->seq, ys->portid,
481 			  ynl_cb_null, ys);
482 }
483 
484 int ynl_cb_null(const struct nlmsghdr *nlh, void *data)
485 {
486 	struct ynl_parse_arg *yarg = data;
487 
488 	yerr(yarg->ys, YNL_ERROR_UNEXPECT_MSG,
489 	     "Received a message when none were expected");
490 
491 	return MNL_CB_ERROR;
492 }
493 
494 /* Init/fini and genetlink boiler plate */
495 static int
496 ynl_get_family_info_mcast(struct ynl_sock *ys, const struct nlattr *mcasts)
497 {
498 	const struct nlattr *entry, *attr;
499 	unsigned int i;
500 
501 	mnl_attr_for_each_nested(attr, mcasts)
502 		ys->n_mcast_groups++;
503 
504 	if (!ys->n_mcast_groups)
505 		return 0;
506 
507 	ys->mcast_groups = calloc(ys->n_mcast_groups,
508 				  sizeof(*ys->mcast_groups));
509 	if (!ys->mcast_groups)
510 		return MNL_CB_ERROR;
511 
512 	i = 0;
513 	mnl_attr_for_each_nested(entry, mcasts) {
514 		mnl_attr_for_each_nested(attr, entry) {
515 			if (mnl_attr_get_type(attr) == CTRL_ATTR_MCAST_GRP_ID)
516 				ys->mcast_groups[i].id = mnl_attr_get_u32(attr);
517 			if (mnl_attr_get_type(attr) == CTRL_ATTR_MCAST_GRP_NAME) {
518 				strncpy(ys->mcast_groups[i].name,
519 					mnl_attr_get_str(attr),
520 					GENL_NAMSIZ - 1);
521 				ys->mcast_groups[i].name[GENL_NAMSIZ - 1] = 0;
522 			}
523 		}
524 	}
525 
526 	return 0;
527 }
528 
529 static int ynl_get_family_info_cb(const struct nlmsghdr *nlh, void *data)
530 {
531 	struct ynl_parse_arg *yarg = data;
532 	struct ynl_sock *ys = yarg->ys;
533 	const struct nlattr *attr;
534 	bool found_id = true;
535 
536 	mnl_attr_for_each(attr, nlh, sizeof(struct genlmsghdr)) {
537 		if (mnl_attr_get_type(attr) == CTRL_ATTR_MCAST_GROUPS)
538 			if (ynl_get_family_info_mcast(ys, attr))
539 				return MNL_CB_ERROR;
540 
541 		if (mnl_attr_get_type(attr) != CTRL_ATTR_FAMILY_ID)
542 			continue;
543 
544 		if (mnl_attr_get_payload_len(attr) != sizeof(__u16)) {
545 			yerr(ys, YNL_ERROR_ATTR_INVALID, "Invalid family ID");
546 			return MNL_CB_ERROR;
547 		}
548 
549 		ys->family_id = mnl_attr_get_u16(attr);
550 		found_id = true;
551 	}
552 
553 	if (!found_id) {
554 		yerr(ys, YNL_ERROR_ATTR_MISSING, "Family ID missing");
555 		return MNL_CB_ERROR;
556 	}
557 	return MNL_CB_OK;
558 }
559 
560 static int ynl_sock_read_family(struct ynl_sock *ys, const char *family_name)
561 {
562 	struct ynl_parse_arg yarg = { .ys = ys, };
563 	struct nlmsghdr *nlh;
564 	int err;
565 
566 	nlh = ynl_gemsg_start_req(ys, GENL_ID_CTRL, CTRL_CMD_GETFAMILY, 1);
567 	mnl_attr_put_strz(nlh, CTRL_ATTR_FAMILY_NAME, family_name);
568 
569 	err = mnl_socket_sendto(ys->sock, nlh, nlh->nlmsg_len);
570 	if (err < 0) {
571 		perr(ys, "failed to request socket family info");
572 		return err;
573 	}
574 
575 	err = mnl_socket_recvfrom(ys->sock, ys->rx_buf, MNL_SOCKET_BUFFER_SIZE);
576 	if (err <= 0) {
577 		perr(ys, "failed to receive the socket family info");
578 		return err;
579 	}
580 	err = mnl_cb_run2(ys->rx_buf, err, ys->seq, ys->portid,
581 			  ynl_get_family_info_cb, &yarg,
582 			  ynl_cb_array, ARRAY_SIZE(ynl_cb_array));
583 	if (err < 0) {
584 		free(ys->mcast_groups);
585 		perr(ys, "failed to receive the socket family info - no such family?");
586 		return err;
587 	}
588 
589 	return ynl_recv_ack(ys, err);
590 }
591 
592 struct ynl_sock *
593 ynl_sock_create(const struct ynl_family *yf, struct ynl_error *yse)
594 {
595 	struct ynl_sock *ys;
596 	int one = 1;
597 
598 	ys = malloc(sizeof(*ys) + 2 * MNL_SOCKET_BUFFER_SIZE);
599 	if (!ys)
600 		return NULL;
601 	memset(ys, 0, sizeof(*ys));
602 
603 	ys->family = yf;
604 	ys->tx_buf = &ys->raw_buf[0];
605 	ys->rx_buf = &ys->raw_buf[MNL_SOCKET_BUFFER_SIZE];
606 	ys->ntf_last_next = &ys->ntf_first;
607 
608 	ys->sock = mnl_socket_open(NETLINK_GENERIC);
609 	if (!ys->sock) {
610 		__perr(yse, "failed to create a netlink socket");
611 		goto err_free_sock;
612 	}
613 
614 	if (mnl_socket_setsockopt(ys->sock, NETLINK_CAP_ACK,
615 				  &one, sizeof(one))) {
616 		__perr(yse, "failed to enable netlink ACK");
617 		goto err_close_sock;
618 	}
619 	if (mnl_socket_setsockopt(ys->sock, NETLINK_EXT_ACK,
620 				  &one, sizeof(one))) {
621 		__perr(yse, "failed to enable netlink ext ACK");
622 		goto err_close_sock;
623 	}
624 
625 	ys->seq = random();
626 	ys->portid = mnl_socket_get_portid(ys->sock);
627 
628 	if (ynl_sock_read_family(ys, yf->name)) {
629 		if (yse)
630 			memcpy(yse, &ys->err, sizeof(*yse));
631 		goto err_close_sock;
632 	}
633 
634 	return ys;
635 
636 err_close_sock:
637 	mnl_socket_close(ys->sock);
638 err_free_sock:
639 	free(ys);
640 	return NULL;
641 }
642 
643 void ynl_sock_destroy(struct ynl_sock *ys)
644 {
645 	struct ynl_ntf_base_type *ntf;
646 
647 	mnl_socket_close(ys->sock);
648 	while ((ntf = ynl_ntf_dequeue(ys)))
649 		ynl_ntf_free(ntf);
650 	free(ys->mcast_groups);
651 	free(ys);
652 }
653 
654 /* YNL multicast handling */
655 
656 void ynl_ntf_free(struct ynl_ntf_base_type *ntf)
657 {
658 	ntf->free(ntf);
659 }
660 
661 int ynl_subscribe(struct ynl_sock *ys, const char *grp_name)
662 {
663 	unsigned int i;
664 	int err;
665 
666 	for (i = 0; i < ys->n_mcast_groups; i++)
667 		if (!strcmp(ys->mcast_groups[i].name, grp_name))
668 			break;
669 	if (i == ys->n_mcast_groups) {
670 		yerr(ys, ENOENT, "Multicast group '%s' not found", grp_name);
671 		return -1;
672 	}
673 
674 	err = mnl_socket_setsockopt(ys->sock, NETLINK_ADD_MEMBERSHIP,
675 				    &ys->mcast_groups[i].id,
676 				    sizeof(ys->mcast_groups[i].id));
677 	if (err < 0) {
678 		perr(ys, "Subscribing to multicast group failed");
679 		return -1;
680 	}
681 
682 	return 0;
683 }
684 
685 int ynl_socket_get_fd(struct ynl_sock *ys)
686 {
687 	return mnl_socket_get_fd(ys->sock);
688 }
689 
690 struct ynl_ntf_base_type *ynl_ntf_dequeue(struct ynl_sock *ys)
691 {
692 	struct ynl_ntf_base_type *ntf;
693 
694 	if (!ynl_has_ntf(ys))
695 		return NULL;
696 
697 	ntf = ys->ntf_first;
698 	ys->ntf_first = ntf->next;
699 	if (ys->ntf_last_next == &ntf->next)
700 		ys->ntf_last_next = &ys->ntf_first;
701 
702 	return ntf;
703 }
704 
705 static int ynl_ntf_parse(struct ynl_sock *ys, const struct nlmsghdr *nlh)
706 {
707 	struct ynl_parse_arg yarg = { .ys = ys, };
708 	const struct ynl_ntf_info *info;
709 	struct ynl_ntf_base_type *rsp;
710 	struct genlmsghdr *gehdr;
711 	int ret;
712 
713 	gehdr = mnl_nlmsg_get_payload(nlh);
714 	if (gehdr->cmd >= ys->family->ntf_info_size)
715 		return MNL_CB_ERROR;
716 	info = &ys->family->ntf_info[gehdr->cmd];
717 	if (!info->cb)
718 		return MNL_CB_ERROR;
719 
720 	rsp = calloc(1, info->alloc_sz);
721 	rsp->free = info->free;
722 	yarg.data = rsp->data;
723 	yarg.rsp_policy = info->policy;
724 
725 	ret = info->cb(nlh, &yarg);
726 	if (ret <= MNL_CB_STOP)
727 		goto err_free;
728 
729 	rsp->family = nlh->nlmsg_type;
730 	rsp->cmd = gehdr->cmd;
731 
732 	*ys->ntf_last_next = rsp;
733 	ys->ntf_last_next = &rsp->next;
734 
735 	return MNL_CB_OK;
736 
737 err_free:
738 	info->free(rsp);
739 	return MNL_CB_ERROR;
740 }
741 
742 static int ynl_ntf_trampoline(const struct nlmsghdr *nlh, void *data)
743 {
744 	return ynl_ntf_parse((struct ynl_sock *)data, nlh);
745 }
746 
747 int ynl_ntf_check(struct ynl_sock *ys)
748 {
749 	ssize_t len;
750 	int err;
751 
752 	do {
753 		/* libmnl doesn't let us pass flags to the recv to make
754 		 * it non-blocking so we need to poll() or peek() :|
755 		 */
756 		struct pollfd pfd = { };
757 
758 		pfd.fd = mnl_socket_get_fd(ys->sock);
759 		pfd.events = POLLIN;
760 		err = poll(&pfd, 1, 1);
761 		if (err < 1)
762 			return err;
763 
764 		len = mnl_socket_recvfrom(ys->sock, ys->rx_buf,
765 					  MNL_SOCKET_BUFFER_SIZE);
766 		if (len < 0)
767 			return len;
768 
769 		err = mnl_cb_run2(ys->rx_buf, len, ys->seq, ys->portid,
770 				  ynl_ntf_trampoline, ys,
771 				  ynl_cb_array, NLMSG_MIN_TYPE);
772 		if (err < 0)
773 			return err;
774 	} while (err > 0);
775 
776 	return 0;
777 }
778 
779 /* YNL specific helpers used by the auto-generated code */
780 
781 struct ynl_dump_list_type *YNL_LIST_END = (void *)(0xb4d123);
782 
783 void ynl_error_unknown_notification(struct ynl_sock *ys, __u8 cmd)
784 {
785 	yerr(ys, YNL_ERROR_UNKNOWN_NTF,
786 	     "Unknown notification message type '%d'", cmd);
787 }
788 
789 int ynl_error_parse(struct ynl_parse_arg *yarg, const char *msg)
790 {
791 	yerr(yarg->ys, YNL_ERROR_INV_RESP, "Error parsing response: %s", msg);
792 	return MNL_CB_ERROR;
793 }
794 
795 static int
796 ynl_check_alien(struct ynl_sock *ys, const struct nlmsghdr *nlh, __u32 rsp_cmd)
797 {
798 	struct genlmsghdr *gehdr;
799 
800 	if (mnl_nlmsg_get_payload_len(nlh) < sizeof(*gehdr)) {
801 		yerr(ys, YNL_ERROR_INV_RESP,
802 		     "Kernel responded with truncated message");
803 		return -1;
804 	}
805 
806 	gehdr = mnl_nlmsg_get_payload(nlh);
807 	if (gehdr->cmd != rsp_cmd)
808 		return ynl_ntf_parse(ys, nlh);
809 
810 	return 0;
811 }
812 
813 static int ynl_req_trampoline(const struct nlmsghdr *nlh, void *data)
814 {
815 	struct ynl_req_state *yrs = data;
816 	int ret;
817 
818 	ret = ynl_check_alien(yrs->yarg.ys, nlh, yrs->rsp_cmd);
819 	if (ret)
820 		return ret < 0 ? MNL_CB_ERROR : MNL_CB_OK;
821 
822 	return yrs->cb(nlh, &yrs->yarg);
823 }
824 
825 int ynl_exec(struct ynl_sock *ys, struct nlmsghdr *req_nlh,
826 	     struct ynl_req_state *yrs)
827 {
828 	ssize_t len;
829 	int err;
830 
831 	err = mnl_socket_sendto(ys->sock, req_nlh, req_nlh->nlmsg_len);
832 	if (err < 0)
833 		return err;
834 
835 	do {
836 		len = mnl_socket_recvfrom(ys->sock, ys->rx_buf,
837 					  MNL_SOCKET_BUFFER_SIZE);
838 		if (len < 0)
839 			return len;
840 
841 		err = mnl_cb_run2(ys->rx_buf, len, ys->seq, ys->portid,
842 				  ynl_req_trampoline, yrs,
843 				  ynl_cb_array, NLMSG_MIN_TYPE);
844 		if (err < 0)
845 			return err;
846 	} while (err > 0);
847 
848 	return 0;
849 }
850 
851 static int ynl_dump_trampoline(const struct nlmsghdr *nlh, void *data)
852 {
853 	struct ynl_dump_state *ds = data;
854 	struct ynl_dump_list_type *obj;
855 	struct ynl_parse_arg yarg = {};
856 	int ret;
857 
858 	ret = ynl_check_alien(ds->ys, nlh, ds->rsp_cmd);
859 	if (ret)
860 		return ret < 0 ? MNL_CB_ERROR : MNL_CB_OK;
861 
862 	obj = calloc(1, ds->alloc_sz);
863 	if (!obj)
864 		return MNL_CB_ERROR;
865 
866 	if (!ds->first)
867 		ds->first = obj;
868 	if (ds->last)
869 		ds->last->next = obj;
870 	ds->last = obj;
871 
872 	yarg.ys = ds->ys;
873 	yarg.rsp_policy = ds->rsp_policy;
874 	yarg.data = &obj->data;
875 
876 	return ds->cb(nlh, &yarg);
877 }
878 
879 static void *ynl_dump_end(struct ynl_dump_state *ds)
880 {
881 	if (!ds->first)
882 		return YNL_LIST_END;
883 
884 	ds->last->next = YNL_LIST_END;
885 	return ds->first;
886 }
887 
888 int ynl_exec_dump(struct ynl_sock *ys, struct nlmsghdr *req_nlh,
889 		  struct ynl_dump_state *yds)
890 {
891 	ssize_t len;
892 	int err;
893 
894 	err = mnl_socket_sendto(ys->sock, req_nlh, req_nlh->nlmsg_len);
895 	if (err < 0)
896 		return err;
897 
898 	do {
899 		len = mnl_socket_recvfrom(ys->sock, ys->rx_buf,
900 					  MNL_SOCKET_BUFFER_SIZE);
901 		if (len < 0)
902 			goto err_close_list;
903 
904 		err = mnl_cb_run2(ys->rx_buf, len, ys->seq, ys->portid,
905 				  ynl_dump_trampoline, yds,
906 				  ynl_cb_array, NLMSG_MIN_TYPE);
907 		if (err < 0)
908 			goto err_close_list;
909 	} while (err > 0);
910 
911 	yds->first = ynl_dump_end(yds);
912 	return 0;
913 
914 err_close_list:
915 	yds->first = ynl_dump_end(yds);
916 	return -1;
917 }
918