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