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