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