xref: /netbsd-src/usr.sbin/ldpd/socketops.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /* $NetBSD: socketops.c,v 1.34 2017/04/12 17:02:51 roy Exp $ */
2 
3 /*
4  * Copyright (c) 2010 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Mihai Chelaru <kefren@NetBSD.org>
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/socket.h>
35 #include <sys/ioctl.h>
36 #include <net/if.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 
40 #include <assert.h>
41 #include <errno.h>
42 #include <ifaddrs.h>
43 #include <poll.h>
44 #include <signal.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <strings.h>
48 #include <unistd.h>
49 
50 #include "conffile.h"
51 #include "fsm.h"
52 #include "ldp.h"
53 #include "ldp_command.h"
54 #include "tlv.h"
55 #include "ldp_peer.h"
56 #include "notifications.h"
57 #include "tlv_stack.h"
58 #include "mpls_interface.h"
59 #include "label.h"
60 #include "mpls_routes.h"
61 #include "ldp_errors.h"
62 #include "socketops.h"
63 
64 int ls;				/* TCP listening socket on port 646 */
65 int route_socket;		/* used to see when a route is added/deleted */
66 int command_socket;		/* Listening socket for interface command */
67 int current_msg_id = 0x233;
68 int command_port = LDP_COMMAND_PORT;
69 extern int      replay_index;
70 extern struct rt_msg replay_rt[REPLAY_MAX];
71 extern struct com_sock	csockets[MAX_COMMAND_SOCKETS];
72 
73 int	ldp_hello_time = LDP_HELLO_TIME;
74 int	ldp_keepalive_time = LDP_KEEPALIVE_TIME;
75 int	ldp_holddown_time = LDP_HOLDTIME;
76 int	no_default_route = 1;
77 int	loop_detection = 0;
78 bool	may_connect;
79 
80 void	recv_pdu(int);
81 void	send_hello_alarm(int);
82 __dead static void bail_out(int);
83 static void print_info(int);
84 static int bind_socket(int s, int stype);
85 static int set_tos(int);
86 static int socket_reuse_port(int);
87 static int get_local_addr(struct sockaddr_dl *, struct in_addr *);
88 static int is_hello_socket(int);
89 static int is_passive_if(const char *if_name);
90 
91 int
92 create_hello_sockets()
93 {
94 	struct ip_mreq  mcast_addr;
95 	int s, joined_groups;
96 	struct ifaddrs *ifa, *ifb;
97 	uint lastifindex;
98 #ifdef INET6
99 	struct ipv6_mreq mcast_addr6;
100 	struct sockaddr_in6 *if_sa6;
101 #endif
102 	struct hello_socket *hs;
103 
104 	SLIST_INIT(&hello_socket_head);
105 
106 	s = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
107 	if (s < 0)
108 		return s;
109 	debugp("INET4 socket created (%d)\n", s);
110 	/*
111 	 * RFC5036 specifies we should listen to all subnet routers multicast
112 	 * group
113 	 */
114 	mcast_addr.imr_multiaddr.s_addr = htonl(INADDR_ALLRTRS_GROUP);
115 
116 	if (socket_reuse_port(s) < 0)
117 		goto chs_error;
118 	/* Bind it to port 646 */
119 	if (bind_socket(s, AF_INET) == -1) {
120 		warnp("Cannot bind INET hello socket\n");
121 		goto chs_error;
122 	}
123 
124 	/* We don't need to receive back our messages */
125 	if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &(u_char){0},
126 	    sizeof(u_char)) == -1) {
127 		fatalp("INET setsockopt IP_MCAST_LOOP: %s\n", strerror(errno));
128 		goto chs_error;
129 	}
130 	/* Finally join the group on all interfaces */
131 	if (getifaddrs(&ifa) == -1) {
132 		fatalp("Cannot iterate interfaces\n");
133 		return -1;
134 	}
135 	lastifindex = UINT_MAX;
136 	joined_groups = 0;
137 	for (ifb = ifa; ifb; ifb = ifb->ifa_next) {
138 		struct sockaddr_in *if_sa = (struct sockaddr_in *) ifb->ifa_addr;
139 		if (if_sa->sin_family != AF_INET || (!(ifb->ifa_flags & IFF_UP)) ||
140 		    (ifb->ifa_flags & IFF_LOOPBACK) ||
141 		    (!(ifb->ifa_flags & IFF_MULTICAST)) ||
142 		    (ntohl(if_sa->sin_addr.s_addr) >> 24 == IN_LOOPBACKNET) ||
143 		    is_passive_if(ifb->ifa_name) ||
144 		    lastifindex == if_nametoindex(ifb->ifa_name))
145 			continue;
146 		lastifindex = if_nametoindex(ifb->ifa_name);
147 
148 		mcast_addr.imr_interface.s_addr = if_sa->sin_addr.s_addr;
149 		debugp("Join IPv4 mcast on %s\n", ifb->ifa_name);
150         	if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mcast_addr,
151 		    sizeof(mcast_addr)) == -1) {
152         	        fatalp("setsockopt ADD_MEMBER: %s\n", strerror(errno));
153 			goto chs_error;
154         	}
155 		joined_groups++;
156 		if (joined_groups == IP_MAX_MEMBERSHIPS) {
157 			warnp("Maximum group memberships reached for INET socket\n");
158 			break;
159 		}
160 	}
161 	/* TTL:1 for IPv4 */
162 	if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &(int){1},
163 	    sizeof(int)) == -1) {
164 		fatalp("set mcast ttl: %s\n", strerror(errno));
165 		goto chs_error;
166 	}
167 	/* TOS :0xc0 for IPv4 */
168 	if (set_tos(s) == -1) {
169 		fatalp("set_tos: %s", strerror(errno));
170 		goto chs_error;
171 	}
172 	/* we need to get the input interface for message processing */
173 	if (setsockopt(s, IPPROTO_IP, IP_RECVIF, &(uint32_t){1},
174 	    sizeof(uint32_t)) == -1) {
175 		fatalp("Cannot set IP_RECVIF\n");
176 		goto chs_error;
177 	}
178 
179 	hs = (struct hello_socket *)malloc(sizeof(*hs));
180 	if (hs == NULL) {
181 		fatalp("Cannot alloc hello_socket structure\n");
182 		goto chs_error;
183 	}
184 	hs->type = AF_INET;
185 	hs->socket = s;
186 	SLIST_INSERT_HEAD(&hello_socket_head, hs, listentry);
187 
188 #ifdef INET6
189 	/*
190 	 * Now we do the same for IPv6
191 	 */
192 	s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
193 	if (s < 0) {
194 		fatalp("Cannot create INET6 socket\n");
195 		return -1;
196 	}
197 	debugp("INET6 socket created (%d)\n", s);
198 
199 	if (socket_reuse_port(s) < 0)
200 		goto chs_error;
201 
202 	if (bind_socket(s, AF_INET6) == -1) {
203 		fatalp("Cannot bind INET6 hello socket\n");
204 		goto chs_error;
205 	}
206 
207 	if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
208 	    &(uint){0}, sizeof(uint)) == -1) {
209 		fatalp("INET6 setsocketopt IP_MCAST_LOOP: %s\n",
210 		    strerror(errno));
211 		goto chs_error;
212 	}
213 
214 	lastifindex = UINT_MAX;
215 	mcast_addr6.ipv6mr_multiaddr = in6addr_linklocal_allrouters;
216 	for (ifb = ifa; ifb; ifb = ifb->ifa_next) {
217 		if_sa6 = (struct sockaddr_in6 *) ifb->ifa_addr;
218 		if (if_sa6->sin6_family != AF_INET6 ||
219 		    (!(ifb->ifa_flags & IFF_UP)) ||
220 		    (!(ifb->ifa_flags & IFF_MULTICAST)) ||
221 		    (ifb->ifa_flags & IFF_LOOPBACK) ||
222 		    is_passive_if(ifb->ifa_name) ||
223 		    IN6_IS_ADDR_LOOPBACK(&if_sa6->sin6_addr))
224 			continue;
225 		/*
226 		 * draft-ietf-mpls-ldp-ipv6-07 Section 5.1:
227 		 * Additionally, the link-local
228 		 * IPv6 address MUST be used as the source IP address in IPv6
229 		 * LDP Link Hellos.
230 		 */
231 		if (IN6_IS_ADDR_LINKLOCAL(&if_sa6->sin6_addr) == 0)
232 			continue;
233 		/* We should have only one LLADDR per interface, but... */
234 		if (lastifindex == if_nametoindex(ifb->ifa_name))
235 			continue;
236 		mcast_addr6.ipv6mr_interface = lastifindex =
237 		    if_nametoindex(ifb->ifa_name);
238 
239 		debugp("Join IPv6 mcast on %s\n", ifb->ifa_name);
240 		if (setsockopt(s, IPPROTO_IPV6, IPV6_JOIN_GROUP,
241 		    (char *)&mcast_addr6, sizeof(mcast_addr6)) == -1) {
242 			fatalp("INET6 setsockopt JOIN: %s\n", strerror(errno));
243 			goto chs_error;
244 		}
245 	}
246 	freeifaddrs(ifa);
247 
248 	/* TTL: 255 for IPv6 - draft-ietf-mpls-ldp-ipv6-07 Section 9 */
249 	if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
250 	    &(int){255}, sizeof(int)) == -1) {
251 		fatalp("set mcast hops: %s\n", strerror(errno));
252 		goto chs_error;
253 	}
254 	if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO,
255 	    &(uint32_t){1}, sizeof(uint32_t)) == -1)
256 		goto chs_error;
257 
258 	hs = (struct hello_socket *)malloc(sizeof(*hs));
259 	if (hs == NULL) {
260 		fatalp("Memory alloc problem: hs\n");
261 		goto chs_error;
262 	}
263 
264 	hs->type = AF_INET6;
265 	hs->socket = s;
266 	SLIST_INSERT_HEAD(&hello_socket_head, hs, listentry);
267 #endif
268 	return 0;
269 chs_error:
270 	close(s);
271 	return -1;
272 }
273 
274 /* Check if parameter is a hello socket */
275 int
276 is_hello_socket(int s)
277 {
278 	struct hello_socket *hs;
279 
280 	SLIST_FOREACH(hs, &hello_socket_head, listentry)
281 		if (hs->socket == s)
282 			return 1;
283 	return 0;
284 }
285 
286 /* Check if interface is passive */
287 static int
288 is_passive_if(const char *if_name)
289 {
290 	struct conf_interface *coif;
291 
292 	SLIST_FOREACH(coif, &coifs_head, iflist)
293 		if (strncasecmp(if_name, coif->if_name, IF_NAMESIZE) == 0 &&
294 		    coif->passive != 0)
295 			return 1;
296 	return 0;
297 }
298 
299 /* Sets the TTL to 1 as we don't want to transmit outside this subnet */
300 int
301 set_ttl(int s)
302 {
303 	int             ret;
304 	if ((ret = setsockopt(s, IPPROTO_IP, IP_TTL, &(int){1}, sizeof(int)))
305 	    == -1)
306 		fatalp("set_ttl: %s", strerror(errno));
307 	return ret;
308 }
309 
310 /* Sets TOS to 0xc0 aka IP Precedence 6 */
311 static int
312 set_tos(int s)
313 {
314 	int             ret;
315 	if ((ret = setsockopt(s, IPPROTO_IP, IP_TOS, &(int){0xc0},
316 	    sizeof(int))) == -1)
317 		fatalp("set_tos: %s", strerror(errno));
318 	return ret;
319 }
320 
321 static int
322 socket_reuse_port(int s)
323 {
324 	int ret;
325 	if ((ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &(int){1},
326 	    sizeof(int))) == -1)
327 		fatalp("socket_reuse_port: %s", strerror(errno));
328 	return ret;
329 }
330 
331 /* binds an UDP socket */
332 static int
333 bind_socket(int s, int stype)
334 {
335 	union sockunion su;
336 
337 	assert (stype == AF_INET || stype == AF_INET6);
338 
339 	memset(&su, 0, sizeof su);
340 	if (stype == AF_INET) {
341 		su.sin.sin_len = sizeof(su.sin);
342 		su.sin.sin_family = AF_INET;
343 		su.sin.sin_addr.s_addr = htonl(INADDR_ANY);
344 		su.sin.sin_port = htons(LDP_PORT);
345 	}
346 #ifdef INET6
347 	else if (stype == AF_INET6) {
348 		su.sin6.sin6_len = sizeof(su.sin6);
349 		su.sin6.sin6_family = AF_INET6;
350 		su.sin6.sin6_addr = in6addr_any;
351 		su.sin6.sin6_port = htons(LDP_PORT);
352 	}
353 #endif
354 	if (bind(s, &su.sa, su.sa.sa_len)) {
355 		fatalp("bind_socket: %s\n", strerror(errno));
356 		return -1;
357 	}
358 	return 0;
359 }
360 
361 /* Create / bind the TCP socket */
362 int
363 create_listening_socket(void)
364 {
365 	struct sockaddr_in sa;
366 	int             s;
367 
368 	sa.sin_len = sizeof(sa);
369 	sa.sin_family = AF_INET;
370 	sa.sin_port = htons(LDP_PORT);
371 	sa.sin_addr.s_addr = htonl(INADDR_ANY);
372 
373 	s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
374 	if (s < 0)
375 		return s;
376 	if (bind(s, (struct sockaddr *) & sa, sizeof(sa))) {
377 		fatalp("bind: %s", strerror(errno));
378 		close(s);
379 		return -1;
380 	}
381 	if (listen(s, 10) == -1) {
382 		fatalp("listen: %s", strerror(errno));
383 		close(s);
384 		return -1;
385 	}
386 /*	if (set_tos(s) == -1) {
387 		fatalp("set_tos: %s", strerror(errno));
388 		close(s);
389 		return -1;
390 	}
391 */	return s;
392 }
393 
394 /*
395  * It's ugly. We need a function to pass all tlvs and create pdu but since I
396  * use UDP socket only to send hellos, I didn't bother
397  */
398 void
399 send_hello(void)
400 {
401 	struct hello_tlv *t;
402 	struct common_hello_tlv *cht;
403 	struct ldp_pdu  *spdu;
404 	struct transport_address_tlv *trtlv;
405 	void *v;
406 	struct sockaddr_in sadest;	/* Destination ALL_ROUTERS */
407 	ssize_t sb = 0;			/* sent bytes */
408 	struct ifaddrs *ifa, *ifb;
409 	struct sockaddr_in *if_sa;
410 	int ip4socket = -1;
411 	uint lastifindex;
412 	struct hello_socket *hs;
413 	struct conf_interface *coif;
414 	bool bad_tr_addr;
415 #ifdef INET6
416 	struct sockaddr_in6 sadest6;
417 	int ip6socket = -1;
418 #endif
419 
420 #define BASIC_HELLO_MSG_SIZE (sizeof(struct ldp_pdu) + 	/* PDU */	\
421 			TLV_TYPE_LENGTH + MSGID_SIZE +	/* Hello TLV */	\
422 			/* Common Hello TLV */				\
423 			sizeof(struct common_hello_tlv))
424 #define GENERAL_HELLO_MSG_SIZE BASIC_HELLO_MSG_SIZE + 			\
425 			/* Transport Address */				\
426 			sizeof(struct transport_address_tlv)
427 #define IPV4_HELLO_MSG_SIZE BASIC_HELLO_MSG_SIZE + 4 + sizeof(struct in_addr)
428 #define IPV6_HELLO_MSG_SIZE BASIC_HELLO_MSG_SIZE + 4 + sizeof(struct in6_addr)
429 
430 	if ((v = calloc(1, GENERAL_HELLO_MSG_SIZE)) == NULL) {
431 		fatalp("alloc problem in send_hello()\n");
432 		return;
433 	}
434 
435 	spdu = (struct ldp_pdu *)((char *)v);
436 	t = (struct hello_tlv *)(spdu + 1);
437 	cht = &t->ch;	/* Hello tlv struct includes CHT */
438 	trtlv = (struct transport_address_tlv *)(t + 1);
439 
440 	/* Prepare PDU envelope */
441 	spdu->version = htons(LDP_VERSION);
442 	spdu->length = htons(IPV4_HELLO_MSG_SIZE - PDU_VER_LENGTH);
443 	inet_aton(LDP_ID, &spdu->ldp_id);
444 
445 	/* Prepare Hello TLV */
446 	t->type = htons(LDP_HELLO);
447 	t->length = htons(MSGID_SIZE +
448 			sizeof(struct common_hello_tlv) +
449 			IPV4_HELLO_MSG_SIZE - BASIC_HELLO_MSG_SIZE);
450 	/*
451 	 * We used ID 0 instead of htonl(get_message_id()) because we've
452 	 * seen hellos from Cisco routers doing the same thing
453 	 */
454 	t->messageid = 0;
455 
456 	/* Prepare Common Hello attributes */
457 	cht->type = htons(TLV_COMMON_HELLO);
458 	cht->length = htons(sizeof(cht->holdtime) + sizeof(cht->res));
459 	cht->holdtime = htons(ldp_holddown_time);
460 	cht->res = 0;
461 
462 	/*
463 	 * Prepare Transport Address TLV RFC5036 says: "If this optional TLV
464 	 * is not present the IPv4 source address for the UDP packet carrying
465 	 * the Hello should be used." But we send it because everybody seems
466 	 * to do so
467 	 */
468 	trtlv->type = htons(TLV_IPV4_TRANSPORT);
469 	trtlv->length = htons(sizeof(struct in_addr));
470 	/* trtlv->address will be set for each socket */
471 
472 	/* Destination sockaddr */
473 	memset(&sadest, 0, sizeof(sadest));
474 	sadest.sin_len = sizeof(sadest);
475 	sadest.sin_family = AF_INET;
476 	sadest.sin_port = htons(LDP_PORT);
477 	sadest.sin_addr.s_addr = htonl(INADDR_ALLRTRS_GROUP);
478 
479 	/* Find our socket */
480 	SLIST_FOREACH(hs, &hello_socket_head, listentry)
481 		if (hs->type == AF_INET) {
482 			ip4socket = hs->socket;
483 			break;
484 		}
485 	assert(ip4socket >= 0);
486 
487 	if (getifaddrs(&ifa) == -1) {
488 		free(v);
489 		fatalp("Cannot enumerate interfaces\n");
490 		return;
491 	}
492 
493 	lastifindex = UINT_MAX;
494 	/* Loop all interfaces in order to send IPv4 hellos */
495 	for (ifb = ifa; ifb; ifb = ifb->ifa_next) {
496 		if_sa = (struct sockaddr_in *) ifb->ifa_addr;
497 		if (if_sa->sin_family != AF_INET ||
498 		    (!(ifb->ifa_flags & IFF_UP)) ||
499 		    (ifb->ifa_flags & IFF_LOOPBACK) ||
500 		    (!(ifb->ifa_flags & IFF_MULTICAST)) ||
501 		    is_passive_if(ifb->ifa_name) ||
502 		    (ntohl(if_sa->sin_addr.s_addr) >> 24 == IN_LOOPBACKNET) ||
503 		    lastifindex == if_nametoindex(ifb->ifa_name))
504 			continue;
505 
506 		/* Send only once per interface, using primary address */
507 		if (lastifindex == if_nametoindex(ifb->ifa_name))
508 			continue;
509 		/* Check if there is transport address set for this interface */
510 		bad_tr_addr = false;
511 		SLIST_FOREACH(coif, &coifs_head, iflist)
512 			if (strncasecmp(coif->if_name, ifb->ifa_name,
513 			    IF_NAMESIZE) == 0 &&
514 			    coif->tr_addr.s_addr != 0 &&
515 			    coif->tr_addr.s_addr != if_sa->sin_addr.s_addr)
516 				bad_tr_addr = true;
517 		if (bad_tr_addr == true)
518 			continue;
519 		lastifindex = if_nametoindex(ifb->ifa_name);
520 
521 		if (setsockopt(ip4socket, IPPROTO_IP, IP_MULTICAST_IF,
522 		    &if_sa->sin_addr, sizeof(struct in_addr)) == -1) {
523 			warnp("setsockopt failed: %s\n", strerror(errno));
524 			continue;
525 		}
526 		trtlv->address.ip4addr.s_addr = if_sa->sin_addr.s_addr;
527 
528 		/* Put it on the wire */
529 		sb = sendto(ip4socket, v, IPV4_HELLO_MSG_SIZE, 0,
530 			    (struct sockaddr *) & sadest, sizeof(sadest));
531 		if (sb < (ssize_t)(IPV4_HELLO_MSG_SIZE))
532 		    fatalp("send: %s", strerror(errno));
533 		else
534 		    debugp("Sent (IPv4) %zd bytes on %s"
535 			" (PDU: %d, Hello TLV: %d, CH: %d, TR: %d)\n",
536 			sb, ifb->ifa_name,
537 			ntohs(spdu->length), ntohs(t->length),
538 			ntohs(cht->length), ntohs(trtlv->length));
539 	}
540 #ifdef INET6
541 	/* Adjust lengths */
542 	spdu->length = htons(IPV6_HELLO_MSG_SIZE - PDU_VER_LENGTH);
543 	t->length = htons(MSGID_SIZE +
544 			sizeof(struct common_hello_tlv) +
545 			IPV6_HELLO_MSG_SIZE - BASIC_HELLO_MSG_SIZE);
546 	trtlv->length = htons(sizeof(struct in6_addr));
547 	trtlv->type = htons(TLV_IPV6_TRANSPORT);
548 
549 	/* Prepare destination sockaddr */
550 	memset(&sadest6, 0, sizeof(sadest6));
551 	sadest6.sin6_len = sizeof(sadest6);
552 	sadest6.sin6_family = AF_INET6;
553 	sadest6.sin6_port = htons(LDP_PORT);
554 	sadest6.sin6_addr = in6addr_linklocal_allrouters;
555 
556 	SLIST_FOREACH(hs, &hello_socket_head, listentry)
557 		if (hs->type == AF_INET6) {
558 			ip6socket = hs->socket;
559 			break;
560 		}
561 
562 	lastifindex = UINT_MAX;
563 	for (ifb = ifa; ifb; ifb = ifb->ifa_next) {
564 		struct sockaddr_in6 * if_sa6 =
565 		    (struct sockaddr_in6 *) ifb->ifa_addr;
566 		if (if_sa6->sin6_family != AF_INET6 ||
567 		    (!(ifb->ifa_flags & IFF_UP)) ||
568 		    (!(ifb->ifa_flags & IFF_MULTICAST)) ||
569 		    (ifb->ifa_flags & IFF_LOOPBACK) ||
570 		    is_passive_if(ifb->ifa_name) ||
571 		    IN6_IS_ADDR_LOOPBACK(&if_sa6->sin6_addr))
572 			continue;
573 		/*
574 		 * draft-ietf-mpls-ldp-ipv6-07 Section 5.1:
575 		 * Additionally, the link-local
576 		 * IPv6 address MUST be used as the source IP address in IPv6
577 		 * LDP Link Hellos.
578 		 */
579 		if (IN6_IS_ADDR_LINKLOCAL(&if_sa6->sin6_addr) == 0)
580 			continue;
581 		/* We should have only one LLADDR per interface, but... */
582 		if (lastifindex == if_nametoindex(ifb->ifa_name))
583 			continue;
584 		lastifindex = if_nametoindex(ifb->ifa_name);
585 
586 		if (setsockopt(ip6socket, IPPROTO_IPV6, IPV6_MULTICAST_IF,
587 		    &lastifindex, sizeof(int)) == -1) {
588 			fatalp("ssopt6 IPV6_MULTICAST_IF failed: %s for %s\n",
589 			    strerror(errno), ifb->ifa_name);
590 			continue;
591 		}
592 
593 		memcpy(&trtlv->address.ip6addr, &if_sa6->sin6_addr,
594 		    sizeof(struct in6_addr));
595 
596 		/* Put it on the wire */
597 		sb = sendto(ip6socket, v, IPV6_HELLO_MSG_SIZE,
598 			    0, (struct sockaddr *)&sadest6, sizeof(sadest6));
599 		if (sb < (ssize_t)(IPV6_HELLO_MSG_SIZE))
600 		    fatalp("send6: %s", strerror(errno));
601 		else
602 		    debugp("Sent (IPv6) %zd bytes on %s "
603 			"(PDU: %d, Hello TLV: %d, CH: %d TR: %d)\n",
604 			sb, ifb->ifa_name, htons(spdu->length),
605 			htons(t->length), htons(cht->length),
606 			htons(trtlv->length));
607 	}
608 #endif
609 	freeifaddrs(ifa);
610 	free(v);
611 }
612 
613 int
614 get_message_id(void)
615 {
616 	current_msg_id++;
617 	return current_msg_id;
618 }
619 
620 static int
621 get_local_addr(struct sockaddr_dl *sdl, struct in_addr *sin)
622 {
623 	struct ifaddrs *ifa, *ifb;
624 	struct sockaddr_in *sinet;
625 
626 	if (sdl == NULL)
627 		return -1;
628 
629 	if (getifaddrs(&ifa) == -1)
630 		return -1;
631 	for (ifb = ifa; ifb; ifb = ifb->ifa_next)
632 		if (ifb->ifa_addr->sa_family == AF_INET) {
633 			if (if_nametoindex(ifb->ifa_name) != sdl->sdl_index)
634 				continue;
635 			sinet = (struct sockaddr_in*) ifb->ifa_addr;
636 			sin->s_addr = sinet->sin_addr.s_addr;
637 			freeifaddrs(ifa);
638 			return 0;
639 		}
640 	freeifaddrs(ifa);
641 	return -1;
642 }
643 
644 /* Receive PDUs on Multicast UDP socket */
645 void
646 recv_pdu(int sock)
647 {
648 	struct ldp_pdu  rpdu;
649 	int             c, i;
650 	struct msghdr msg;
651 	struct iovec iov[1];
652 	unsigned char recvspace[MAX_PDU_SIZE];
653 	struct hello_tlv *t;
654 	union sockunion sender;
655 	struct sockaddr_dl *sdl = NULL;
656 	struct in_addr my_ldp_addr, local_addr;
657 	struct cmsghdr *cmptr;
658 	union {
659 		struct cmsghdr cm;
660 		char control[1024];
661 	} control_un;
662 
663 	memset(&msg, 0, sizeof(msg));
664 	msg.msg_control = control_un.control;
665 	msg.msg_controllen = sizeof(control_un.control);
666 	msg.msg_flags = 0;
667 	msg.msg_name = &sender;
668 	msg.msg_namelen = sizeof(sender);
669 	iov[0].iov_base = recvspace;
670 	iov[0].iov_len = sizeof(recvspace);
671 	msg.msg_iov = iov;
672 	msg.msg_iovlen = 1;
673 
674 	c = recvmsg(sock, &msg, MSG_WAITALL);
675 
676 	/* Check to see if this is larger than MIN_PDU_SIZE */
677 	if (c < MIN_PDU_SIZE)
678 		return;
679 
680 	/* Read the PDU */
681 	i = get_pdu(recvspace, &rpdu);
682 
683 	debugp("recv_pdu(%d): PDU(size: %d) from: %s\n", sock,
684 	    c, satos(&sender.sa));
685 
686 	/* We currently understand Version 1 */
687 	if (rpdu.version != LDP_VERSION) {
688 		warnp("recv_pdu: Version mismatch\n");
689 		return;
690 	}
691 
692 	/* Check if it's our hello */
693 	inet_aton(LDP_ID, &my_ldp_addr);
694 	if (rpdu.ldp_id.s_addr == my_ldp_addr.s_addr) {
695 		/* It should not be looped. We set MULTICAST_LOOP 0 */
696 		fatalp("Received our PDU. Ignoring it\n");
697 		return;
698 	}
699 
700 	if (msg.msg_controllen < (socklen_t)sizeof(struct cmsghdr) ||
701 	    (msg.msg_flags & MSG_CTRUNC))
702 		local_addr.s_addr = my_ldp_addr.s_addr;
703 	else {
704 		for (cmptr = CMSG_FIRSTHDR(&msg); cmptr != NULL;
705 		    cmptr = CMSG_NXTHDR(&msg, cmptr))
706 			if (cmptr->cmsg_level == IPPROTO_IP &&
707 			    cmptr->cmsg_type == IP_RECVIF) {
708 				sdl = (struct sockaddr_dl *) CMSG_DATA(cmptr);
709 				break;
710 			}
711 		if (get_local_addr(sdl, &local_addr) != 0)
712 			local_addr.s_addr = my_ldp_addr.s_addr;
713 	}
714 
715 
716 	debugp("Read %d bytes from address %s Length: %.4d Version: %d\n",
717 	       c, inet_ntoa(rpdu.ldp_id), rpdu.length, rpdu.version);
718 
719 	/* Fill the TLV messages */
720 	t = get_hello_tlv(recvspace + i, c - i);
721 	run_ldp_hello(&rpdu, t, &sender.sa, &local_addr, sock, may_connect);
722 }
723 
724 void
725 send_hello_alarm(int unused)
726 {
727 	struct ldp_peer *p, *ptmp;
728 	struct hello_info *hi, *hinext;
729 	time_t          t = time(NULL);
730 	int             olderrno = errno;
731 
732 	if (may_connect == false)
733 		may_connect = true;
734 	/* Send hellos */
735 	if (!(t % ldp_hello_time))
736 		send_hello();
737 
738 	/* Timeout -- */
739 	SLIST_FOREACH(p, &ldp_peer_head, peers)
740 		p->timeout--;
741 
742 	/* Check for timeout */
743 	SLIST_FOREACH_SAFE(p, &ldp_peer_head, peers, ptmp)
744 		if (p->timeout < 1)
745 			switch (p->state) {
746 			case LDP_PEER_HOLDDOWN:
747 				debugp("LDP holddown expired for peer %s\n",
748 				       inet_ntoa(p->ldp_id));
749 				ldp_peer_delete(p);
750 				break;
751 			case LDP_PEER_ESTABLISHED:
752 			case LDP_PEER_CONNECTED:
753 				send_notification(p, 0,
754 				    NOTIF_FATAL|NOTIF_KEEP_ALIVE_TIMER_EXPIRED);
755 				warnp("Keepalive expired for %s\n",
756 				    inet_ntoa(p->ldp_id));
757 				ldp_peer_holddown(p);
758 				break;
759 			}	/* switch */
760 
761 	/* send keepalives */
762 	if (!(t % ldp_keepalive_time)) {
763 		SLIST_FOREACH(p, &ldp_peer_head, peers)
764 		    if (p->state == LDP_PEER_ESTABLISHED) {
765 			debugp("Sending KeepAlive to %s\n",
766 			    inet_ntoa(p->ldp_id));
767 			keep_alive(p);
768 		    }
769 	}
770 
771 	/* Decrement and Check hello keepalives */
772 	SLIST_FOREACH_SAFE(hi, &hello_info_head, infos, hinext) {
773 		if (hi->keepalive != 0xFFFF)
774 			hi->keepalive--;
775 		if (hi->keepalive < 1)
776 			SLIST_REMOVE(&hello_info_head, hi, hello_info, infos);
777 	}
778 
779 	/* Set the alarm again and bail out */
780 	alarm(1);
781 	errno = olderrno;
782 }
783 
784 static void
785 bail_out(int x)
786 {
787 	ldp_peer_holddown_all();
788 	flush_mpls_routes();
789 	exit(0);
790 }
791 
792 static void
793 print_info(int x)
794 {
795 	printf("Info for %s\n-------\n", LDP_ID);
796 	printf("Neighbours:\n");
797 	show_neighbours(1, NULL);
798 	printf("Bindings:\n");
799 	show_bindings(1, NULL);
800 	printf("Labels:\n");
801 	show_labels(1, NULL);
802 	printf("--------\n");
803 }
804 
805 /*
806  * The big poll that catches every single event
807  * on every socket.
808  */
809 int
810 the_big_loop(void)
811 {
812 	int		sock_error;
813 	uint32_t	i;
814 	socklen_t       sock_error_size = sizeof(int);
815 	struct ldp_peer *p;
816 	struct com_sock	*cs;
817 	struct pollfd	pfd[MAX_POLL_FDS];
818 	struct hello_socket *hs;
819 	nfds_t pollsum;
820 #ifdef RO_MSGFILTER
821 	unsigned char msgfilter[] = {
822 		RTM_NEWADDR, RTM_DELADDR,
823 		RTM_ADD, RTM_DELETE, RTM_CHANGE,
824 	};
825 #endif
826 
827 	assert(MAX_POLL_FDS > 5);
828 
829 	SLIST_INIT(&hello_info_head);
830 
831 	signal(SIGALRM, send_hello_alarm);
832 	signal(SIGPIPE, SIG_IGN);
833 	signal(SIGINT, bail_out);
834 	signal(SIGTERM, bail_out);
835 	signal(SIGINFO, print_info);
836 
837 	/* Send first hellos in 5 seconds. Avoid No hello notifications */
838 	may_connect = false;
839 	alarm(5);
840 
841 	route_socket = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
842 	setsockopt(route_socket, SOL_SOCKET, SO_USELOOPBACK, &(int){0},
843 		sizeof(int));
844 #ifdef RO_MSGFILTER
845 	setsockopt(route_socket, PF_ROUTE, RO_MSGFILTER, &msgfilter,
846 		sizeof(msgfilter));
847 #endif
848 
849 	sock_error = bind_current_routes();
850 	if (sock_error != LDP_E_OK) {
851 		fatalp("Cannot get current routes\n");
852 		return sock_error;
853 	}
854 
855 	for (;;) {
856 		pfd[0].fd = ls;
857 		pfd[0].events = POLLRDNORM;
858 		pfd[0].revents = 0;
859 
860 		pfd[1].fd = route_socket;
861 		pfd[1].events = POLLRDNORM;
862 		pfd[1].revents = 0;
863 
864 		pfd[2].fd = command_socket;
865 		pfd[2].events = POLLRDNORM;
866 		pfd[2].revents = 0;
867 
868 		/* Hello sockets */
869 		pollsum = 3;
870 		SLIST_FOREACH(hs, &hello_socket_head, listentry) {
871 			pfd[pollsum].fd = hs->socket;
872 			pfd[pollsum].events = POLLIN;
873 			pfd[pollsum].revents = 0;
874 			pollsum++;
875 		}
876 
877 		/* Command sockets */
878 		for (i=0; i < MAX_COMMAND_SOCKETS; i++)
879 			if (csockets[i].socket != -1) {
880 				if (pollsum >= MAX_POLL_FDS)
881 					break;
882 				pfd[pollsum].fd = csockets[i].socket;
883 				pfd[pollsum].events = POLLIN;
884 				pfd[pollsum].revents = 0;
885 				pollsum++;
886 			}
887 
888 		/* LDP Peer sockets */
889 		SLIST_FOREACH(p, &ldp_peer_head, peers) {
890 			if (p->socket < 1)
891 				continue;
892 			switch (p->state) {
893 			    case LDP_PEER_CONNECTED:
894 			    case LDP_PEER_ESTABLISHED:
895 				if (pollsum >= MAX_POLL_FDS)
896 					break;
897 				pfd[pollsum].fd = p->socket;
898 				pfd[pollsum].events = POLLRDNORM;
899 				pfd[pollsum].revents = 0;
900 				pollsum++;
901 				break;
902 			    case LDP_PEER_CONNECTING:
903 				if (pollsum >= MAX_POLL_FDS)
904 					break;
905 				pfd[pollsum].fd = p->socket;
906 				pfd[pollsum].events = POLLWRNORM;
907 				pfd[pollsum].revents = 0;
908 				pollsum++;
909 				break;
910 			}
911 		}
912 
913 		if (pollsum >= MAX_POLL_FDS) {
914 			fatalp("Too many sockets. Increase MAX_POLL_FDS\n");
915 			return LDP_E_TOO_MANY_FDS;
916 		}
917 		if (poll(pfd, pollsum, INFTIM) < 0) {
918 			if (errno != EINTR)
919 				fatalp("poll: %s", strerror(errno));
920 			continue;
921 		}
922 
923 		for (i = 0; i < pollsum; i++) {
924 			if ((pfd[i].revents & POLLRDNORM) ||
925 			    (pfd[i].revents & POLLIN)) {
926 				if(pfd[i].fd == ls)
927 					new_peer_connection();
928 				else if (pfd[i].fd == route_socket) {
929 					struct rt_msg xbuf;
930 					int l, rtmlen = sizeof(xbuf);
931 					/* Read at least rtm_msglen */
932 					l = recv(route_socket, &xbuf,
933 					  sizeof(u_short), MSG_PEEK);
934 					if (l == sizeof(u_short))
935 						rtmlen = xbuf.m_rtm.rtm_msglen;
936 					do {
937 						l = recv(route_socket, &xbuf,
938 						    rtmlen, MSG_WAITALL);
939 					} while ((l == -1) && (errno == EINTR));
940 
941 					if (l == -1)
942 						break;
943 
944 					check_route(&xbuf, l);
945 
946 				} else if (is_hello_socket(pfd[i].fd) == 1) {
947 					/* Receiving hello socket */
948 					recv_pdu(pfd[i].fd);
949 				} else if (pfd[i].fd == command_socket) {
950 					command_accept(command_socket);
951 				} else if ((cs = is_command_socket(pfd[i].fd))
952 						!= NULL) {
953 					command_dispatch(cs);
954 				} else {
955 					/* ldp peer socket */
956 					p = get_ldp_peer_by_socket(pfd[i].fd);
957 					if (p)
958 						recv_session_pdu(p);
959 				}
960 			} else if(pfd[i].revents & POLLWRNORM) {
961 				p = get_ldp_peer_by_socket(pfd[i].fd);
962 				if (!p)
963 					continue;
964 				assert(p->state == LDP_PEER_CONNECTING);
965 				if (getsockopt(pfd[i].fd, SOL_SOCKET, SO_ERROR,
966 				    &sock_error, &sock_error_size) != 0 ||
967 				    sock_error != 0) {
968 					ldp_peer_holddown(p);
969 					sock_error = 0;
970 				} else {
971 					p->state = LDP_PEER_CONNECTED;
972 					send_initialize(p);
973 				}
974 			}
975 		}
976 
977 		for (int ri = 0; ri < replay_index; ri++) {
978 			debugp("Replaying: PID %d, SEQ %d\n",
979 				replay_rt[ri].m_rtm.rtm_pid,
980 				replay_rt[ri].m_rtm.rtm_seq);
981 			check_route(&replay_rt[ri], sizeof(struct rt_msg));
982                 }
983 		replay_index = 0;
984 	}	/* for (;;) */
985 }
986 
987 void
988 new_peer_connection()
989 {
990 	union sockunion peer_address, my_address;
991 	struct in_addr *peer_ldp_id = NULL;
992 	struct hello_info *hi;
993 	int s;
994 
995 	s = accept(ls, &peer_address.sa,
996 		& (socklen_t) { sizeof(union sockunion) } );
997 	if (s < 0) {
998 		fatalp("accept: %s", strerror(errno));
999 		return;
1000 	}
1001 
1002 	if (getsockname(s, &my_address.sa,
1003 	    & (socklen_t) { sizeof(union sockunion) } )) {
1004 		fatalp("new_peer_connection(): cannot getsockname\n");
1005 		close(s);
1006 		return;
1007 	}
1008 
1009 	if (peer_address.sa.sa_family == AF_INET)
1010 		peer_address.sin.sin_port = 0;
1011 	else if (peer_address.sa.sa_family == AF_INET6)
1012 		peer_address.sin6.sin6_port = 0;
1013 	else {
1014 		fatalp("Unknown peer address family\n");
1015 		close(s);
1016 		return;
1017 	}
1018 
1019 	/* Already peered or in holddown ? */
1020 	if (get_ldp_peer(&peer_address.sa) != NULL) {
1021 		close(s);
1022 		return;
1023 	}
1024 
1025 	warnp("Accepted a connection from %s\n", satos(&peer_address.sa));
1026 
1027 	/* Verify if it should connect - XXX: no check for INET6 */
1028 	if (peer_address.sa.sa_family == AF_INET &&
1029 	    ntohl(peer_address.sin.sin_addr.s_addr) <
1030 	    ntohl(my_address.sin.sin_addr.s_addr)) {
1031 		fatalp("Peer %s: connect from lower ID\n",
1032 		    satos(&peer_address.sa));
1033 		close(s);
1034 		return;
1035 	}
1036 
1037 	/* Match hello info in order to get ldp_id */
1038 	SLIST_FOREACH(hi, &hello_info_head, infos) {
1039 		if (sockaddr_cmp(&peer_address.sa,
1040 		    &hi->transport_address.sa) == 0) {
1041 			peer_ldp_id = &hi->ldp_id;
1042 			break;
1043 		}
1044 	}
1045 	if (peer_ldp_id == NULL) {
1046 		warnp("Got connection from %s, but no hello info exists\n",
1047 		    satos(&peer_address.sa));
1048 		close(s);
1049 		return;
1050 	} else
1051 		ldp_peer_new(peer_ldp_id, &peer_address.sa, NULL,
1052 		    ldp_holddown_time, s);
1053 
1054 }
1055 
1056 void
1057 send_initialize(const struct ldp_peer * p)
1058 {
1059 	struct init_tlv ti;
1060 
1061 	ti.type = htons(LDP_INITIALIZE);
1062 	ti.length = htons(sizeof(struct init_tlv) - TLV_TYPE_LENGTH);
1063 	ti.messageid = htonl(get_message_id());
1064 	ti.cs_type = htons(TLV_COMMON_SESSION);
1065 	ti.cs_len = htons(CS_LEN);
1066 	ti.cs_version = htons(LDP_VERSION);
1067 	ti.cs_keepalive = htons(2 * ldp_keepalive_time);
1068 	ti.cs_adpvlim = 0;
1069 	ti.cs_maxpdulen = htons(MAX_PDU_SIZE);
1070 	ti.cs_peeraddress.s_addr = p->ldp_id.s_addr;
1071 	ti.cs_peeraddrspace = 0;
1072 
1073 	send_tlv(p, (struct tlv *) (void *) &ti);
1074 }
1075 
1076 void
1077 keep_alive(const struct ldp_peer * p)
1078 {
1079 	struct ka_tlv   kt;
1080 
1081 	kt.type = htons(LDP_KEEPALIVE);
1082 	kt.length = htons(sizeof(kt.messageid));
1083 	kt.messageid = htonl(get_message_id());
1084 
1085 	send_tlv(p, (struct tlv *) (void *) &kt);
1086 }
1087 
1088 /*
1089  * Process a message received from a peer
1090  */
1091 void
1092 recv_session_pdu(struct ldp_peer * p)
1093 {
1094 	struct ldp_pdu *rpdu;
1095 	struct address_tlv *atlv;
1096 	struct al_tlv  *altlv;
1097 	struct init_tlv	*itlv;
1098 	struct label_map_tlv *lmtlv;
1099 	struct fec_tlv *fectlv;
1100 	struct label_tlv *labeltlv;
1101 	struct notification_tlv *nottlv;
1102 	struct hello_info *hi;
1103 
1104 	int             c;
1105 	int32_t         wo = 0;
1106 	struct tlv     *ttmp;
1107 	unsigned char   recvspace[MAX_PDU_SIZE];
1108 
1109 	memset(recvspace, 0, MAX_PDU_SIZE);
1110 
1111 	do {
1112 		c = recv(p->socket, (void *) recvspace, MAX_PDU_SIZE, MSG_PEEK);
1113 	} while (c == -1 && errno == EINTR);
1114 
1115 	debugp("Ready to read %d bytes\n", c);
1116 
1117 	if (c < 1) {		/* Session closed */
1118 		warnp("Error in connection with %s\n", inet_ntoa(p->ldp_id));
1119 		ldp_peer_holddown(p);
1120 		return;
1121 	}
1122 	if (c > MAX_PDU_SIZE) {
1123 		debugp("Incoming PDU size exceeds MAX_PDU_SIZE !\n");
1124 		return;
1125 	}
1126 	if (c < MIN_PDU_SIZE) {
1127 		debugp("PDU too small received from peer %s\n",
1128 		    inet_ntoa(p->ldp_id));
1129 		return;
1130 	}
1131 	rpdu = (struct ldp_pdu *) recvspace;
1132 	do {
1133 		c = recv(p->socket, (void *) recvspace,
1134 		    ntohs(rpdu->length) + PDU_VER_LENGTH, MSG_WAITALL);
1135 	} while (c == -1 && errno == EINTR);
1136 
1137 	/* sanity check */
1138 	if (check_recv_pdu(p, rpdu, c) != 0)
1139 		return;
1140 
1141 	debugp("Read %d bytes, PDU size: %d bytes\n", c, ntohs(rpdu->length));
1142 	wo = sizeof(struct ldp_pdu);
1143 
1144 	while (wo + TLV_TYPE_LENGTH < (uint)c) {
1145 
1146 		ttmp = (struct tlv *) (&recvspace[wo]);
1147 
1148 		if ((ntohs(ttmp->type) != LDP_KEEPALIVE) &&
1149 		    (ntohs(ttmp->type) != LDP_LABEL_MAPPING)) {
1150 			debugp("Got Type: 0x%.4X (Length: %d) from %s\n",
1151 			    ntohs(ttmp->type), ntohs(ttmp->length),
1152 			    inet_ntoa(p->ldp_id));
1153 		} else
1154 			debugp("Got Type: 0x%.4X (Length: %d) from %s\n",
1155 			    ntohs(ttmp->type), ntohs(ttmp->length),
1156 			    inet_ntoa(p->ldp_id));
1157 
1158 		/* Should we get the message ? */
1159 		if (p->state != LDP_PEER_ESTABLISHED &&
1160 		    ntohs(ttmp->type) != LDP_INITIALIZE &&
1161 		    ntohs(ttmp->type) != LDP_KEEPALIVE &&
1162 		    ntohs(ttmp->type) != LDP_NOTIFICATION)
1163 			break;
1164 		/* The big switch */
1165 		switch (ntohs(ttmp->type)) {
1166 		case LDP_INITIALIZE:
1167 			itlv = (struct init_tlv *)ttmp;
1168 			/* Check size */
1169 			if (ntohs(itlv->length) <
1170 			    sizeof(struct init_tlv) - TLV_TYPE_LENGTH) {
1171 				debugp("Bad size\n");
1172 				send_notification(p, 0,
1173 				    NOTIF_BAD_PDU_LEN | NOTIF_FATAL);
1174 				ldp_peer_holddown(p);
1175 				break;
1176 			}
1177 			/* Check version */
1178 			if (ntohs(itlv->cs_version) != LDP_VERSION) {
1179 				debugp("Bad version");
1180 				send_notification(p, ntohl(itlv->messageid),
1181 					NOTIF_BAD_LDP_VER | NOTIF_FATAL);
1182 				ldp_peer_holddown(p);
1183 				break;
1184 			}
1185 			/* Check if we got any hello from this one */
1186 			SLIST_FOREACH(hi, &hello_info_head, infos)
1187 				if (hi->ldp_id.s_addr == rpdu->ldp_id.s_addr)
1188 					break;
1189 			if (hi == NULL) {
1190 			    debugp("No hello. Moving peer to holddown\n");
1191 			    send_notification(p, ntohl(itlv->messageid),
1192 				NOTIF_SESSION_REJECTED_NO_HELLO | NOTIF_FATAL);
1193 			    ldp_peer_holddown(p);
1194 			    break;
1195 			}
1196 
1197 			if (!p->master) {
1198 				send_initialize(p);
1199 				keep_alive(p);
1200 			} else {
1201 				p->state = LDP_PEER_ESTABLISHED;
1202 				p->established_t = time(NULL);
1203 				keep_alive(p);
1204 
1205 				/*
1206 				 * Recheck here ldp id because we accepted
1207 				 * connection without knowing who is it for sure
1208 				 */
1209 				p->ldp_id.s_addr = rpdu->ldp_id.s_addr;
1210 
1211 				fatalp("LDP neighbour %s is UP\n",
1212 				    inet_ntoa(p->ldp_id));
1213 				mpls_add_ldp_peer(p);
1214 				send_addresses(p);
1215 				send_all_bindings(p);
1216 			}
1217 			break;
1218 		case LDP_KEEPALIVE:
1219 			if ((p->state == LDP_PEER_CONNECTED) && (!p->master)) {
1220 				p->state = LDP_PEER_ESTABLISHED;
1221 				p->established_t = time(NULL);
1222 				fatalp("LDP neighbour %s is UP\n",
1223 				    inet_ntoa(p->ldp_id));
1224 				mpls_add_ldp_peer(p);
1225 				send_addresses(p);
1226 				send_all_bindings(p);
1227 			}
1228 			p->timeout = p->holdtime;
1229 			break;
1230 		case LDP_ADDRESS:
1231 			/* Add peer addresses */
1232 			atlv = (struct address_tlv *) ttmp;
1233 			altlv = (struct al_tlv *) (&atlv[1]);
1234 			add_ifaddresses(p, altlv);
1235 			/*
1236 			 * try to see if we have labels with null peer that
1237 			 * would match the new peer
1238 			 */
1239 			label_check_assoc(p);
1240 			print_bounded_addresses(p);
1241 			break;
1242 		case LDP_ADDRESS_WITHDRAW:
1243 			atlv = (struct address_tlv *) ttmp;
1244 			altlv = (struct al_tlv *) (&atlv[1]);
1245 			del_ifaddresses(p, altlv);
1246 			break;
1247 		case LDP_LABEL_MAPPING:
1248 			lmtlv = (struct label_map_tlv *) ttmp;
1249 			fectlv = (struct fec_tlv *) (&lmtlv[1]);
1250 			labeltlv = (struct label_tlv *)((unsigned char *)fectlv
1251 				+ ntohs(fectlv->length) + TLV_TYPE_LENGTH);
1252 			map_label(p, fectlv, labeltlv);
1253 			break;
1254 		case LDP_LABEL_REQUEST:
1255 			lmtlv = (struct label_map_tlv *) ttmp;
1256 			fectlv = (struct fec_tlv *) (&lmtlv[1]);
1257 			switch (request_respond(p, lmtlv, fectlv)) {
1258 			case LDP_E_BAD_FEC:
1259 				send_notification(p, ntohl(lmtlv->messageid),
1260 					NOTIF_UNKNOWN_TLV);
1261 				break;
1262 			case LDP_E_BAD_AF:
1263 				send_notification(p, ntohl(lmtlv->messageid),
1264 					NOTIF_UNSUPPORTED_AF);
1265 				break;
1266 			case LDP_E_NO_SUCH_ROUTE:
1267 				send_notification(p, ntohl(lmtlv->messageid),
1268 					NOTIF_NO_ROUTE);
1269 				break;
1270 			}
1271 			break;
1272 		case LDP_LABEL_WITHDRAW:
1273 			lmtlv = (struct label_map_tlv *) ttmp;
1274 			fectlv = (struct fec_tlv *) (&lmtlv[1]);
1275 			if (withdraw_label(p, fectlv) == LDP_E_OK) {
1276 				/* Send RELEASE */
1277 				prepare_release(ttmp);
1278 				send_tlv(p, ttmp);
1279 				}
1280 			break;
1281 		case LDP_LABEL_RELEASE:
1282 			/*
1283 			 * XXX: we need to make a timed queue...
1284 			 * For now I just assume peers are processing messages
1285 			 * correctly so I just ignore confirmations
1286 			 */
1287 			wo = -1;	/* Ignore rest of message */
1288 			break;
1289 		case LDP_LABEL_ABORT:
1290 		/* XXX: For now I pretend I can process everything
1291 		 * RFC 5036, Section 3.5.9.1
1292 		 * If an LSR receives a Label Abort Request Message after it
1293 		 * has responded to the Label Request in question with a Label
1294 		 * Mapping message or a Notification message, it ignores the
1295 		 * abort request.
1296 		 */
1297 			wo = -1;
1298 			break;
1299 		case LDP_NOTIFICATION:
1300 			nottlv = (struct notification_tlv *) ttmp;
1301 			nottlv->st_code = ntohl(nottlv->st_code);
1302 			fatalp("Got notification 0x%X from peer %s\n",
1303 			    nottlv->st_code, inet_ntoa(p->ldp_id));
1304 			if (nottlv->st_code >> 31) {
1305 				fatalp("LDP peer %s signalized %s\n",
1306 				    inet_ntoa(p->ldp_id),
1307 				    NOTIF_STR[(nottlv->st_code << 1) >> 1]);
1308 				ldp_peer_holddown(p);
1309 				wo = -1;
1310 			}
1311 			break;
1312 		case LDP_HELLO:
1313 			/* No hellos should came on tcp session */
1314 			wo = -1;
1315 			break;
1316 		default:
1317 			warnp("Unknown TLV received from %s\n",
1318 			    inet_ntoa(p->ldp_id));
1319 			debug_tlv(ttmp);
1320 			wo = -1;/* discard the rest of the message */
1321 			break;
1322 		}
1323 		if (wo < 0) {
1324 			debugp("Discarding the rest of the message\n");
1325 			break;
1326 		} else {
1327 			wo += ntohs(ttmp->length) + TLV_TYPE_LENGTH;
1328 			debugp("WORKED ON %u bytes (Left %d)\n", wo, c - wo);
1329 		}
1330 	}			/* while */
1331 
1332 }
1333 
1334 /* Sends a pdu, tlv pair to a connected peer */
1335 int
1336 send_message(const struct ldp_peer * p, const struct ldp_pdu * pdu,
1337 	const struct tlv * t)
1338 {
1339 	unsigned char   sendspace[MAX_PDU_SIZE];
1340 
1341 	/* Check if peer is connected */
1342 	switch (p->state) {
1343 	case LDP_PEER_CONNECTED:
1344 	case LDP_PEER_ESTABLISHED:
1345 		break;
1346 	default:
1347 		return -1;
1348 	}
1349 
1350 	/* Check length validity first */
1351 	if (ntohs(pdu->length) !=
1352 	    ntohs(t->length) + TLV_TYPE_LENGTH + PDU_PAYLOAD_LENGTH) {
1353 		fatalp("LDP: TLV - PDU incompability. Message discarded\n");
1354 		fatalp("LDP: TLV len %d - PDU len %d\n", ntohs(t->length),
1355 		    ntohs(pdu->length));
1356 		return -1;
1357 	}
1358 	if (ntohs(t->length) + PDU_VER_LENGTH > MAX_PDU_SIZE) {
1359 		fatalp("Message to large discarded\n");
1360 		return -1;
1361 	}
1362 	/* Arrange them in a buffer and send */
1363 	memcpy(sendspace, pdu, sizeof(struct ldp_pdu));
1364 	memcpy(sendspace + sizeof(struct ldp_pdu), t,
1365 	    ntohs(t->length) + TLV_TYPE_LENGTH);
1366 
1367 	/* Report keepalives only for DEBUG */
1368 	if ((ntohs(t->type) != 0x201) && (ntohs(t->type) != 0x400)) {
1369 		debugp("Sending message type 0x%.4X to %s (size: %d)\n",
1370 		    ntohs(t->type), inet_ntoa(p->ldp_id), ntohs(t->length));
1371 	} else
1372 	/* downgraded from warnp to debugp for now */
1373 		debugp("Sending message type 0x%.4X to %s (size: %d)\n",
1374 		    ntohs(t->type), inet_ntoa(p->ldp_id), ntohs(t->length));
1375 
1376 	/* Send it finally */
1377 	return send(p->socket, sendspace,
1378 		ntohs(pdu->length) + PDU_VER_LENGTH, 0);
1379 }
1380 
1381 /*
1382  * Encapsulates TLV into a PDU and sends it to a peer
1383  */
1384 int
1385 send_tlv(const struct ldp_peer * p, const struct tlv * t)
1386 {
1387 	struct ldp_pdu  pdu;
1388 
1389 	pdu.version = htons(LDP_VERSION);
1390 	inet_aton(LDP_ID, &pdu.ldp_id);
1391 	pdu.label_space = 0;
1392 	pdu.length = htons(ntohs(t->length) + TLV_TYPE_LENGTH +
1393 		PDU_PAYLOAD_LENGTH);
1394 
1395 	return send_message(p, &pdu, t);
1396 }
1397 
1398 
1399 int
1400 send_addresses(const struct ldp_peer * p)
1401 {
1402 	struct address_list_tlv *t;
1403 	int             ret;
1404 
1405 	t = build_address_list_tlv();
1406 
1407 	ret = send_tlv(p, (struct tlv *) t);
1408 	free(t);
1409 	return ret;
1410 
1411 }
1412