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