Home | History | Annotate | Line # | Download | only in ldpd
socketops.c revision 1.22
      1 /* $NetBSD: socketops.c,v 1.22 2013/01/28 20:32:04 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 and Check hello keepalives */
    755 	SLIST_FOREACH_SAFE(hi, &hello_info_head, infos, hinext) {
    756 		if (hi->keepalive != 0xFFFF)
    757 			hi->keepalive--;
    758 		if (hi->keepalive < 1)
    759 			SLIST_REMOVE(&hello_info_head, hi, hello_info, infos);
    760 	}
    761 
    762 	/* Set the alarm again and bail out */
    763 	alarm(1);
    764 	errno = olderrno;
    765 }
    766 
    767 static void
    768 bail_out(int x)
    769 {
    770 	ldp_peer_holddown_all();
    771 	flush_mpls_routes();
    772 	exit(0);
    773 }
    774 
    775 /*
    776  * The big poll that catches every single event
    777  * on every socket.
    778  */
    779 int
    780 the_big_loop(void)
    781 {
    782 	int		sock_error;
    783 	uint32_t	i;
    784 	socklen_t       sock_error_size = sizeof(int);
    785 	struct ldp_peer *p;
    786 	struct com_sock	*cs;
    787 	struct pollfd	pfd[MAX_POLL_FDS];
    788 	struct hello_socket *hs;
    789 	nfds_t pollsum;
    790 
    791 	assert(MAX_POLL_FDS > 5);
    792 
    793 	SLIST_INIT(&hello_info_head);
    794 
    795 	signal(SIGALRM, send_hello_alarm);
    796 	signal(SIGPIPE, SIG_IGN);
    797 	signal(SIGINT, bail_out);
    798 	signal(SIGTERM, bail_out);
    799 
    800 	/* Send first hellos in 5 seconds. Avoid No hello notifications */
    801 	alarm(5);
    802 
    803 	route_socket = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC);
    804 
    805 	sock_error = bind_current_routes();
    806 	if (sock_error != LDP_E_OK) {
    807 		fatalp("Cannot get current routes\n");
    808 		return sock_error;
    809 	}
    810 
    811 	for (;;) {
    812 		pfd[0].fd = ls;
    813 		pfd[0].events = POLLRDNORM;
    814 		pfd[0].revents = 0;
    815 
    816 		pfd[1].fd = route_socket;
    817 		pfd[1].events = POLLRDNORM;
    818 		pfd[1].revents = 0;
    819 
    820 		pfd[2].fd = command_socket;
    821 		pfd[2].events = POLLRDNORM;
    822 		pfd[2].revents = 0;
    823 
    824 		/* Hello sockets */
    825 		pollsum = 3;
    826 		SLIST_FOREACH(hs, &hello_socket_head, listentry) {
    827 			pfd[pollsum].fd = hs->socket;
    828 			pfd[pollsum].events = POLLIN;
    829 			pfd[pollsum].revents = 0;
    830 			pollsum++;
    831 		}
    832 
    833 		/* Command sockets */
    834 		for (i=0; i < MAX_COMMAND_SOCKETS; i++)
    835 			if (csockets[i].socket != -1) {
    836 				if (pollsum >= MAX_POLL_FDS)
    837 					break;
    838 				pfd[pollsum].fd = csockets[i].socket;
    839 				pfd[pollsum].events = POLLIN;
    840 				pfd[pollsum].revents = 0;
    841 				pollsum++;
    842 			}
    843 
    844 		/* LDP Peer sockets */
    845 		SLIST_FOREACH(p, &ldp_peer_head, peers) {
    846 			if (p->socket < 1)
    847 				continue;
    848 			switch (p->state) {
    849 			    case LDP_PEER_CONNECTED:
    850 			    case LDP_PEER_ESTABLISHED:
    851 				if (pollsum >= MAX_POLL_FDS)
    852 					break;
    853 				pfd[pollsum].fd = p->socket;
    854 				pfd[pollsum].events = POLLRDNORM;
    855 				pfd[pollsum].revents = 0;
    856 				pollsum++;
    857 				break;
    858 			    case LDP_PEER_CONNECTING:
    859 				if (pollsum >= MAX_POLL_FDS)
    860 					break;
    861 				pfd[pollsum].fd = p->socket;
    862 				pfd[pollsum].events = POLLWRNORM;
    863 				pfd[pollsum].revents = 0;
    864 				pollsum++;
    865 				break;
    866 			}
    867 		}
    868 
    869 		if (pollsum >= MAX_POLL_FDS) {
    870 			fatalp("Too many sockets. Increase MAX_POLL_FDS\n");
    871 			return LDP_E_TOO_MANY_FDS;
    872 		}
    873 		if (poll(pfd, pollsum, INFTIM) < 0) {
    874 			if (errno != EINTR)
    875 				fatalp("poll: %s", strerror(errno));
    876 			continue;
    877 		}
    878 
    879 		for (i = 0; i < pollsum; i++) {
    880 			if ((pfd[i].revents & POLLRDNORM) ||
    881 			    (pfd[i].revents & POLLIN)) {
    882 				if(pfd[i].fd == ls)
    883 					new_peer_connection();
    884 				else if (pfd[i].fd == route_socket) {
    885 					struct rt_msg xbuf;
    886 					int l;
    887 					do {
    888 						l = read(route_socket, &xbuf,
    889 						    sizeof(xbuf));
    890 					} while ((l == -1) && (errno == EINTR));
    891 
    892 					if (l == -1)
    893 						break;
    894 
    895 					check_route(&xbuf, l);
    896 
    897 				} else if (is_hello_socket(pfd[i].fd) == 1) {
    898 					/* Receiving hello socket */
    899 					recv_pdu(pfd[i].fd);
    900 				} else if (pfd[i].fd == command_socket) {
    901 					command_accept(command_socket);
    902 				} else if ((cs = is_command_socket(pfd[i].fd))
    903 						!= NULL) {
    904 					command_dispatch(cs);
    905 				} else {
    906 					/* ldp peer socket */
    907 					p = get_ldp_peer_by_socket(pfd[i].fd);
    908 					if (p)
    909 						recv_session_pdu(p);
    910 				}
    911 			} else if(pfd[i].revents & POLLWRNORM) {
    912 				p = get_ldp_peer_by_socket(pfd[i].fd);
    913 				if (!p)
    914 					continue;
    915 				if (getsockopt(pfd[i].fd, SOL_SOCKET, SO_ERROR,
    916 				    &sock_error, &sock_error_size) != 0 ||
    917 				    sock_error != 0) {
    918 					ldp_peer_holddown(p);
    919 					sock_error = 0;
    920 				} else {
    921 					p->state = LDP_PEER_CONNECTED;
    922 					send_initialize(p);
    923 				}
    924 			}
    925 		}
    926 
    927 		for (int ri = 0; ri < replay_index; ri++) {
    928 			debugp("Replaying: PID %d, SEQ %d\n",
    929 				replay_rt[ri].m_rtm.rtm_pid,
    930 				replay_rt[ri].m_rtm.rtm_seq);
    931 			check_route(&replay_rt[ri], sizeof(struct rt_msg));
    932                 }
    933 		replay_index = 0;
    934 	}	/* for (;;) */
    935 }
    936 
    937 void
    938 new_peer_connection()
    939 {
    940 	struct sockaddr_in sa, sin_me;
    941 	int             s;
    942 
    943 	s = accept(ls, (struct sockaddr *) & sa,
    944 		& (socklen_t) { sizeof(struct sockaddr_in) } );
    945 	if (s < 0) {
    946 		fatalp("accept: %s", strerror(errno));
    947 		return;
    948 	}
    949 
    950 	if (get_ldp_peer((const struct sockaddr *)&sa) != NULL) {
    951 		close(s);
    952 		return;
    953 	}
    954 
    955 	warnp("Accepted a connection from %s\n", inet_ntoa(sa.sin_addr));
    956 
    957 	if (getsockname(s, (struct sockaddr *)&sin_me,
    958 	    & (socklen_t) { sizeof(struct sockaddr_in) } )) {
    959 		fatalp("new_peer_connection(): cannot getsockname\n");
    960 		close(s);
    961 		return;
    962 	}
    963 
    964 	if (ntohl(sa.sin_addr.s_addr) < ntohl(sin_me.sin_addr.s_addr)) {
    965 		fatalp("Peer %s: connect from lower ID\n",
    966 		    inet_ntoa(sa.sin_addr));
    967 		close(s);
    968 		return;
    969 	}
    970 	/* XXX: sa.sin_addr is not peer LDP ID ... */
    971 	ldp_peer_new(&sa.sin_addr, (struct sockaddr *)&sa, NULL, ldp_holddown_time, s);
    972 
    973 }
    974 
    975 void
    976 send_initialize(struct ldp_peer * p)
    977 {
    978 	struct init_tlv ti;
    979 
    980 	ti.type = htons(LDP_INITIALIZE);
    981 	ti.length = htons(sizeof(struct init_tlv) - TLV_TYPE_LENGTH);
    982 	ti.messageid = htonl(get_message_id());
    983 	ti.cs_type = htons(TLV_COMMON_SESSION);
    984 	ti.cs_len = htons(CS_LEN);
    985 	ti.cs_version = htons(LDP_VERSION);
    986 	ti.cs_keepalive = htons(2 * ldp_keepalive_time);
    987 	ti.cs_adpvlim = 0;
    988 	ti.cs_maxpdulen = htons(MAX_PDU_SIZE);
    989 	ti.cs_peeraddress.s_addr = p->ldp_id.s_addr;
    990 	ti.cs_peeraddrspace = 0;
    991 
    992 	send_tlv(p, (struct tlv *) (void *) &ti);
    993 }
    994 
    995 void
    996 keep_alive(struct ldp_peer * p)
    997 {
    998 	struct ka_tlv   kt;
    999 
   1000 	kt.type = htons(LDP_KEEPALIVE);
   1001 	kt.length = htons(sizeof(kt.messageid));
   1002 	kt.messageid = htonl(get_message_id());
   1003 
   1004 	send_tlv(p, (struct tlv *) (void *) &kt);
   1005 
   1006 }
   1007 
   1008 void
   1009 recv_session_pdu(struct ldp_peer * p)
   1010 {
   1011 	struct ldp_pdu *rpdu;
   1012 	struct address_tlv *atlv;
   1013 	struct al_tlv  *altlv;
   1014 	struct init_tlv	*itlv;
   1015 	struct label_map_tlv *lmtlv;
   1016 	struct fec_tlv *fectlv;
   1017 	struct label_tlv *labeltlv;
   1018 	struct notification_tlv *nottlv;
   1019 	struct hello_info *hi;
   1020 
   1021 	int             c;
   1022 	int32_t         wo = 0;
   1023 	struct tlv     *ttmp;
   1024 	unsigned char   recvspace[MAX_PDU_SIZE];
   1025 
   1026 	memset(recvspace, 0, MAX_PDU_SIZE);
   1027 
   1028 	c = recv(p->socket, (void *) recvspace, MAX_PDU_SIZE, MSG_PEEK);
   1029 
   1030 	debugp("Ready to read %d bytes\n", c);
   1031 
   1032 	if (c < 1) {		/* Session closed */
   1033 		warnp("Error in connection with %s\n", inet_ntoa(p->ldp_id));
   1034 		ldp_peer_holddown(p);
   1035 		return;
   1036 	}
   1037 	if (c > MAX_PDU_SIZE) {
   1038 		debugp("Incoming PDU size exceeds MAX_PDU_SIZE !\n");
   1039 		return;
   1040 	}
   1041 	if (c < MIN_PDU_SIZE) {
   1042 		debugp("PDU too small received from peer %s\n", inet_ntoa(p->ldp_id));
   1043 		return;
   1044 	}
   1045 	rpdu = (struct ldp_pdu *) recvspace;
   1046 	/* XXX: buggy messages may crash the whole thing */
   1047 	c = recv(p->socket, (void *) recvspace,
   1048 		ntohs(rpdu->length) + PDU_VER_LENGTH, MSG_WAITALL);
   1049 	rpdu = (struct ldp_pdu *) recvspace;
   1050 
   1051 	/* Check if it's somehow OK... */
   1052 	if (check_recv_pdu(p, rpdu, c) != 0)
   1053 		return;
   1054 
   1055 	debugp("Read %d bytes, PDU size: %d bytes\n", c, ntohs(rpdu->length));
   1056 	wo = sizeof(struct ldp_pdu);
   1057 
   1058 	while (wo + TLV_TYPE_LENGTH < (uint)c) {
   1059 
   1060 		ttmp = (struct tlv *) (&recvspace[wo]);
   1061 
   1062 		if ((ntohs(ttmp->type) != LDP_KEEPALIVE) &&
   1063 		    (ntohs(ttmp->type) != LDP_LABEL_MAPPING)) {
   1064 			debugp("Got Type: 0x%.4X (Length: %d) from %s\n",
   1065 			    ntohs(ttmp->type), ntohs(ttmp->length),
   1066 			    inet_ntoa(p->ldp_id));
   1067 		} else
   1068 			debugp("Got Type: 0x%.4X (Length: %d) from %s\n",
   1069 			    ntohs(ttmp->type), ntohs(ttmp->length),
   1070 			    inet_ntoa(p->ldp_id));
   1071 
   1072 		/* Should we get the message ? */
   1073 		if (p->state != LDP_PEER_ESTABLISHED &&
   1074 		    ntohs(ttmp->type) != LDP_INITIALIZE &&
   1075 		    ntohs(ttmp->type) != LDP_KEEPALIVE &&
   1076 		    ntohs(ttmp->type) != LDP_NOTIFICATION)
   1077 			break;
   1078 		/* The big switch */
   1079 		switch (ntohs(ttmp->type)) {
   1080 		case LDP_INITIALIZE:
   1081 			itlv = (struct init_tlv *)ttmp;
   1082 			/* Check size */
   1083 			if (ntohs(itlv->length) <
   1084 			    sizeof(struct init_tlv) - TLV_TYPE_LENGTH) {
   1085 				debugp("Bad size\n");
   1086 				send_notification(p, 0,
   1087 				    NOTIF_BAD_PDU_LEN | NOTIF_FATAL);
   1088 				ldp_peer_holddown(p);
   1089 				break;
   1090 			}
   1091 			/* Check version */
   1092 			if (ntohs(itlv->cs_version) != LDP_VERSION) {
   1093 				debugp("Bad version");
   1094 				send_notification(p, ntohl(itlv->messageid),
   1095 					NOTIF_BAD_LDP_VER | NOTIF_FATAL);
   1096 				ldp_peer_holddown(p);
   1097 				break;
   1098 			}
   1099 			/* Check if we got any hello from this one */
   1100 			SLIST_FOREACH(hi, &hello_info_head, infos)
   1101 				if (hi->ldp_id.s_addr == rpdu->ldp_id.s_addr)
   1102 					break;
   1103 			if (hi == NULL) {
   1104 			    debugp("No hello. Moving peer to holddown\n");
   1105 			    send_notification(p, ntohl(itlv->messageid),
   1106 				NOTIF_SESSION_REJECTED_NO_HELLO | NOTIF_FATAL);
   1107 			    ldp_peer_holddown(p);
   1108 			    break;
   1109 			}
   1110 
   1111 			if (!p->master) {
   1112 				keep_alive(p);
   1113 				send_initialize(p);
   1114 			} else {
   1115 				p->state = LDP_PEER_ESTABLISHED;
   1116 				p->established_t = time(NULL);
   1117 				keep_alive(p);
   1118 
   1119 				/*
   1120 				 * Recheck here ldp id because we accepted
   1121 				 * connection without knowing who is it for sure
   1122 				 */
   1123 				p->ldp_id.s_addr = rpdu->ldp_id.s_addr;
   1124 
   1125 				fatalp("LDP neighbour %s is UP\n",
   1126 				    inet_ntoa(p->ldp_id));
   1127 				mpls_add_ldp_peer(p);
   1128 				send_addresses(p);
   1129 				send_all_bindings(p);
   1130 			}
   1131 			break;
   1132 		case LDP_KEEPALIVE:
   1133 			if ((p->state == LDP_PEER_CONNECTED) && (!p->master)) {
   1134 				p->state = LDP_PEER_ESTABLISHED;
   1135 				p->established_t = time(NULL);
   1136 				fatalp("LDP neighbour %s is UP\n",
   1137 				    inet_ntoa(p->ldp_id));
   1138 				mpls_add_ldp_peer(p);
   1139 				send_addresses(p);
   1140 				send_all_bindings(p);
   1141 			}
   1142 			p->timeout = p->holdtime;
   1143 			break;
   1144 		case LDP_ADDRESS:
   1145 			/* Add peer addresses */
   1146 			atlv = (struct address_tlv *) ttmp;
   1147 			altlv = (struct al_tlv *) (&atlv[1]);
   1148 			add_ifaddresses(p, altlv);
   1149 			print_bounded_addresses(p);
   1150 			break;
   1151 		case LDP_ADDRESS_WITHDRAW:
   1152 			atlv = (struct address_tlv *) ttmp;
   1153 			altlv = (struct al_tlv *) (&atlv[1]);
   1154 			del_ifaddresses(p, altlv);
   1155 			break;
   1156 		case LDP_LABEL_MAPPING:
   1157 			lmtlv = (struct label_map_tlv *) ttmp;
   1158 			fectlv = (struct fec_tlv *) (&lmtlv[1]);
   1159 			labeltlv = (struct label_tlv *)((unsigned char *)fectlv
   1160 				+ ntohs(fectlv->length) + TLV_TYPE_LENGTH);
   1161 			map_label(p, fectlv, labeltlv);
   1162 			break;
   1163 		case LDP_LABEL_REQUEST:
   1164 			lmtlv = (struct label_map_tlv *) ttmp;
   1165 			fectlv = (struct fec_tlv *) (&lmtlv[1]);
   1166 			switch (request_respond(p, lmtlv, fectlv)) {
   1167 			case LDP_E_BAD_FEC:
   1168 				send_notification(p, ntohl(lmtlv->messageid),
   1169 					NOTIF_UNKNOWN_TLV);
   1170 				break;
   1171 			case LDP_E_BAD_AF:
   1172 				send_notification(p, ntohl(lmtlv->messageid),
   1173 					NOTIF_UNSUPPORTED_AF);
   1174 				break;
   1175 			case LDP_E_NO_SUCH_ROUTE:
   1176 				send_notification(p, ntohl(lmtlv->messageid),
   1177 					NOTIF_NO_ROUTE);
   1178 				break;
   1179 			}
   1180 			break;
   1181 		case LDP_LABEL_WITHDRAW:
   1182 			lmtlv = (struct label_map_tlv *) ttmp;
   1183 			fectlv = (struct fec_tlv *) (&lmtlv[1]);
   1184 			if (withdraw_label(p, fectlv) == LDP_E_OK) {
   1185 				/* Send RELEASE */
   1186 				prepare_release(ttmp);
   1187 				send_tlv(p, ttmp);
   1188 				}
   1189 			break;
   1190 		case LDP_LABEL_RELEASE:
   1191 			/*
   1192 			 * XXX: we need to make a timed queue...
   1193 			 * For now I just assume peers are processing messages
   1194 			 * correctly so I just ignore confirmations
   1195 			 */
   1196 			wo = -1;	/* Ignore rest of message */
   1197 			break;
   1198 		case LDP_LABEL_ABORT:
   1199 		/* XXX: For now I pretend I can process everything
   1200 		 * RFC 5036, Section 3.5.9.1
   1201 		 * If an LSR receives a Label Abort Request Message after it
   1202 		 * has responded to the Label Request in question with a Label
   1203 		 * Mapping message or a Notification message, it ignores the
   1204 		 * abort request.
   1205 		 */
   1206 			wo = -1;
   1207 			break;
   1208 		case LDP_NOTIFICATION:
   1209 			nottlv = (struct notification_tlv *) ttmp;
   1210 			nottlv->st_code = ntohl(nottlv->st_code);
   1211 			fatalp("Got notification 0x%X from peer %s\n",
   1212 			    nottlv->st_code, inet_ntoa(p->ldp_id));
   1213 			if (nottlv->st_code >> 31) {
   1214 				fatalp("LDP peer %s signalized %s\n",
   1215 				    inet_ntoa(p->ldp_id),
   1216 				    NOTIF_STR[(nottlv->st_code << 1) >> 1]);
   1217 				ldp_peer_holddown(p);
   1218 				wo = -1;
   1219 			}
   1220 			break;
   1221 		case LDP_HELLO:
   1222 			/* No hellos should came on tcp session */
   1223 			wo = -1;
   1224 			break;
   1225 		default:
   1226 			warnp("Unknown TLV received from %s\n",
   1227 			    inet_ntoa(p->ldp_id));
   1228 			debug_tlv(ttmp);
   1229 			wo = -1;/* discard the rest of the message */
   1230 			break;
   1231 		}
   1232 		if (wo < 0) {
   1233 			debugp("Discarding the rest of the message\n");
   1234 			break;
   1235 		} else {
   1236 			wo += ntohs(ttmp->length) + TLV_TYPE_LENGTH;
   1237 			debugp("WORKED ON %u bytes (Left %d)\n", wo, c - wo);
   1238 		}
   1239 	}			/* while */
   1240 
   1241 }
   1242 
   1243 /* Sends a pdu, tlv pair to a connected peer */
   1244 int
   1245 send_message(struct ldp_peer * p, struct ldp_pdu * pdu, struct tlv * t)
   1246 {
   1247 	unsigned char   sendspace[MAX_PDU_SIZE];
   1248 
   1249 	/* Check if peer is connected */
   1250 	switch (p->state) {
   1251 	case LDP_PEER_CONNECTED:
   1252 	case LDP_PEER_ESTABLISHED:
   1253 		break;
   1254 	default:
   1255 		return -1;
   1256 	}
   1257 
   1258 	/* Check length validity first */
   1259 	if (ntohs(pdu->length) !=
   1260 	    ntohs(t->length) + TLV_TYPE_LENGTH + PDU_PAYLOAD_LENGTH) {
   1261 		fatalp("LDP: TLV - PDU incompability. Message discarded\n");
   1262 		fatalp("LDP: TLV len %d - PDU len %d\n", ntohs(t->length),
   1263 		    ntohs(pdu->length));
   1264 		return -1;
   1265 	}
   1266 	if (ntohs(t->length) + PDU_VER_LENGTH > MAX_PDU_SIZE) {
   1267 		fatalp("Message to large discarded\n");
   1268 		return -1;
   1269 	}
   1270 	/* Arrange them in a buffer and send */
   1271 	memcpy(sendspace, pdu, sizeof(struct ldp_pdu));
   1272 	memcpy(sendspace + sizeof(struct ldp_pdu), t,
   1273 	    ntohs(t->length) + TLV_TYPE_LENGTH);
   1274 
   1275 	/* Report keepalives only for DEBUG */
   1276 	if ((ntohs(t->type) != 0x201) && (ntohs(t->type) != 0x400)) {
   1277 		debugp("Sending message type 0x%.4X to %s (size: %d)\n",
   1278 		    ntohs(t->type), inet_ntoa(p->ldp_id), ntohs(t->length));
   1279 	} else
   1280 	/* downgraded from warnp to debugp for now */
   1281 		debugp("Sending message type 0x%.4X to %s (size: %d)\n",
   1282 		    ntohs(t->type), inet_ntoa(p->ldp_id), ntohs(t->length));
   1283 
   1284 	/* Send it finally */
   1285 	return send(p->socket, sendspace,
   1286 		ntohs(pdu->length) + PDU_VER_LENGTH, 0);
   1287 }
   1288 
   1289 /*
   1290  * Encapsulates TLV into a PDU and sends it to a peer
   1291  */
   1292 int
   1293 send_tlv(struct ldp_peer * p, struct tlv * t)
   1294 {
   1295 	struct ldp_pdu  pdu;
   1296 
   1297 	pdu.version = htons(LDP_VERSION);
   1298 	inet_aton(LDP_ID, &pdu.ldp_id);
   1299 	pdu.label_space = 0;
   1300 	pdu.length = htons(ntohs(t->length) + TLV_TYPE_LENGTH +
   1301 		PDU_PAYLOAD_LENGTH);
   1302 
   1303 	return send_message(p, &pdu, t);
   1304 }
   1305 
   1306 
   1307 int
   1308 send_addresses(struct ldp_peer * p)
   1309 {
   1310 	struct address_list_tlv *t;
   1311 	int             ret;
   1312 
   1313 	t = build_address_list_tlv();
   1314 
   1315 	ret = send_tlv(p, (struct tlv *) t);
   1316 	free(t);
   1317 	return ret;
   1318 
   1319 }
   1320