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