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