xref: /openbsd/usr.sbin/npppd/l2tp/l2tp_ctrl.c (revision 3d8817e4)
1 /* $OpenBSD: l2tp_ctrl.c,v 1.6 2011/01/20 23:12:33 jasper Exp $	*/
2 
3 /*-
4  * Copyright (c) 2009 Internet Initiative Japan Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 /**@file Control connection processing functions for L2TP LNS */
29 /* $Id: l2tp_ctrl.c,v 1.6 2011/01/20 23:12:33 jasper Exp $ */
30 #include <sys/types.h>
31 #include <sys/param.h>
32 #include <sys/time.h>
33 #include <sys/socket.h>
34 #include <sys/endian.h>
35 #include <netinet/in.h>
36 #include <net/if.h>
37 #include <arpa/inet.h>
38 #include <stdlib.h>
39 #include <syslog.h>
40 #include <stdio.h>
41 #include <stdarg.h>
42 #include <stddef.h>
43 #include <netdb.h>
44 #include <time.h>
45 #include <string.h>
46 #include <event.h>
47 #include <ifaddrs.h>
48 
49 #ifdef USE_LIBSOCKUTIL
50 #include <seil/sockfromto.h>
51 #endif
52 
53 #include "time_utils.h"
54 #include "ipsec_util.h"
55 #include "bytebuf.h"
56 #include "hash.h"
57 #include "debugutil.h"
58 #include "slist.h"
59 #include "l2tp.h"
60 #include "l2tp_local.h"
61 #include "l2tp_subr.h"
62 #include "net_utils.h"
63 #include "config_helper.h"
64 #include "version.h"
65 
66 static int                l2tp_ctrl_init (l2tp_ctrl *, l2tpd *, struct sockaddr *, struct sockaddr *, void *);
67 static void               l2tp_ctrl_reload (l2tp_ctrl *);
68 static int                l2tp_ctrl_send_disconnect_notify (l2tp_ctrl *);
69 #if 0
70 static void               l2tp_ctrl_purge_ipsec_sa (l2tp_ctrl *);
71 #endif
72 static void               l2tp_ctrl_timeout (int, short, void *);
73 static int                l2tp_ctrl_resend_una_packets (l2tp_ctrl *);
74 static void               l2tp_ctrl_destroy_all_calls (l2tp_ctrl *);
75 static int                l2tp_ctrl_disconnect_all_calls (l2tp_ctrl *);
76 static void               l2tp_ctrl_reset_timeout (l2tp_ctrl *);
77 static inline int         l2tp_ctrl_txwin_size (l2tp_ctrl *);
78 static inline int         l2tp_ctrl_txwin_is_full (l2tp_ctrl *);
79 static int                l2tp_ctrl_recv_SCCRQ (l2tp_ctrl *, u_char *, int, l2tpd *, struct sockaddr *);
80 static int                l2tp_ctrl_send_StopCCN (l2tp_ctrl *, int);
81 static int                l2tp_ctrl_recv_StopCCN (l2tp_ctrl *, u_char *, int);
82 static void               l2tp_ctrl_send_SCCRP (l2tp_ctrl *);
83 static int                l2tp_ctrl_send_HELLO (l2tp_ctrl *);
84 static int                l2tp_ctrl_send_ZLB (l2tp_ctrl *);
85 static inline const char  *l2tp_ctrl_state_string (l2tp_ctrl *);
86 
87 #ifdef	L2TP_CTRL_DEBUG
88 #define	L2TP_CTRL_ASSERT(x)	ASSERT(x)
89 #define	L2TP_CTRL_DBG(x)	l2tp_ctrl_log x
90 #else
91 #define	L2TP_CTRL_ASSERT(x)
92 #define	L2TP_CTRL_DBG(x)
93 #endif
94 
95 /* Sequence # of l2tp_ctrl ID */
96 static unsigned l2tp_ctrl_id_seq = 0;
97 
98 #define SEQ_LT(a,b)	((int16_t)((a) - (b)) <  0)
99 #define SEQ_GT(a,b)	((int16_t)((a) - (b)) >  0)
100 
101 /**
102  * Build instance of {@link ::_l2tp_ctrl L2TP LNS control connection}
103  */
104 l2tp_ctrl *
105 l2tp_ctrl_create(void)
106 {
107 	l2tp_ctrl *_this;
108 
109 	if ((_this = malloc(sizeof(l2tp_ctrl))) == NULL)
110 		return NULL;
111 
112 	memset(_this, 0, sizeof(l2tp_ctrl));
113 	return (l2tp_ctrl *)_this;
114 }
115 
116 /**
117  * initialize and startup of {@link ::_l2tp_ctrl L2TP LNS control connection}
118  * instance
119  */
120 static int
121 l2tp_ctrl_init(l2tp_ctrl *_this, l2tpd *_l2tpd, struct sockaddr *peer,
122     struct sockaddr *sock, void *nat_t_ctx)
123 {
124 	int tunid, i;
125 	bytebuffer *bytebuf;
126 	time_t curr_time;
127 
128 	memset(_this, 0, sizeof(l2tp_ctrl));
129 
130 	curr_time = get_monosec();
131 	_this->l2tpd = _l2tpd;
132 	_this->state = L2TP_CTRL_STATE_IDLE;
133 	_this->last_snd_ctrl = curr_time;
134 
135 	slist_init(&_this->call_list);
136 
137 	/* seek a free tunnel ID */
138 	i = 0;
139 	_this->id = ++l2tp_ctrl_id_seq;
140 	for (i = 0, tunid = _this->id; ; i++, tunid++) {
141 		tunid &= 0xffff;
142 		_this->tunnel_id = l2tp_ctrl_id_seq & 0xffff;
143 		if (tunid == 0)
144 			continue;
145 		if (l2tpd_get_ctrl(_l2tpd, tunid) == NULL)
146 			break;
147 		if (i > 80000) {
148 			/* this must be happen, just log it. */
149 			l2tpd_log(_l2tpd, LOG_ERR, "Too many l2tp controls");
150 			return -1;
151 		}
152 	}
153 
154 	_this->tunnel_id = tunid;
155 
156 	L2TP_CTRL_ASSERT(peer != NULL);
157 	L2TP_CTRL_ASSERT(sock != NULL);
158 	memcpy(&_this->peer, peer, peer->sa_len);
159 	memcpy(&_this->sock, sock, sock->sa_len);
160 
161 	/* prepare send buffer */
162 	_this->winsz = L2TPD_DEFAULT_SEND_WINSZ;
163 	if ((_this->snd_buffers = calloc(_this->winsz, sizeof(bytebuffer *)))
164 	    == NULL) {
165 		l2tpd_log(_l2tpd, LOG_ERR,
166 		    "calloc() failed in %s(): %m", __func__);
167 		goto fail;
168 	}
169 	for (i = 0; i < _this->winsz; i++) {
170 		if ((bytebuf = bytebuffer_create(L2TPD_SND_BUFSIZ)) == NULL) {
171 			l2tpd_log(_l2tpd, LOG_ERR,
172 			    "bytebuffer_create() failed in %s(): %m", __func__);
173 			goto fail;
174 		}
175 		_this->snd_buffers[i] = bytebuf;
176 	}
177 	if ((_this->zlb_buffer = bytebuffer_create(sizeof(struct l2tp_header)
178 	    + 128)) == NULL) {
179 		l2tpd_log(_l2tpd, LOG_ERR,
180 		    "bytebuffer_create() failed in %s(): %m", __func__);
181 		goto fail;
182 	}
183 #ifdef USE_LIBSOCKUTIL
184 	if (nat_t_ctx != NULL) {
185 		if ((_this->sa_cookie = malloc(
186 		    sizeof(struct in_ipsec_sa_cookie))) != NULL) {
187 			*(struct in_ipsec_sa_cookie *)_this->sa_cookie =
188 			    *(struct in_ipsec_sa_cookie *)nat_t_ctx;
189 		} else {
190 			l2tpd_log(_l2tpd, LOG_ERR,
191 			    "creating sa_cookie failed: %m");
192 			goto fail;
193 		}
194 	}
195 #endif
196 	_this->hello_interval = L2TP_CTRL_DEFAULT_HELLO_INTERVAL;
197 	_this->hello_timeout = L2TP_CTRL_DEFAULT_HELLO_TIMEOUT;
198 	_this->hello_io_time = curr_time;
199 
200 	/* initialize timeout timer */
201 	l2tp_ctrl_reset_timeout(_this);
202 
203 	/* register l2tp context */
204 	l2tpd_add_ctrl(_l2tpd, _this);
205 	return 0;
206 fail:
207 	l2tp_ctrl_stop(_this, 0);
208 	return -1;
209 }
210 
211 /*
212  * setup {@link ::_l2tp_ctrl L2TP LNS control connection} instance
213  */
214 static void
215 l2tp_ctrl_reload(l2tp_ctrl *_this)
216 {
217 	int ival;
218 
219 	_this->data_use_seq = l2tp_ctrl_config_str_equal(_this,
220 	    "l2tp.data_use_seq", "true", 1);
221 
222 	if ((ival = l2tp_ctrl_config_int(_this, "l2tp.hello_interval", 0))!= 0)
223 		_this->hello_interval = ival;
224 	if ((ival = l2tp_ctrl_config_int(_this, "l2tp.hello_timeout", 0)) != 0)
225 		_this->hello_timeout = ival;
226 
227 	return;
228 }
229 
230 /*
231  * free {@link ::_l2tp_ctrl L2TP LNS control connection} instance
232  */
233 void
234 l2tp_ctrl_destroy(l2tp_ctrl *_this)
235 {
236 	L2TP_CTRL_ASSERT(_this != NULL);
237 #ifdef USE_LIBSOCKUTIL
238 	if (_this->sa_cookie != NULL)
239 		free(_this->sa_cookie);
240 #endif
241 	free(_this);
242 }
243 
244 /*
245  * nortify disconnection to peer
246  *
247  * @return 	0: all CDN and StopCCN have been sent.
248  *		N: if the remaining calls which still not sent CDN exist,
249  *		   return # of the calls.
250  *		-1: when try to send of StopCCN failed.
251  */
252 static int
253 l2tp_ctrl_send_disconnect_notify(l2tp_ctrl *_this)
254 {
255 	int ncalls;
256 
257 	L2TP_CTRL_ASSERT(_this != NULL)
258 	L2TP_CTRL_ASSERT(_this->state == L2TP_CTRL_STATE_ESTABLISHED ||
259 	    _this->state == L2TP_CTRL_STATE_CLEANUP_WAIT);
260 
261 	/* the contexts is not active or StopCCN have been sent */
262 	if (_this->active_closing == 0)
263 		return 0;
264 
265 	/* CDN have been sent for all Calls */
266 	ncalls = 0;
267 	if (slist_length(&_this->call_list) != 0) {
268 		ncalls = l2tp_ctrl_disconnect_all_calls(_this);
269 		if (ncalls > 0) {
270 			/*
271 			 * Call l2tp_ctrl_disconnect_all_calls() to check
272 			 * the send window still filled.
273 			 */
274 			ncalls = l2tp_ctrl_disconnect_all_calls(_this);
275 		}
276 	}
277 	if (ncalls > 0)
278 		return ncalls;
279 
280 	if (l2tp_ctrl_send_StopCCN(_this, _this->active_closing) != 0)
281 		return -1;
282 	_this->active_closing = 0;
283 
284 	return 0;
285 }
286 
287 /*
288  * Terminate the control connection
289  *
290  * <p>
291  * please spcify an appropriate value to result( >0 ) for
292  * StopCCN ResultCode AVP, when to sent Active Close (which
293  * require StopCCN sent).</p>
294  * <p>
295  * When the return value of this function is zero, the _this
296  * is already released. The lt2p_ctrl process that was bound to it
297  * could not contine.
298  * When the return value of this function is one, the timer
299  * is reset.</p>
300  *
301  * @return	return 0 if terminate process was completed.
302  */
303 int
304 l2tp_ctrl_stop(l2tp_ctrl *_this, int result)
305 {
306 	int i;
307 	l2tpd *_l2tpd;
308 
309 	L2TP_CTRL_ASSERT(_this != NULL);
310 
311 	switch (_this->state) {
312 	case L2TP_CTRL_STATE_ESTABLISHED:
313 		_this->state = L2TP_CTRL_STATE_CLEANUP_WAIT;
314 		if (result > 0) {
315 			_this->active_closing = result;
316 			l2tp_ctrl_send_disconnect_notify(_this);
317 			break;
318 		}
319 		goto cleanup;
320 	default:
321 		l2tp_ctrl_log(_this, LOG_DEBUG, "%s() unexpected state=%s",
322 		    __func__, l2tp_ctrl_state_string(_this));
323 		/* FALLTHROUGH */
324 	case L2TP_CTRL_STATE_WAIT_CTL_CONN:
325 		/* FALLTHROUGH */
326 	case L2TP_CTRL_STATE_CLEANUP_WAIT:
327 cleanup:
328 		if (slist_length(&_this->call_list) != 0) {
329 			if (l2tp_ctrl_disconnect_all_calls(_this) > 0)
330 				break;
331 		}
332 #if 0
333 		if (_this->l2tpd->purge_ipsec_sa != 0)
334 			l2tp_ctrl_purge_ipsec_sa(_this);
335 #endif
336 
337 		l2tp_ctrl_log(_this, LOG_NOTICE, "logtype=Finished");
338 
339 		evtimer_del(&_this->ev_timeout);
340 
341 		/* free send buffer */
342 		if (_this->snd_buffers != NULL) {
343 			for (i = 0; i < _this->winsz; i++)
344 				bytebuffer_destroy(_this->snd_buffers[i]);
345 			free(_this->snd_buffers);
346 			_this->snd_buffers = NULL;
347 		}
348 		if (_this->zlb_buffer != NULL) {
349 			bytebuffer_destroy(_this->zlb_buffer);
350 			_this->zlb_buffer = NULL;
351 		}
352 
353 		/* free l2tp_call */
354 		l2tp_ctrl_destroy_all_calls(_this);
355 		slist_fini(&_this->call_list);
356 
357 		l2tpd_remove_ctrl(_this->l2tpd, _this->tunnel_id);
358 
359 		_l2tpd = _this->l2tpd;
360 		l2tp_ctrl_destroy(_this);
361 
362 		l2tpd_ctrl_finished_notify(_l2tpd);
363 		return 0;	/* stopped */
364 	}
365 	l2tp_ctrl_reset_timeout(_this);
366 
367 	return 1;
368 }
369 
370 #if 0
371 /** Delete the IPsec SA for disconnection */
372 static void
373 l2tp_ctrl_purge_ipsec_sa(l2tp_ctrl *_this)
374 {
375 	int is_natt, proto;
376 	struct sockaddr_storage peer, sock;
377 	hash_link *hl;
378 #ifdef USE_LIBSOCKUTIL
379 	struct in_ipsec_sa_cookie *ipsec_sa_cookie;
380 #endif
381 	l2tp_ctrl *anot;
382 
383 	/*
384 	 * Search another tunnel that uses the same IPsec SA
385 	 * by lineer.
386 	 */
387 	for (hl = hash_first(_this->l2tpd->ctrl_map);
388 	    hl != NULL; hl = hash_next(_this->l2tpd->ctrl_map)) {
389 		anot = hl->item;
390 		if (anot == _this)
391 			continue;
392 
393 		if (_this->peer.ss_family != anot->peer.ss_family)
394 			continue;
395 		if (_this->peer.ss_family == AF_INET) {
396 			if (SIN(&_this->peer)->sin_addr.s_addr !=
397 			    SIN(&anot->peer)->sin_addr.s_addr)
398 				continue;
399 		} else if (_this->peer.ss_family == AF_INET6) {
400 			if (!IN6_ARE_ADDR_EQUAL(
401 			    &(SIN6(&_this->peer)->sin6_addr),
402 			    &(SIN6(&anot->peer)->sin6_addr)))
403 				continue;
404 		}
405 #ifdef USE_LIBSOCKUTIL
406 		if (_this->sa_cookie != NULL && anot->sa_cookie != NULL) {
407 			/* Both tunnels belong the same NAT box.  */
408 
409 			if (memcmp(_this->sa_cookie, anot->sa_cookie,
410 			    sizeof(struct in_ipsec_sa_cookie)) != 0)
411 				/* Different hosts behind the NAT box.  */
412 				continue;
413 
414 			/* The SA is shared by another tunnels by one host. */
415 			return;	/* don't purge the sa */
416 
417 		} else if (_this->sa_cookie != NULL || anot->sa_cookie != NULL)
418 			/* Only one is behind the NAT */
419 			continue;
420 #endif
421 		return;	/* don't purge the sa */
422 	}
423 
424 #ifdef USE_LIBSOCKUTIL
425 	is_natt = (_this->sa_cookie != NULL)? 1 : 0;
426 #else
427 	is_natt = 0;
428 #endif
429 	memcpy(&peer, &_this->peer, _this->peer.ss_len);
430 	memcpy(&sock, &_this->sock, _this->sock.ss_len);
431 	if (!is_natt) {
432 		proto = 0;
433 		SIN(&peer)->sin_port = SIN(&sock)->sin_port = 0;
434 	}
435 #ifdef USE_LIBSOCKUTIL
436 	else {
437 		ipsec_sa_cookie = _this->sa_cookie;
438 		SIN(&peer)->sin_port = ipsec_sa_cookie->remote_port;
439 		SIN(&sock)->sin_port = ipsec_sa_cookie->local_port;
440 #if 1
441 		/*
442 		 * XXX: As RFC 2367, protocol sould be specified if the port
443 		 * XXX: number is non-zero.
444 		 */
445 		proto = 0;
446 #else
447 		proto = IPPROTO_UDP;
448 #endif
449 	}
450 #endif
451 	if (ipsec_util_purge_transport_sa((struct sockaddr *)&peer,
452 	    (struct sockaddr *)&sock, proto, IPSEC_UTIL_DIRECTION_BOTH) != 0)
453 		l2tp_ctrl_log(_this, LOG_NOTICE, "failed to purge IPSec SA");
454 }
455 #endif
456 
457 /* timeout processing */
458 static void
459 l2tp_ctrl_timeout(int fd, short evtype, void *ctx)
460 {
461 	int next_timeout, need_resend;
462 	time_t curr_time;
463 	l2tp_ctrl *_this;
464 	l2tp_call *call;
465 
466 	/*
467 	 * the timer must be reset, when leave this function.
468 	 * MEMO: l2tp_ctrl_stop() will reset the timer in it.
469 	 * and please remember that the l2tp_ctrl_stop() may free _this.
470 	 */
471 	_this = ctx;
472 	L2TP_CTRL_ASSERT(_this != NULL);
473 
474 	curr_time = get_monosec();
475 
476 	next_timeout = 2;
477 	need_resend = 0;
478 
479 	if (l2tp_ctrl_txwin_size(_this) > 0)  {
480 		if (_this->state == L2TP_CTRL_STATE_ESTABLISHED) {
481 			if (_this->hello_wait_ack != 0) {
482 				/* wait Hello reply */
483 				if (curr_time - _this->hello_io_time >=
484 				    _this->hello_timeout) {
485 					l2tp_ctrl_log(_this, LOG_NOTICE,
486 					    "timeout waiting ack for hello "
487 					    "packets.");
488 					l2tp_ctrl_stop(_this,
489 					    L2TP_STOP_CCN_RCODE_GENERAL);
490 					return;
491 				}
492 			}
493 		} else if (curr_time - _this->last_snd_ctrl >=
494 		    L2TP_CTRL_CTRL_PKT_TIMEOUT) {
495 			l2tp_ctrl_log(_this, LOG_NOTICE,
496 			    "timeout waiting ack for ctrl packets.");
497 			l2tp_ctrl_stop(_this,
498 			    L2TP_STOP_CCN_RCODE_GENERAL);
499 			return;
500 		}
501 		need_resend = 1;
502 	} else {
503 		for (slist_itr_first(&_this->call_list);
504 		    slist_itr_has_next(&_this->call_list);) {
505 			call = slist_itr_next(&_this->call_list);
506 			if (call->state == L2TP_CALL_STATE_CLEANUP_WAIT) {
507 				l2tp_call_destroy(call, 1);
508 				slist_itr_remove(&_this->call_list);
509 			}
510 		}
511 	}
512 
513 	switch (_this->state) {
514 	case L2TP_CTRL_STATE_IDLE:
515 		/*
516 		 * idle:
517 		 * XXX: never happen in current implementation
518 		 */
519 		l2tp_ctrl_log(_this, LOG_ERR,
520 		    "Internal error, timeout on illegal state=idle");
521 		l2tp_ctrl_stop(_this, L2TP_STOP_CCN_RCODE_GENERAL);
522 		break;
523 	case L2TP_CTRL_STATE_WAIT_CTL_CONN:
524 		/*
525 		 * wait-ctrl-conn:
526 		 * 	if there is no ack for SCCRP, the peer will
527 		 * 	resend SCCRQ. however this implementation can
528 		 *	not recognize that the SCCRQ was resent or not.
529 		 *	Therefore, never resent from this side.
530 		 */
531 		need_resend = 0;
532 		break;
533 	case L2TP_CTRL_STATE_ESTABLISHED:
534 		if (slist_length(&_this->call_list) == 0 &&
535 		    curr_time - _this->last_snd_ctrl >=
536 			    L2TP_CTRL_WAIT_CALL_TIMEOUT) {
537 			if (_this->ncalls == 0)
538 				/* fail to receive first call */
539 				l2tp_ctrl_log(_this, LOG_WARNING,
540 				    "timeout waiting call");
541 			l2tp_ctrl_stop(_this,
542 			    L2TP_STOP_CCN_RCODE_GENERAL);
543 			return;
544 		}
545 		if (_this->hello_wait_ack == 0 && _this->hello_interval > 0) {
546 			/* send Hello */
547 			if (curr_time - _this->hello_interval >=
548 			    _this->hello_io_time) {
549 				if (l2tp_ctrl_send_HELLO(_this) == 0)
550 					/* success */
551 					_this->hello_wait_ack = 1;
552 				_this->hello_io_time = curr_time;
553 				need_resend = 0;
554 			}
555 		}
556 		break;
557 	case L2TP_CTRL_STATE_CLEANUP_WAIT:
558 		if (curr_time - _this->last_snd_ctrl >=
559 		    L2TP_CTRL_CLEANUP_WAIT_TIME) {
560 			l2tp_ctrl_log(_this, LOG_NOTICE,
561 			    "Cleanup timeout state=%d", _this->state);
562 			l2tp_ctrl_stop(_this, 0);
563 			return;
564 		}
565 		if (_this->active_closing != 0)
566 			l2tp_ctrl_send_disconnect_notify(_this);
567 		break;
568 	default:
569 		l2tp_ctrl_log(_this, LOG_ERR,
570 		    "Internal error, timeout on illegal state=%d",
571 			_this->state);
572 		l2tp_ctrl_stop(_this, L2TP_STOP_CCN_RCODE_GENERAL);
573 		return;
574 	}
575 	/* resend if required */
576 	if (need_resend)
577 		l2tp_ctrl_resend_una_packets(_this);
578 	l2tp_ctrl_reset_timeout(_this);
579 }
580 
581 int
582 l2tp_ctrl_send(l2tp_ctrl *_this, const void *msg, int len)
583 {
584 	int rval;
585 
586 #ifdef USE_LIBSOCKUTIL
587 	if (_this->sa_cookie != NULL)
588 		rval = sendfromto_nat_t(LISTENER_SOCK(_this), msg, len, 0,
589 		    (struct sockaddr *)&_this->sock,
590 		    (struct sockaddr *)&_this->peer, _this->sa_cookie);
591 	else
592 		rval = sendfromto(LISTENER_SOCK(_this), msg, len, 0,
593 		    (struct sockaddr *)&_this->sock,
594 		    (struct sockaddr *)&_this->peer);
595 #else
596 	rval = sendto(LISTENER_SOCK(_this), msg, len, 0,
597 	    (struct sockaddr *)&_this->peer, _this->peer.ss_len);
598 #endif
599 	return rval;
600 }
601 
602 /* resend una packets */
603 static int
604 l2tp_ctrl_resend_una_packets(l2tp_ctrl *_this)
605 {
606 	uint16_t seq;
607 	bytebuffer *bytebuf;
608 	struct l2tp_header *header;
609 	int nsend;
610 
611 	nsend = 0;
612 	for (seq = _this->snd_una; SEQ_LT(seq, _this->snd_nxt); seq++) {
613 		bytebuf = _this->snd_buffers[seq % _this->winsz];
614 		header = bytebuffer_pointer(bytebuf);
615 		header->nr = htons(_this->rcv_nxt);
616 #ifdef L2TP_CTRL_DEBUG
617 		if (debuglevel >= 3) {
618 			l2tp_ctrl_log(_this, DEBUG_LEVEL_3, "RESEND seq=%u",
619 			    ntohs(header->ns));
620 			show_hd(debug_get_debugfp(),
621 			    bytebuffer_pointer(bytebuf),
622 			    bytebuffer_remaining(bytebuf));
623 		}
624 #endif
625 		if (l2tp_ctrl_send(_this, bytebuffer_pointer(bytebuf),
626 		    bytebuffer_remaining(bytebuf)) < 0) {
627 			l2tp_ctrl_log(_this, LOG_ERR,
628 			    "sendto() failed in %s: %m", __func__);
629 			return -1;
630 		}
631 		nsend++;
632 	}
633 	return nsend;
634 }
635 
636 /* free all calls */
637 static void
638 l2tp_ctrl_destroy_all_calls(l2tp_ctrl *_this)
639 {
640 	l2tp_call *call;
641 
642 	L2TP_CTRL_ASSERT(_this != NULL);
643 
644 	while ((call = slist_remove_first(&_this->call_list)) != NULL)
645 		l2tp_call_destroy(call, 1);
646 }
647 
648 
649 /* disconnect all calls on the control context
650  * @return return # of calls that is not waiting cleanup.
651  */
652 static int
653 l2tp_ctrl_disconnect_all_calls(l2tp_ctrl *_this)
654 {
655 	int i, len, ncalls;
656 	l2tp_call *call;
657 
658 	L2TP_CTRL_ASSERT(_this != NULL);
659 
660 	ncalls = 0;
661 	len = slist_length(&_this->call_list);
662 	for (i = 0; i < len; i++) {
663 		call = slist_get(&_this->call_list, i);
664 		if (call->state != L2TP_CALL_STATE_CLEANUP_WAIT) {
665 			ncalls++;
666 
667 			if (l2tp_ctrl_txwin_is_full(_this)) {
668 				L2TP_CTRL_DBG((_this, LOG_INFO,
669 				    "Too many calls.  Sending window is not "
670 				    "enough to send CDN to all clients."));
671 				/* nothing to do */
672 			} else
673 				l2tp_call_admin_disconnect(call);
674 		}
675 	}
676 	return ncalls;
677 }
678 
679 /* reset timeout */
680 static void
681 l2tp_ctrl_reset_timeout(l2tp_ctrl *_this)
682 {
683 	int intvl;
684 	struct timeval tv0;
685 
686 	L2TP_CTRL_ASSERT(_this != NULL);
687 
688 	if (evtimer_initialized(&_this->ev_timeout))
689 		evtimer_del(&_this->ev_timeout);
690 
691 	switch (_this->state) {
692 	case L2TP_CTRL_STATE_CLEANUP_WAIT:
693 		intvl = 1;
694 		break;
695 	default:
696 		intvl = 2;
697 		break;
698 	}
699 	tv0.tv_usec = 0;
700 	tv0.tv_sec = intvl;
701 	if (!evtimer_initialized(&_this->ev_timeout))
702 		evtimer_set(&_this->ev_timeout, l2tp_ctrl_timeout, _this);
703 	evtimer_add(&_this->ev_timeout, &tv0);
704 }
705 
706 /*
707  * protocols / send and receive
708  */
709 /* Receive packet */
710 void
711 l2tp_ctrl_input(l2tpd *_this, int listener_index, struct sockaddr *peer,
712     struct sockaddr *sock, void *nat_t_ctx, u_char *pkt, int pktlen)
713 {
714 	int i, len, offsiz, reqlen, is_ctrl;
715 	uint16_t mestype;
716 	struct l2tp_avp *avp, *avp0;
717 	l2tp_ctrl *ctrl;
718 	l2tp_call *call;
719 	char buf[L2TP_AVP_MAXSIZ], errmsg[256];
720 	time_t curr_time;
721 	u_char *pkt0;
722 	char ifname[IF_NAMESIZE], phy_label[256];
723 	struct l2tp_header hdr;
724 	char hbuf[NI_MAXHOST + NI_MAXSERV + 16];
725 
726 	ctrl = NULL;
727 	curr_time = get_monosec();
728 	pkt0 = pkt;
729 
730 	L2TP_CTRL_ASSERT(peer->sa_family == sock->sa_family);
731 	L2TP_CTRL_ASSERT(peer->sa_family == AF_INET ||
732 	    peer->sa_family == AF_INET6)
733     /*
734      * Parse L2TP Header
735      */
736 	memset(&hdr, 0, sizeof(hdr));
737 	if (pktlen < 2) {
738 		snprintf(errmsg, sizeof(errmsg), "a short packet.  "
739 		    "length=%d", pktlen);
740 		goto bad_packet;
741 	}
742 	memcpy(&hdr, pkt, 2);
743 	pkt += 2;
744 	if (hdr.ver != L2TP_HEADER_VERSION_RFC2661) {
745 		/* XXX: only RFC2661 is supported */
746 		snprintf(errmsg, sizeof(errmsg),
747 		    "Unsupported version at header = %d", hdr.ver);
748 		goto bad_packet;
749 	}
750 	is_ctrl = (hdr.t != 0)? 1 : 0;
751 
752 	/* calc required length */
753 	reqlen = 6;		/* for Flags, Tunnel-Id, Session-Id field */
754 	if (hdr.l) reqlen += 2;	/* for Length field (opt) */
755 	if (hdr.s) reqlen += 4;	/* for Ns, Nr field (opt) */
756 	if (hdr.o) reqlen += 2;	/* for Offset Size field (opt) */
757 	if (reqlen > pktlen) {
758 		snprintf(errmsg, sizeof(errmsg),
759 		    "a short packet. length=%d", pktlen);
760 		goto bad_packet;
761 	}
762 
763 	if (hdr.l != 0) {
764 		GETSHORT(hdr.length, pkt);
765 		if (hdr.length > pktlen) {
766 			snprintf(errmsg, sizeof(errmsg),
767 			    "Actual packet size is smaller than the length "
768 			    "field %d < %d", pktlen, hdr.length);
769 			goto bad_packet;
770 		}
771 		pktlen = hdr.length;	/* remove trailing trash */
772 	}
773 	GETSHORT(hdr.tunnel_id, pkt);
774 	GETSHORT(hdr.session_id, pkt);
775 	if (hdr.s != 0) {
776 		GETSHORT(hdr.ns, pkt);
777 		GETSHORT(hdr.nr, pkt);
778 	}
779 	if (hdr.o != 0) {
780 		GETSHORT(offsiz, pkt);
781 		if (pktlen < offsiz) {
782 			snprintf(errmsg, sizeof(errmsg),
783 			    "offset field is bigger than remaining packet "
784 			    "length %d > %d", offsiz, pktlen);
785 			goto bad_packet;
786 		}
787 		pkt += offsiz;
788 	}
789 	L2TP_CTRL_ASSERT(pkt - pkt0 == reqlen);
790 	pktlen -= (pkt - pkt0);	/* cut down the length of header */
791 
792 	ctrl = NULL;
793 	memset(buf, 0, sizeof(buf));
794 	mestype = 0;
795 	avp = NULL;
796 
797 	if (is_ctrl) {
798 		avp0 = (struct l2tp_avp *)buf;
799 		avp = avp_find_message_type_avp(avp0, pkt, pktlen);
800 		if (avp != NULL)
801 			mestype = avp->attr_value[0] << 8 | avp->attr_value[1];
802 	}
803 	ctrl = l2tpd_get_ctrl(_this, hdr.tunnel_id);
804 
805 	if (ctrl == NULL) {
806 		/* new control */
807 		if (!is_ctrl) {
808 			snprintf(errmsg, sizeof(errmsg),
809 			    "bad data message: tunnelId=%d is not "
810 			    "found.", hdr.tunnel_id);
811 			goto bad_packet;
812 		}
813 		if (mestype != L2TP_AVP_MESSAGE_TYPE_SCCRQ) {
814 			snprintf(errmsg, sizeof(errmsg),
815 			    "bad control message: tunnelId=%d is not "
816 			    "found.  mestype=%s", hdr.tunnel_id,
817 			    avp_mes_type_string(mestype));
818 			goto bad_packet;
819 		}
820 
821 		strlcpy(phy_label,
822 		    ((l2tpd_listener *)slist_get(&_this->listener,
823 		    listener_index))->phy_label, sizeof(phy_label));
824 		if (_this->phy_label_with_ifname != 0) {
825 			if (get_ifname_by_sockaddr(sock, ifname) == NULL) {
826 				l2tpd_log_access_deny(_this,
827 				    "could not get interface informations",
828 				    peer);
829 				goto fail;
830 			}
831 			if (l2tpd_config_str_equal(_this,
832 			    config_key_prefix("l2tpd.interface", ifname),
833 			    "accept", 0)){
834 				strlcat(phy_label, "%", sizeof(phy_label));
835 				strlcat(phy_label, ifname, sizeof(phy_label));
836 			} else if (l2tpd_config_str_equal(_this,
837 			    config_key_prefix("l2tpd.interface", "any"),
838 			    "accept", 0)){
839 			} else {
840 				/* the interface is not permited */
841 				snprintf(errmsg, sizeof(errmsg),
842 				    "'%s' is not allowed by config.", ifname);
843 				l2tpd_log_access_deny(_this, errmsg, peer);
844 				goto fail;
845 			}
846 		}
847 
848 		if ((ctrl = l2tp_ctrl_create()) == NULL) {
849 			l2tp_ctrl_log(ctrl, LOG_ERR,
850 			    "l2tp_ctrl_create() failed: %m");
851 			goto fail;
852 		}
853 		if (l2tp_ctrl_init(ctrl, _this, peer, sock, nat_t_ctx) != 0) {
854 			l2tp_ctrl_log(ctrl, LOG_ERR,
855 			    "l2tp_ctrl_start() failed: %m");
856 			goto fail;
857 		}
858 
859 		ctrl->listener_index = listener_index;
860 		strlcpy(ctrl->phy_label, phy_label, sizeof(ctrl->phy_label));
861 		l2tp_ctrl_reload(ctrl);
862 	} else {
863 		/*
864 		 * treat as an error if src address and port is not
865 		 * match. (because it is potentially DoS attach)
866 		 */
867 		int notmatch = 0;
868 
869 		if (ctrl->peer.ss_family != peer->sa_family)
870 			notmatch = 1;
871 		else if (peer->sa_family == AF_INET) {
872 			if (SIN(peer)->sin_addr.s_addr !=
873 			    SIN(&ctrl->peer)->sin_addr.s_addr ||
874 			    SIN(peer)->sin_port != SIN(&ctrl->peer)->sin_port)
875 				notmatch = 1;
876 		} else if (peer->sa_family == AF_INET6) {
877 			if (!IN6_ARE_ADDR_EQUAL(&(SIN6(peer)->sin6_addr),
878 				    &(SIN6(&ctrl->peer)->sin6_addr)) ||
879 			    SIN6(peer)->sin6_port !=
880 				    SIN6(&ctrl->peer)->sin6_port)
881 				notmatch = 1;
882  		}
883 		if (notmatch) {
884 			snprintf(errmsg, sizeof(errmsg),
885 			    "tunnelId=%u is already assigned for %s",
886 			    hdr.tunnel_id, addrport_tostring(
887 				(struct sockaddr *)&ctrl->peer,
888 				ctrl->peer.ss_len, hbuf, sizeof(hbuf)));
889 			goto bad_packet;
890 		}
891 	}
892 	ctrl->last_rcv = curr_time;
893 	call = NULL;
894 	if (hdr.session_id != 0) {
895 		/* search l2tp_call by Session ID */
896 		/* linear search is enough for this purpose */
897 		len = slist_length(&ctrl->call_list);
898 		for (i = 0; i < len; i++) {
899 			call = slist_get(&ctrl->call_list, i);
900 			if (call->session_id == hdr.session_id)
901 				break;
902 			call = NULL;
903 		}
904 	}
905 	if (!is_ctrl) {
906 		/* L2TP data */
907 		if (ctrl->state != L2TP_CTRL_STATE_ESTABLISHED) {
908 			l2tp_ctrl_log(ctrl, LOG_WARNING,
909 			    "Received Data packet in '%s'",
910 			    l2tp_ctrl_state_string(ctrl));
911 			goto fail;
912 		}
913 		if (call == NULL) {
914 			l2tp_ctrl_log(ctrl, LOG_WARNING,
915 			    "Received a data packet but it has no call.  "
916 			    "session_id=%u",  hdr.session_id);
917 			goto fail;
918 		}
919 		L2TP_CTRL_DBG((ctrl, DEBUG_LEVEL_2,
920 		    "call=%u RECV   ns=%u nr=%u snd_nxt=%u rcv_nxt=%u len=%d",
921 		    call->id, hdr.ns, hdr.nr, call->snd_nxt, call->rcv_nxt,
922 		    pktlen));
923 		if (call->state != L2TP_CALL_STATE_ESTABLISHED){
924 			l2tp_ctrl_log(ctrl, LOG_WARNING,
925 			    "Received a data packet but call is not "
926 			    "established");
927 			goto fail;
928 		}
929 
930 		if (hdr.s != 0) {
931 			if (SEQ_LT(hdr.ns, call->rcv_nxt)) {
932 				/* sequence number seems to rewind */
933 				/* XXX: need to log? */
934 				L2TP_CTRL_DBG((ctrl, LOG_DEBUG,
935 				    "receive a out of sequence data packet: "
936 				    "%u < %u.  ", hdr.ns, call->rcv_nxt));
937 				return;
938 			}
939 			call->rcv_nxt = hdr.ns + 1;
940 		}
941 		l2tp_call_ppp_input(call, pkt, pktlen);
942 
943 		return;
944 	}
945 	if (hdr.s != 0) {
946 		L2TP_CTRL_DBG((ctrl, DEBUG_LEVEL_2,
947 		    "RECV %s ns=%u nr=%u snd_nxt=%u snd_una=%u rcv_nxt=%u "
948 		    "len=%d", (is_ctrl)? "C" : "", hdr.ns, hdr.nr,
949 		    ctrl->snd_nxt, ctrl->snd_una, ctrl->rcv_nxt, pktlen));
950 
951 		if (pktlen <= 0)
952 			l2tp_ctrl_log(ctrl, LOG_INFO, "RecvZLB");
953 
954 		if (SEQ_GT(hdr.nr, ctrl->snd_una)) {
955 			if (hdr.nr == ctrl->snd_nxt ||
956 			    SEQ_LT(hdr.nr, ctrl->snd_nxt))
957 				ctrl->snd_una = hdr.nr;
958 			else {
959 				l2tp_ctrl_log(ctrl, LOG_INFO,
960 				    "Received message has bad Nr field: "
961 				    "%u < %u.", hdr.ns, ctrl->snd_nxt);
962 				/* XXX Drop with ZLB? */
963 				goto fail;
964 			}
965 		}
966 		if (l2tp_ctrl_txwin_size(ctrl) <= 0) {
967 			/* no waiting ack */
968 			if (ctrl->hello_wait_ack != 0) {
969 				/*
970 				 * Reset Hello state, as an ack for the Hello
971 				 * is recived.
972 				 */
973 				ctrl->hello_wait_ack = 0;
974 				ctrl->hello_io_time = curr_time;
975 			}
976 			switch (ctrl->state) {
977 			case L2TP_CTRL_STATE_CLEANUP_WAIT:
978 				l2tp_ctrl_stop(ctrl, 0);
979 				return;
980 			}
981 		}
982 		if (hdr.ns != ctrl->rcv_nxt) {
983 			/* there are remaining packet */
984 			if (l2tp_ctrl_resend_una_packets(ctrl) <= 0) {
985 				/* resend or sent ZLB */
986 				l2tp_ctrl_send_ZLB(ctrl);
987 			}
988 #ifdef	L2TP_CTRL_DEBUG
989 			if (pktlen != 0) {	/* not ZLB */
990 				L2TP_CTRL_DBG((ctrl, LOG_DEBUG,
991 				    "receive out of sequence %u must be %u.  "
992 				    "mestype=%s", hdr.ns, ctrl->rcv_nxt,
993 				    avp_mes_type_string(mestype)));
994 			}
995 #endif
996 			return;
997 		}
998 		if (pktlen <= 0)
999 			return;		/* ZLB */
1000 
1001 		if (l2tp_ctrl_txwin_is_full(ctrl)) {
1002 			L2TP_CTRL_DBG((ctrl, LOG_DEBUG,
1003 			    "Received message cannot be handled. "
1004 			    "Transmission window is full."));
1005 			l2tp_ctrl_send_ZLB(ctrl);
1006 			return;
1007 		}
1008 
1009 		ctrl->rcv_nxt++;
1010 		if (avp == NULL) {
1011 			l2tpd_log(_this, LOG_WARNING,
1012 			    "bad control message: no message-type AVP.");
1013 			goto fail;
1014 		}
1015 	}
1016 
1017     /*
1018      * state machine (RFC2661 pp. 56-57)
1019      */
1020 	switch (ctrl->state) {
1021 	case L2TP_CTRL_STATE_IDLE:
1022 		switch (mestype) {
1023 		case L2TP_AVP_MESSAGE_TYPE_SCCRQ:
1024 			if (l2tp_ctrl_recv_SCCRQ(ctrl, pkt, pktlen, _this,
1025 			    peer) == 0) {
1026 				/* acceptable */
1027 				l2tp_ctrl_send_SCCRP(ctrl);
1028 				ctrl->state = L2TP_CTRL_STATE_WAIT_CTL_CONN;
1029 				return;
1030 			}
1031 			/*
1032 			 * in case un-acceptable, it was already processed
1033 			 * at l2tcp_ctrl_recv_SCCRQ
1034 			 */
1035 			return;
1036 		case L2TP_AVP_MESSAGE_TYPE_SCCRP:
1037 			/*
1038 			 * RFC specifies that sent of StopCCN in the state,
1039 			 * However as this implementation only support Passive
1040 			 * open, this packet will not received.
1041 			 */
1042 			/* FALLTHROUGH */
1043 		case L2TP_AVP_MESSAGE_TYPE_SCCCN:
1044 		default:
1045 			break;
1046 		}
1047 		goto fsm_fail;
1048 
1049 	case L2TP_CTRL_STATE_WAIT_CTL_CONN:
1050 	    /* Wait-Ctl-Conn */
1051 		switch (mestype) {
1052 		case L2TP_AVP_MESSAGE_TYPE_SCCCN:
1053 			l2tp_ctrl_log(ctrl, LOG_INFO, "RecvSCCN");
1054 			if (l2tp_ctrl_send_ZLB(ctrl) == 0) {
1055 				ctrl->state = L2TP_CTRL_STATE_ESTABLISHED;
1056 			}
1057 			return;
1058 		case L2TP_AVP_MESSAGE_TYPE_StopCCN:
1059 			goto receive_stop_ccn;
1060 		case L2TP_AVP_MESSAGE_TYPE_SCCRQ:
1061 		case L2TP_AVP_MESSAGE_TYPE_SCCRP:
1062 		default:
1063 			break;
1064 		}
1065 		break;	/* fsm_fail */
1066 	case L2TP_CTRL_STATE_ESTABLISHED:
1067 	    /* Established */
1068 		switch (mestype) {
1069 		case L2TP_AVP_MESSAGE_TYPE_SCCCN:
1070 		case L2TP_AVP_MESSAGE_TYPE_SCCRQ:
1071 		case L2TP_AVP_MESSAGE_TYPE_SCCRP:
1072 			break;
1073 receive_stop_ccn:
1074 		case L2TP_AVP_MESSAGE_TYPE_StopCCN:
1075 			if (l2tp_ctrl_recv_StopCCN(ctrl, pkt, pktlen) == 0) {
1076 				if (l2tp_ctrl_resend_una_packets(ctrl) <= 0)
1077 					l2tp_ctrl_send_ZLB(ctrl);
1078 				l2tp_ctrl_stop(ctrl, 0);
1079 				return;
1080 			}
1081 			l2tp_ctrl_log(ctrl, LOG_ERR, "Received bad StopCCN");
1082 			l2tp_ctrl_send_ZLB(ctrl);
1083 			l2tp_ctrl_stop(ctrl, 0);
1084 			return;
1085 
1086 		case L2TP_AVP_MESSAGE_TYPE_HELLO:
1087 			if (l2tp_ctrl_resend_una_packets(ctrl) <= 0)
1088 				l2tp_ctrl_send_ZLB(ctrl);
1089 			return;
1090 		case L2TP_AVP_MESSAGE_TYPE_CDN:
1091 		case L2TP_AVP_MESSAGE_TYPE_ICRP:
1092 		case L2TP_AVP_MESSAGE_TYPE_ICCN:
1093 			if (call == NULL) {
1094 				l2tp_ctrl_log(ctrl, LOG_INFO,
1095 				    "Unknown call message: %s",
1096 				    avp_mes_type_string(mestype));
1097 				goto fail;
1098 			}
1099 			/* FALLTHROUGH */
1100 		case L2TP_AVP_MESSAGE_TYPE_ICRQ:
1101 			l2tp_call_recv_packet(ctrl, call, mestype, pkt,
1102 			    pktlen);
1103 			return;
1104 		default:
1105 			break;
1106 		}
1107 		break;	/* fsm_fail */
1108 	case L2TP_CTRL_STATE_CLEANUP_WAIT:
1109 		if (mestype == L2TP_AVP_MESSAGE_TYPE_StopCCN) {
1110 			/*
1111 			 * We left ESTABLISHED state, but the peer sent StopCCN.
1112 			 */
1113 			goto receive_stop_ccn;
1114 		}
1115 		break;	/* fsm_fail */
1116 	}
1117 
1118 fsm_fail:
1119 	/* state machine error */
1120 	l2tp_ctrl_log(ctrl, LOG_WARNING, "Received %s in '%s' state",
1121 	    avp_mes_type_string(mestype), l2tp_ctrl_state_string(ctrl));
1122 	l2tp_ctrl_stop(ctrl, L2TP_STOP_CCN_RCODE_FSM_ERROR);
1123 
1124 	return;
1125 fail:
1126 	if (ctrl != NULL && mestype != 0) {
1127 		l2tp_ctrl_log(ctrl, LOG_WARNING, "Received %s in '%s' state",
1128 		    avp_mes_type_string(mestype), l2tp_ctrl_state_string(ctrl));
1129 		l2tp_ctrl_stop(ctrl, L2TP_STOP_CCN_RCODE_GENERAL_ERROR);
1130 	}
1131 	return;
1132 
1133 bad_packet:
1134 	l2tpd_log(_this, LOG_INFO, "Received from=%s: %s",
1135 	    addrport_tostring(peer, peer->sa_len, hbuf, sizeof(hbuf)), errmsg);
1136 
1137 	return;
1138 }
1139 
1140 static inline int
1141 l2tp_ctrl_txwin_size(l2tp_ctrl *_this)
1142 {
1143 	uint16_t sz;
1144 
1145 	sz = _this->snd_nxt - _this->snd_una;
1146 
1147 	L2TP_CTRL_ASSERT(sz <= _this->winsz);
1148 
1149 	return sz;
1150 }
1151 
1152 static inline int
1153 l2tp_ctrl_txwin_is_full(l2tp_ctrl *_this)
1154 {
1155 	return (l2tp_ctrl_txwin_size(_this) >= _this->winsz)? 1 : 0;
1156 }
1157 
1158 /* send control packet */
1159 int
1160 l2tp_ctrl_send_packet(l2tp_ctrl *_this, int call_id, bytebuffer *bytebuf,
1161     int is_ctrl)
1162 {
1163 	struct l2tp_header *hdr;
1164 	int rval, use_seq;
1165 	time_t curr_time;
1166 
1167 	curr_time = get_monosec();
1168 
1169 #ifdef L2TP_DATA_WITH_SEQUENCE
1170 	use_seq = 1;
1171 #else
1172 	use_seq = is_ctrl;
1173 #endif
1174 
1175 	bytebuffer_flip(bytebuf);
1176 	hdr = (struct l2tp_header *)bytebuffer_pointer(bytebuf);
1177 	memset(hdr, 0, sizeof(*hdr));
1178 
1179 	hdr->t = 1;
1180 	hdr->ver = L2TP_HEADER_VERSION_RFC2661;
1181 	hdr->l = 1;
1182 	hdr->length = htons(bytebuffer_remaining(bytebuf));
1183 	hdr->tunnel_id = htons(_this->peer_tunnel_id);
1184 	hdr->session_id = htons(call_id);
1185 
1186 	hdr->s = 1;
1187 	hdr->ns = htons(_this->snd_nxt);
1188 	hdr->nr = htons(_this->rcv_nxt);
1189 
1190 	if (is_ctrl &&
1191 	    bytebuffer_remaining(bytebuf) > sizeof(struct l2tp_header))
1192 		/* Not ZLB */
1193 		_this->snd_nxt++;
1194 
1195 	L2TP_CTRL_DBG((_this, DEBUG_LEVEL_2,
1196 	    "SEND %s ns=%u nr=%u snd_nxt=%u snd_una=%u rcv_nxt=%u ",
1197 	    (is_ctrl)? "C" : " ", ntohs(hdr->ns), htons(hdr->nr),
1198 	    _this->snd_nxt, _this->snd_una, _this->rcv_nxt));
1199 
1200 	if (_this->l2tpd->ctrl_out_pktdump != 0) {
1201 		l2tpd_log(_this->l2tpd, LOG_DEBUG,
1202 		    "L2TP Control output packet dump");
1203 		show_hd(debug_get_debugfp(), bytebuffer_pointer(bytebuf),
1204 		    bytebuffer_remaining(bytebuf));
1205 	}
1206 
1207 	if ((rval = l2tp_ctrl_send(_this, bytebuffer_pointer(bytebuf),
1208 	    bytebuffer_remaining(bytebuf))) < 0) {
1209 		L2TP_CTRL_DBG((_this, LOG_DEBUG, "sendto() failed: %m"));
1210 	}
1211 
1212 	_this->last_snd_ctrl = curr_time;
1213 
1214 	return (rval == bytebuffer_remaining(bytebuf))? 0 : 1;
1215 }
1216 
1217 /*
1218  * receiver SCCRQ
1219  */
1220 static int
1221 l2tp_ctrl_recv_SCCRQ(l2tp_ctrl *_this, u_char *pkt, int pktlen, l2tpd *_l2tpd,
1222     struct sockaddr *peer)
1223 {
1224 	int avpsz, len, protover, protorev, firmrev, result;
1225 	struct l2tp_avp *avp;
1226 	char host[NI_MAXHOST], serv[NI_MAXSERV];
1227 	char buf[L2TP_AVP_MAXSIZ], emes[256], hostname[256], vendorname[256];
1228 
1229 	result = L2TP_STOP_CCN_RCODE_GENERAL_ERROR;
1230 	strlcpy(hostname, "(no hostname)", sizeof(hostname));
1231 	strlcpy(vendorname, "(no vendorname)", sizeof(vendorname));
1232 
1233 	firmrev = 0;
1234 	protover = 0;
1235 	protorev = 0;
1236 	avp = (struct l2tp_avp *)buf;
1237 	while (pktlen >= 6 && (avpsz = avp_enum(avp, pkt, pktlen, 1)) > 0) {
1238 		pkt += avpsz;
1239 		pktlen -= avpsz;
1240 		if (avp->vendor_id != 0) {
1241 			L2TP_CTRL_DBG((_this, LOG_DEBUG,
1242 			    "Received a Vendor-specific AVP vendor-id=%d "
1243 			    "type=%d", avp->vendor_id, avp->attr_type));
1244 			continue;
1245 		}
1246 		switch (avp->attr_type) {
1247 		case L2TP_AVP_TYPE_MESSAGE_TYPE:
1248 			AVP_SIZE_CHECK(avp, ==, 8);
1249 			continue;
1250 		case L2TP_AVP_TYPE_PROTOCOL_VERSION:
1251 			AVP_SIZE_CHECK(avp, ==, 8);
1252 			protover = avp->attr_value[0];
1253 			protorev = avp->attr_value[1];
1254 
1255 			if (protover != L2TP_RFC2661_VERSION ||
1256 			    protorev != L2TP_RFC2661_REVISION) {
1257 				result = L2TP_STOP_CCN_RCODE_GENERAL_ERROR;
1258 				snprintf(emes, sizeof(emes),
1259 				    "Peer's protocol version is not supported:"
1260 				    " %d.%d", protover, protorev);
1261 				goto not_acceptable;
1262 			}
1263 			continue;
1264 		case L2TP_AVP_TYPE_FRAMING_CAPABILITIES:
1265 			AVP_SIZE_CHECK(avp, ==, 10);
1266 			if ((avp_get_val32(avp) & L2TP_FRAMING_CAP_FLAGS_SYNC)
1267 			    == 0) {
1268 				L2TP_CTRL_DBG((_this, LOG_DEBUG, "Peer doesn't "
1269 				    "support synchronous framing"));
1270 			}
1271 			continue;
1272 		case L2TP_AVP_TYPE_BEARER_CAPABILITIES:
1273 			AVP_SIZE_CHECK(avp, ==, 10);
1274 			continue;
1275 		case L2TP_AVP_TYPE_TIE_BREAKER:
1276 			AVP_SIZE_CHECK(avp, ==, 14);
1277 			/*
1278 			 * As the implementation never send SCCRQ,
1279 			 * the peer is always winner
1280 			 */
1281 			continue;
1282 		case L2TP_AVP_TYPE_FIRMWARE_REVISION:
1283 			AVP_SIZE_CHECK(avp, >=, 6);
1284 			firmrev = avp_get_val16(avp);
1285 			continue;
1286 		case L2TP_AVP_TYPE_HOST_NAME:
1287 			AVP_SIZE_CHECK(avp, >, 4);
1288 			len = MIN(sizeof(hostname) - 1, avp->length - 6);
1289 			memcpy(hostname, avp->attr_value, len);
1290 			hostname[len] = '\0';
1291 			continue;
1292 		case L2TP_AVP_TYPE_VENDOR_NAME:
1293 			AVP_SIZE_CHECK(avp, >, 4);
1294 			len = MIN(sizeof(vendorname) - 1, avp->length - 6);
1295 			memcpy(vendorname, avp->attr_value, len);
1296 			vendorname[len] = '\0';
1297 			continue;
1298 		case L2TP_AVP_TYPE_ASSINGED_TUNNEL_ID:
1299 			AVP_SIZE_CHECK(avp, ==, 8);
1300 			_this->peer_tunnel_id = avp_get_val16(avp);
1301 			continue;
1302 		case L2TP_AVP_TYPE_RECV_WINDOW_SIZE:
1303 			AVP_SIZE_CHECK(avp, ==, 8);
1304 			_this->peer_winsz = avp_get_val16(avp);
1305 			continue;
1306 		}
1307 		if (avp->is_mandatory) {
1308 			l2tp_ctrl_log(_this, LOG_WARNING,
1309 			    "Received AVP (%s/%d) is not supported, but it's "
1310 			    "mandatory", avp_attr_type_string(avp->attr_type),
1311 			    avp->attr_type);
1312 #ifdef L2TP_CTRL_DEBUG
1313 		} else {
1314 			L2TP_CTRL_DBG((_this, LOG_DEBUG,
1315 			    "AVP (%s/%d) is not handled",
1316 			    avp_attr_type_string(avp->attr_type),
1317 			    avp->attr_type));
1318 #endif
1319 		}
1320 	}
1321 	if (getnameinfo((struct sockaddr *)&_this->peer, _this->peer.ss_len,
1322 	    host, sizeof(host), serv, sizeof(serv),
1323 	    NI_NUMERICHOST | NI_NUMERICSERV | NI_DGRAM) != 0) {
1324 		l2tp_ctrl_log(_this, LOG_ERR,
1325 		    "getnameinfo() failed at %s(): %m", __func__);
1326 		strlcpy(host, "error", sizeof(host));
1327 		strlcpy(serv, "error", sizeof(serv));
1328 	}
1329 	l2tp_ctrl_log(_this, LOG_NOTICE, "logtype=Started RecvSCCRQ "
1330 	    "from=%s:%s/udp tunnel_id=%u/%u protocol=%d.%d winsize=%d "
1331 	    "hostname=%s vendor=%s firm=%04X", host, serv, _this->tunnel_id,
1332 	    _this->peer_tunnel_id, protover, protorev, _this->peer_winsz,
1333 	    hostname, vendorname, firmrev);
1334 
1335 	return 0;
1336 not_acceptable:
1337 size_check_failed:
1338 	l2tp_ctrl_log(_this, LOG_ERR, "Received bad SCCRQ: %s", emes);
1339 	l2tp_ctrl_stop(_this, result);
1340 
1341 	return 1;
1342 }
1343 
1344 /*
1345  * send StopCCN
1346  */
1347 static int
1348 l2tp_ctrl_send_StopCCN(l2tp_ctrl *_this, int result)
1349 {
1350 	struct l2tp_avp *avp;
1351 	char buf[L2TP_AVP_MAXSIZ];
1352 	bytebuffer *bytebuf;
1353 
1354 	if ((bytebuf = l2tp_ctrl_prepare_snd_buffer(_this, 1)) == NULL) {
1355 		l2tp_ctrl_log(_this, LOG_ERR,
1356 		    "sending StopCCN failed: no buffer.");
1357 		return -1;
1358 	}
1359 	avp = (struct l2tp_avp *)buf;
1360 
1361 	/* Message Type = StopCCN */
1362 	memset(avp, 0, sizeof(*avp));
1363 	avp->is_mandatory = 1;
1364 	avp->attr_type = L2TP_AVP_TYPE_MESSAGE_TYPE;
1365 	avp_set_val16(avp, L2TP_AVP_MESSAGE_TYPE_StopCCN);
1366 	bytebuf_add_avp(bytebuf, avp, 2);
1367 
1368 	/* Assigned Tunnel Id */
1369 	memset(avp, 0, sizeof(*avp));
1370 	avp->is_mandatory = 1;
1371 	avp->attr_type = L2TP_AVP_TYPE_ASSINGED_TUNNEL_ID;
1372 	avp_set_val16(avp, _this->tunnel_id);
1373 	bytebuf_add_avp(bytebuf, avp, 2);
1374 
1375 	/* Result Code */
1376 	memset(avp, 0, sizeof(*avp));
1377 	avp->is_mandatory = 1;
1378 	avp->attr_type = L2TP_AVP_TYPE_RESULT_CODE;
1379 	avp_set_val16(avp, result);
1380 	bytebuf_add_avp(bytebuf, avp, 2);
1381 
1382 	if (l2tp_ctrl_send_packet(_this, 0, bytebuf, 1) != 0) {
1383 		l2tp_ctrl_log(_this, LOG_ERR, "sending CCN failed");
1384 		return - 1;
1385 	}
1386 	l2tp_ctrl_log(_this, LOG_INFO, "SendStopCCN result=%d", result);
1387 
1388 	return 0;
1389 }
1390 
1391 /*
1392  * Receiver StopCCN
1393  */
1394 static int
1395 l2tp_ctrl_recv_StopCCN(l2tp_ctrl *_this, u_char *pkt, int pktlen)
1396 {
1397 	int avpsz;
1398 	uint32_t val32;
1399 	uint16_t rcode, tunid, ecode;
1400 	struct l2tp_avp *avp;
1401 	char buf[L2TP_AVP_MAXSIZ + 16], emes[256], peermes[256];
1402 
1403 	rcode = 0;
1404 	ecode = 0;
1405 	tunid = 0;
1406 	peermes[0] = '\0';
1407 	avp = (struct l2tp_avp *)buf;
1408 	while (pktlen >= 6 && (avpsz = avp_enum(avp, pkt, pktlen, 1)) > 0) {
1409 		pkt += avpsz;
1410 		pktlen -= avpsz;
1411 		if (avp->vendor_id != 0) {
1412 			L2TP_CTRL_DBG((_this, LOG_DEBUG,
1413 			    "Received a Vendor-specific AVP vendor-id=%d "
1414 			    "type=%d", avp->vendor_id, avp->attr_type));
1415 			continue;
1416 		}
1417 		if (avp->is_hidden != 0) {
1418 			l2tp_ctrl_log(_this, LOG_WARNING,
1419 			    "Received AVP (%s/%d) is hidden.  But we don't "
1420 			    "share secret.",
1421 			    avp_attr_type_string(avp->attr_type),
1422 			    avp->attr_type);
1423 			if (avp->is_mandatory != 0) {
1424 				l2tp_ctrl_stop(_this,
1425 				    L2TP_STOP_CCN_RCODE_GENERAL_ERROR |
1426 				    L2TP_ECODE_UNKNOWN_MANDATORY_AVP);
1427 				return 1;
1428 			}
1429 			continue;
1430 		}
1431 		switch (avp->attr_type) {
1432 		case L2TP_AVP_TYPE_MESSAGE_TYPE:
1433 			AVP_SIZE_CHECK(avp, ==, 8);
1434 			continue;
1435 		case L2TP_AVP_TYPE_RESULT_CODE:
1436 			AVP_SIZE_CHECK(avp, >=, 10);
1437 			val32 = avp_get_val32(avp);
1438 			rcode = val32 >> 16;
1439 			ecode = val32 & 0xffff;
1440 			if (avp->length > 10) {
1441 				avp->attr_value[avp->length - 6] = '\0';
1442 				strlcpy(peermes,
1443 				    (const char *)avp->attr_value + 4,
1444 				    sizeof(peermes));
1445 			}
1446 			continue;
1447 		case L2TP_AVP_TYPE_ASSINGED_TUNNEL_ID:
1448 			AVP_SIZE_CHECK(avp, ==, 8);
1449 			tunid = avp_get_val16(avp);
1450 			continue;
1451 		default:
1452 			if (avp->is_mandatory != 0) {
1453 				l2tp_ctrl_log(_this, LOG_WARNING,
1454 				    "Received AVP (%s/%d) is not supported, "
1455 				    "but it's mandatory",
1456 				    avp_attr_type_string(avp->attr_type),
1457 				    avp->attr_type);
1458 #ifdef L2TP_CTRL_DEBUG
1459 			} else {
1460 				L2TP_CTRL_DBG((_this, LOG_DEBUG,
1461 				    "AVP (%s/%d) is not handled",
1462 				    avp_attr_type_string(avp->attr_type),
1463 				    avp->attr_type));
1464 #endif
1465 			}
1466 		}
1467 	}
1468 
1469 	if (rcode == L2TP_CDN_RCODE_ERROR_CODE &&
1470 	    ecode == L2TP_ECODE_NO_RESOURCE) {
1471 		/*
1472 		 * Memo:
1473 		 * This state may be happen in following state.
1474 		 * - lots of connect/disconect by long-running
1475 		 *   windows2000, sometimes it fall to this state.
1476 		 *   Once it fall to here, connection will fail till
1477 		 *   the windows rebooted
1478 		 */
1479 		l2tp_ctrl_log(_this, LOG_WARNING,
1480 		    "Peer indicates \"No Resource\" error.");
1481 	}
1482 
1483 	l2tp_ctrl_log(_this, LOG_INFO, "RecvStopCCN result=%s/%u "
1484 	    "error=%s/%u tunnel_id=%u message=\"%s\"",
1485 	    l2tp_stopccn_rcode_string(rcode), rcode, l2tp_ecode_string(ecode),
1486 	    ecode, tunid, peermes);
1487 
1488 	return 0;
1489 
1490 size_check_failed:
1491 	l2tp_ctrl_log(_this, LOG_ERR, "Received bad StopCCN: %s", emes);
1492 
1493 	return -1;
1494 }
1495 
1496 /*
1497  * send SCCRP
1498  */
1499 static void
1500 l2tp_ctrl_send_SCCRP(l2tp_ctrl *_this)
1501 {
1502 	int len;
1503 	struct l2tp_avp *avp;
1504 	char buf[L2TP_AVP_MAXSIZ];
1505 	const char *val;
1506 	bytebuffer *bytebuf;
1507 
1508 	if ((bytebuf = l2tp_ctrl_prepare_snd_buffer(_this, 1)) == NULL) {
1509 		l2tp_ctrl_log(_this, LOG_ERR,
1510 		    "sending SCCRP failed: no buffer.");
1511 		return;
1512 	}
1513 	avp = (struct l2tp_avp *)buf;
1514 
1515 	/* Message Type = SCCRP */
1516 	memset(avp, 0, sizeof(*avp));
1517 	avp->is_mandatory = 1;
1518 	avp->attr_type = L2TP_AVP_TYPE_MESSAGE_TYPE;
1519 	avp_set_val16(avp, L2TP_AVP_MESSAGE_TYPE_SCCRP);
1520 	bytebuf_add_avp(bytebuf, avp, 2);
1521 
1522 	/* Protocol Version = 1.0 */
1523 	memset(avp, 0, sizeof(*avp));
1524 	avp->is_mandatory = 1;
1525 	avp->attr_type = L2TP_AVP_TYPE_PROTOCOL_VERSION;
1526 	avp->attr_value[0] = L2TP_RFC2661_VERSION;
1527 	avp->attr_value[1] = L2TP_RFC2661_REVISION;
1528 	bytebuf_add_avp(bytebuf, avp, 2);
1529 
1530 	/* Framing Capability = Async */
1531 	memset(avp, 0, sizeof(*avp));
1532 	avp->is_mandatory = 1;
1533 	avp->attr_type = L2TP_AVP_TYPE_FRAMING_CAPABILITIES;
1534 	avp_set_val32(avp, L2TP_FRAMING_CAP_FLAGS_SYNC);
1535 	bytebuf_add_avp(bytebuf, avp, 4);
1536 
1537 	/* Host Name */
1538 	memset(avp, 0, sizeof(*avp));
1539 	avp->is_mandatory = 1;
1540 	avp->attr_type = L2TP_AVP_TYPE_HOST_NAME;
1541 
1542 	if ((val = l2tp_ctrl_config_str(_this, "l2tp.host_name")) == NULL)
1543 		val = _this->l2tpd->default_hostname;
1544 	if (val[0] == '\0')
1545 		val = "G";	/* XXX magic word, why? ask yasuoka */
1546 	len = strlen(val);
1547 	memcpy(avp->attr_value, val, len);
1548 	bytebuf_add_avp(bytebuf, avp, len);
1549 
1550 	/* Assigned Tunnel Id */
1551 	memset(avp, 0, sizeof(*avp));
1552 	avp->is_mandatory = 1;
1553 	avp->attr_type = L2TP_AVP_TYPE_ASSINGED_TUNNEL_ID;
1554 	avp_set_val16(avp, _this->tunnel_id);
1555 	bytebuf_add_avp(bytebuf, avp, 2);
1556 
1557 	/* Bearer Capability
1558 	 * This implementation never act as LAC.
1559 	 *
1560 	memset(avp, 0, sizeof(*avp));
1561 	avp->is_mandatory = 1;
1562 	avp->attr_type = L2TP_AVP_TYPE_BEARER_CAPABILITIES;
1563 	avp_set_val32(avp, 0);
1564 	bytebuf_add_avp(bytebuf, avp, 4);
1565 	 */
1566 
1567 	/* Firmware Revision */
1568 	memset(avp, 0, sizeof(*avp));
1569 	avp->is_mandatory = 1;
1570 	avp->attr_type = L2TP_AVP_TYPE_FIRMWARE_REVISION;
1571 	avp->attr_value[0] = MAJOR_VERSION;
1572 	avp->attr_value[1] = MINOR_VERSION;
1573 	bytebuf_add_avp(bytebuf, avp, 2);
1574 
1575 	/* Host Name */
1576 	memset(avp, 0, sizeof(*avp));
1577 	avp->is_mandatory = 1;
1578 	avp->attr_type = L2TP_AVP_TYPE_VENDOR_NAME;
1579 
1580 	if ((val = l2tp_ctrl_config_str(_this, "l2tp.vendor_name")) == NULL)
1581 		val =  L2TPD_VENDOR_NAME;
1582 
1583 	len = strlen(val);
1584 	memcpy(avp->attr_value, val, len);
1585 	bytebuf_add_avp(bytebuf, avp, len);
1586 
1587 	/* Window Size */
1588 	memset(avp, 0, sizeof(*avp));
1589 	avp->is_mandatory = 1;
1590 	avp->attr_type = L2TP_AVP_TYPE_RECV_WINDOW_SIZE;
1591 	avp_set_val16(avp, _this->winsz);
1592 	bytebuf_add_avp(bytebuf, avp, 2);
1593 
1594 	if ((l2tp_ctrl_send_packet(_this, 0, bytebuf, 1)) != 0) {
1595 		l2tp_ctrl_log(_this, LOG_ERR, "sending SCCRP failed");
1596 		l2tp_ctrl_stop(_this, L2TP_STOP_CCN_RCODE_GENERAL);
1597 		return;
1598 	}
1599 	l2tp_ctrl_log(_this, LOG_INFO, "SendSCCRP");
1600 }
1601 
1602 static int
1603 l2tp_ctrl_send_HELLO(l2tp_ctrl *_this)
1604 {
1605 	struct l2tp_avp *avp;
1606 	char buf[L2TP_AVP_MAXSIZ];
1607 	bytebuffer *bytebuf;
1608 
1609 	if ((bytebuf = l2tp_ctrl_prepare_snd_buffer(_this, 1)) == NULL) {
1610 		l2tp_ctrl_log(_this, LOG_ERR,
1611 		    "sending SCCRP failed: no buffer.");
1612 		return 1;
1613 	}
1614 	avp = (struct l2tp_avp *)buf;
1615 
1616 	/* Message Type = HELLO */
1617 	memset(avp, 0, sizeof(*avp));
1618 	avp->is_mandatory = 1;
1619 	avp->attr_type = L2TP_AVP_TYPE_MESSAGE_TYPE;
1620 	avp_set_val16(avp, L2TP_AVP_MESSAGE_TYPE_HELLO);
1621 	bytebuf_add_avp(bytebuf, avp, 2);
1622 
1623 	if ((l2tp_ctrl_send_packet(_this, 0, bytebuf, 1)) != 0) {
1624 		l2tp_ctrl_log(_this, LOG_ERR, "sending HELLO failed");
1625 		l2tp_ctrl_stop(_this, L2TP_STOP_CCN_RCODE_GENERAL);
1626 		return 1;
1627 	}
1628 	l2tp_ctrl_log(_this, LOG_DEBUG, "SendHELLO");
1629 
1630 	return 0;
1631 }
1632 
1633 /* Send  ZLB */
1634 static int
1635 l2tp_ctrl_send_ZLB(l2tp_ctrl *_this)
1636 {
1637 	int loglevel;
1638 
1639 	loglevel = (_this->state == L2TP_CTRL_STATE_ESTABLISHED)
1640 	    ? LOG_DEBUG : LOG_INFO;
1641 	l2tp_ctrl_log(_this, loglevel, "SendZLB");
1642 	bytebuffer_clear(_this->zlb_buffer);
1643 	bytebuffer_put(_this->zlb_buffer, BYTEBUFFER_PUT_DIRECT,
1644 	    sizeof(struct l2tp_header));
1645 
1646 	return l2tp_ctrl_send_packet(_this, 0, _this->zlb_buffer, 1);
1647 }
1648 
1649 /*
1650  * Utitlity
1651  */
1652 
1653 /**
1654  * Prepare send buffer
1655  * @return return Null when the send buffer exceed Window.
1656  */
1657 bytebuffer *
1658 l2tp_ctrl_prepare_snd_buffer(l2tp_ctrl *_this, int with_seq)
1659 {
1660 	bytebuffer *bytebuf;
1661 
1662 	L2TP_CTRL_ASSERT(_this != NULL);
1663 
1664 	if (l2tp_ctrl_txwin_is_full(_this)) {
1665 		l2tp_ctrl_log(_this, LOG_INFO, "sending buffer is full.");
1666 		return NULL;
1667 	}
1668 	bytebuf = _this->snd_buffers[_this->snd_nxt % _this->winsz];
1669 	bytebuffer_clear(bytebuf);
1670 	if (with_seq)
1671 		bytebuffer_put(bytebuf, BYTEBUFFER_PUT_DIRECT,
1672 		    sizeof(struct l2tp_header));
1673 	else
1674 		bytebuffer_put(bytebuf, BYTEBUFFER_PUT_DIRECT,
1675 		    offsetof(struct l2tp_header, ns));
1676 
1677 	return bytebuf;
1678 }
1679 
1680 /**
1681  * return current state as strings
1682  */
1683 static inline const char *
1684 l2tp_ctrl_state_string(l2tp_ctrl *_this)
1685 {
1686 	switch (_this->state) {
1687 	case L2TP_CTRL_STATE_IDLE:		return "idle";
1688 	case L2TP_CTRL_STATE_WAIT_CTL_CONN:	return "wait-ctl-conn";
1689 	case L2TP_CTRL_STATE_WAIT_CTL_REPLY:	return "wait-ctl-reply";
1690 	case L2TP_CTRL_STATE_ESTABLISHED:	return "established";
1691 	case L2TP_CTRL_STATE_CLEANUP_WAIT:	return "cleanup-wait";
1692 	}
1693 	return "unknown";
1694 }
1695 
1696 /* logging with the label of the l2tp instance. */
1697 void
1698 l2tp_ctrl_log(l2tp_ctrl *_this, int prio, const char *fmt, ...)
1699 {
1700 	char logbuf[BUFSIZ];
1701 	va_list ap;
1702 
1703 	va_start(ap, fmt);
1704 #ifdef	L2TPD_MULITPLE
1705 	snprintf(logbuf, sizeof(logbuf), "l2tpd id=%u ctrl=%u %s",
1706 	    _this->l2tpd->id, _this->id, fmt);
1707 #else
1708 	snprintf(logbuf, sizeof(logbuf), "l2tpd ctrl=%u %s", _this->id, fmt);
1709 #endif
1710 	vlog_printf(prio, logbuf, ap);
1711 	va_end(ap);
1712 }
1713