summaryrefslogtreecommitdiff
path: root/usr.sbin/npppctl/npppctl.c
blob: 5860ddd91688bbd548b92006706ce86c0cd98c57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/*	$OpenBSD: npppctl.c,v 1.12 2024/11/21 13:08:55 claudio Exp $	*/

/*
 * Copyright (c) 2012 Internet Initiative Japan Inc.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include <sys/queue.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <errno.h>
#include <netdb.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <imsg.h>

#include <unistd.h>
#include <err.h>

#include "parser.h"
#include "npppd_ctl.h"

#define MINIMUM(a, b)	(((a) < (b)) ? (a) : (b))

#ifndef nitems
#define nitems(_x)	(sizeof(_x) / sizeof(_x[0]))
#endif

#define	NMAX_DISCONNECT		2048

static void         usage (void);
static void         show_clear_session (struct parse_result *, FILE *);
static void         monitor_session (struct parse_result *, FILE *);
static void         clear_session (u_int[], int, int, FILE *);
static void         fprint_who_brief (int, struct npppd_who *, FILE *);
static void         fprint_who_packets (int, struct npppd_who *, FILE *);
static void         fprint_who_all (int, struct npppd_who *, FILE *);
static const char  *peerstr (struct sockaddr *, char *, int);
static const char  *humanize_duration (uint32_t, char *, int);
static const char  *humanize_bytes (double, char *, int);
static bool         filter_match(struct parse_result *, struct npppd_who *);
static int          imsg_wait_command_completion (void);

static int             nflag = 0;
static struct imsgbuf  ctl_ibuf;
static struct imsg     ctl_imsg;

static void
usage(void)
{
	extern char		*__progname;

	fprintf(stderr,
	    "usage: %s [-n] [-s socket] command [arg ...]\n", __progname);
}

int
main(int argc, char *argv[])
{
	int			 ch, ctlsock = -1;
	struct parse_result	*result;
	struct sockaddr_un	 sun;
	const char		*npppd_ctlpath = NPPPD_SOCKET;

	while ((ch = getopt(argc, argv, "ns:")) != -1)
		switch (ch) {
		case 'n':
			nflag = 1;
			break;
		case 's':
			npppd_ctlpath = optarg;
			break;
		default:
			usage();
			exit(EXIT_FAILURE);
		}

	argc -= optind;
	argv += optind;

	if ((result = parse(argc, argv)) == NULL)
		exit(EXIT_FAILURE);

	if ((ctlsock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
		err(EXIT_FAILURE, "socket");
	memset(&sun, 0, sizeof(sun));
	sun.sun_family = AF_UNIX;
	strlcpy(sun.sun_path, npppd_ctlpath, sizeof(sun.sun_path));
	if (connect(ctlsock, (struct sockaddr *)&sun, sizeof(sun)) == -1)
		err(EXIT_FAILURE, "connect");

	imsg_init(&ctl_ibuf, ctlsock);

	switch (result->action) {
	case SESSION_BRIEF:
	case SESSION_PKTS:
	case SESSION_ALL:
		show_clear_session(result, stdout);
		break;
	case CLEAR_SESSION:
		if (!result->has_ppp_id)
			show_clear_session(result, stdout);
		else {
			u_int ids[1];
			ids[0] = result->ppp_id;
			clear_session(ids, 1, 1, stdout);
		}
		break;
	case MONITOR_SESSION:
		monitor_session(result, stdout);
		break;
	case NONE:
		break;
	}

	exit(EXIT_SUCCESS);
}

static void
show_clear_session(struct parse_result *result, FILE *out)
{
	int                    i, n, ppp_id_idx;
	struct npppd_who_list *res;
	u_int                  ppp_id[NMAX_DISCONNECT];

	if (imsg_compose(&ctl_ibuf, IMSG_CTL_WHO, 0, 0, -1, NULL, 0) == -1)
		err(EXIT_FAILURE, "failed to compose a message\n");
	if (imsg_wait_command_completion() < 0)
		errx(EXIT_FAILURE, "failed to get response");
	if (ctl_imsg.hdr.type != IMSG_CTL_OK)
		errx(EXIT_FAILURE, "command was fail");
	n = ppp_id_idx = 0;
	while (imsg_wait_command_completion() == IMSG_PPP_START) {
		res = (struct npppd_who_list *)ctl_imsg.data;
		if (ctl_imsg.hdr.len - IMSG_HEADER_SIZE <
		    offsetof(struct npppd_who_list,
			    entry[res->entry_count])) {
			errx(1, "response size %d is too small for "
			    "the entry count %d",
			    (int)(ctl_imsg.hdr.len - IMSG_HEADER_SIZE),
			    res->entry_count);
		}
		for (i = 0; i < res->entry_count; i++, n++) {
			switch (result->action) {
			case SESSION_BRIEF:
				fprint_who_brief(n, &res->entry[i], out);
				break;
			case SESSION_PKTS:
				fprint_who_packets(n, &res->entry[i], out);
				break;
			case SESSION_ALL:
				if (filter_match(result, &res->entry[i]))
					fprint_who_all(n, &res->entry[i], out);
				break;
			case CLEAR_SESSION:
				if (filter_match(result, &res->entry[i])) {
					if (ppp_id_idx < nitems(ppp_id))
						ppp_id[ppp_id_idx] =
						    res->entry[i].ppp_id;
					ppp_id_idx++;
				}
				break;
			default:
				warnx("must not reached here");
				abort();
			}
		}
		if (!res->more_data)
			break;
	}
	if (result->action == CLEAR_SESSION) {
		if (ppp_id_idx > nitems(ppp_id))
			warnx(
			    "Disconnection for %d sessions has been requested, "
			    "but cannot disconnect only %d sessions because of "
			    "the implementation limit.",
			    ppp_id_idx, (int)nitems(ppp_id));
		clear_session(ppp_id, MINIMUM(ppp_id_idx, nitems(ppp_id)),
			ppp_id_idx, out);
	}
}

const char *bar =
"------------------------------------------------------------------------\n";
static void
monitor_session(struct parse_result *result, FILE *out)
{
	int                    i, n;
	struct npppd_who_list *res;

	if (imsg_compose(&ctl_ibuf, IMSG_CTL_MONITOR, 0, 0, -1, NULL, 0) == -1)
		err(EXIT_FAILURE, "failed to compose a message");
	if (imsg_wait_command_completion() < 0)
		errx(EXIT_FAILURE, "failed to get response");
	if (ctl_imsg.hdr.type != IMSG_CTL_OK)
		errx(EXIT_FAILURE, "command was fail");
	do {
		if (imsg_wait_command_completion() < 0)
			break;
		n = 0;
		if (ctl_imsg.hdr.type == IMSG_PPP_START ||
		    ctl_imsg.hdr.type == IMSG_PPP_STOP) {
			res = (struct npppd_who_list *)ctl_imsg.data;
			for (i = 0; i < res->entry_count; i++) {
				if (!filter_match(result, &res->entry[i]))
					continue;
				if (n == 0)
					fprintf(out, "PPP %s\n%s",
					    (ctl_imsg.hdr.type ==
						    IMSG_PPP_START)
						    ? "Started"
						    : "Stopped", bar);
				fprint_who_all(n++, &res->entry[i], out);
			}
			if (n > 0)
				fputs(bar, out);
		} else {
			warnx("received unknown message type = %d",
			    ctl_imsg.hdr.type);
			break;
		}
	} while (true);

	return;
}

static void
fprint_who_brief(int i, struct npppd_who *w, FILE *out)
{
	char buf[BUFSIZ];

	if (i == 0)
		fputs(
"Ppp Id     Assigned IPv4   Username             Proto Tunnel From\n"
"---------- --------------- -------------------- ----- ------------------------"
"-\n",
		    out);
	fprintf(out, "%10u %-15s %-20s %-5s %s\n", w->ppp_id,
	    inet_ntoa(w->framed_ip_address), w->username, w->tunnel_proto,
	    peerstr((struct sockaddr *)&w->tunnel_peer, buf, sizeof(buf)));
}

static void
fprint_who_packets(int i, struct npppd_who *w, FILE *out)
{
	if (i == 0)
		fputs(
"Ppd Id     Username             In(Kbytes/pkts/errs)    Out(Kbytes/pkts/errs)"
"\n"
"---------- -------------------- ----------------------- ----------------------"
"-\n",
		    out);
	fprintf(out, "%10u %-20s %9.1f %7u %5u %9.1f %7u %5u\n", w->ppp_id,
	    w->username,
	    (double)w->ibytes/1024, w->ipackets, w->ierrors,
	    (double)w->obytes/1024, w->opackets, w->oerrors);
}

static void
fprint_who_all(int i, struct npppd_who *w, FILE *out)
{
	struct tm  tm;
	char       ibytes_buf[48], obytes_buf[48], peer_buf[48], time_buf[48];
	char       dur_buf[48];

	localtime_r(&w->time, &tm);
	strftime(time_buf, sizeof(time_buf), "%Y/%m/%d %T", &tm);
	if (i != 0)
		fputs("\n", out);

	fprintf(out,
	    "Ppp Id = %u\n"
	    "          Ppp Id                  : %u\n"
	    "          Username                : %s\n"
	    "          Realm Name              : %s\n"
	    "          Concentrated Interface  : %s\n"
	    "          Assigned IPv4 Address   : %s\n"
	    "          MRU                     : %u\n"
	    "          Tunnel Protocol         : %s\n"
	    "          Tunnel From             : %s\n"
	    "          Start Time              : %s\n"
	    "          Elapsed Time            : %lu sec %s\n"
	    "          Input Bytes             : %llu%s\n"
	    "          Input Packets           : %lu\n"
	    "          Input Errors            : %lu (%.1f%%)\n"
	    "          Output Bytes            : %llu%s\n"
	    "          Output Packets          : %lu\n"
	    "          Output Errors           : %lu (%.1f%%)\n",
	    w->ppp_id, w->ppp_id, w->username, w->rlmname, w->ifname,
	    inet_ntoa(w->framed_ip_address), (u_int)w->mru, w->tunnel_proto,
	    peerstr((struct sockaddr *)&w->tunnel_peer, peer_buf,
		sizeof(peer_buf)), time_buf,
	    (unsigned long)w->duration_sec,
	    humanize_duration(w->duration_sec, dur_buf, sizeof(dur_buf)),
	    (unsigned long long)w->ibytes,
	    humanize_bytes((double)w->ibytes, ibytes_buf, sizeof(ibytes_buf)),
	    (unsigned long)w->ipackets,
	    (unsigned long)w->ierrors,
	    ((w->ipackets + w->ierrors) <= 0)
		? 0.0 : (100.0 * w->ierrors) / (w->ierrors + w->ipackets),
	    (unsigned long long)w->obytes,
	    humanize_bytes((double)w->obytes, obytes_buf, sizeof(obytes_buf)),
	    (unsigned long)w->opackets,
	    (unsigned long)w->oerrors,
	    ((w->opackets + w->oerrors) <= 0)
		? 0.0 : (100.0 * w->oerrors) / (w->oerrors + w->opackets));
}

/***********************************************************************
 * clear session
 ***********************************************************************/
static void
clear_session(u_int ppp_id[], int ppp_id_count, int total, FILE *out)
{
	int                               succ, fail, i, n, nmax;
	struct iovec                      iov[2];
	struct npppd_disconnect_request   req;
	struct npppd_disconnect_response *res;

	succ = fail = 0;
	if (ppp_id_count > 0) {
		nmax = (MAX_IMSGSIZE - IMSG_HEADER_SIZE -
		    offsetof(struct npppd_disconnect_request, ppp_id[0])) /
		    sizeof(u_int);
		for (i = 0; i < ppp_id_count; i += n) {
			n = MINIMUM(nmax, ppp_id_count - i);
			req.count = n;
			iov[0].iov_base = &req;
			iov[0].iov_len = offsetof(
			    struct npppd_disconnect_request, ppp_id[0]);
			iov[1].iov_base = &ppp_id[i];
			iov[1].iov_len = sizeof(u_int) * n;

			if (imsg_composev(&ctl_ibuf, IMSG_CTL_DISCONNECT, 0, 0,
			    -1, iov, 2) == -1)
				err(EXIT_FAILURE,
				    "Failed to compose a message");
			if (imsg_wait_command_completion() < 0)
				errx(EXIT_FAILURE, "failed to get response");
			if (ctl_imsg.hdr.type != IMSG_CTL_OK)
				errx(EXIT_FAILURE,
				    "Command was fail: msg type = %d",
				    ctl_imsg.hdr.type);
			if (ctl_imsg.hdr.len - IMSG_HEADER_SIZE <
			    sizeof(struct npppd_disconnect_response))
				err(EXIT_FAILURE, "response is corrupted");
			res = (struct npppd_disconnect_response *)ctl_imsg.data;
			succ += res->count;
		}
		fail = total - succ;
	}
	if (succ > 0)
		fprintf(out, "Successfully disconnected %d session%s.\n",
		    succ, (succ > 1)? "s" : "");
	if (fail > 0)
		fprintf(out, "Failed to disconnect %d session%s.\n",
		    fail, (fail > 1)? "s" : "");
	if (succ == 0 && fail == 0)
		fprintf(out, "No session to disconnect.\n");
}

/***********************************************************************
 * common functions
 ***********************************************************************/
static bool
filter_match(struct parse_result *result, struct npppd_who *who)
{
	if (result->has_ppp_id && result->ppp_id != who->ppp_id)
		return (false);

	switch (result->address.ss_family) {
	case AF_INET:
		if (((struct sockaddr_in *)&result->address)->sin_addr.
		    s_addr != who->framed_ip_address.s_addr)
			return (false);
		break;
	case AF_INET6:
		/* npppd doesn't support IPv6 yet */
		return (false);
	}

	if (result->interface != NULL &&
	    strcmp(result->interface, who->ifname) != 0)
		return (false);

	if (result->protocol != PROTO_UNSPEC &&
	    result->protocol != parse_protocol(who->tunnel_proto) )
		return (false);

	if (result->realm != NULL && strcmp(result->realm, who->rlmname) != 0)
		return (false);

	if (result->username != NULL &&
	    strcmp(result->username, who->username) != 0)
		return (false);

	return (true);
}

static const char *
peerstr(struct sockaddr *sa, char *buf, int lbuf)
{
	int   niflags, hasserv;
	char  hoststr[NI_MAXHOST], servstr[NI_MAXSERV];

	niflags = hasserv = 0;
	if (nflag)
		niflags |= NI_NUMERICHOST;
	if (sa->sa_family == AF_INET || sa->sa_family ==AF_INET6) {
		hasserv = 1;
		niflags |= NI_NUMERICSERV;
	}

	if (sa->sa_family == AF_LINK)
		snprintf(hoststr, sizeof(hoststr),
		    "%02x:%02x:%02x:%02x:%02x:%02x",
		    LLADDR((struct sockaddr_dl *)sa)[0] & 0xff,
		    LLADDR((struct sockaddr_dl *)sa)[1] & 0xff,
		    LLADDR((struct sockaddr_dl *)sa)[2] & 0xff,
		    LLADDR((struct sockaddr_dl *)sa)[3] & 0xff,
		    LLADDR((struct sockaddr_dl *)sa)[4] & 0xff,
		    LLADDR((struct sockaddr_dl *)sa)[5] & 0xff);
	else
		getnameinfo(sa, sa->sa_len, hoststr, sizeof(hoststr), servstr,
		    sizeof(servstr), niflags);

	strlcpy(buf, hoststr, lbuf);
	if (hasserv) {
		strlcat(buf, ":", lbuf);
		strlcat(buf, servstr, lbuf);
	}

	return (buf);
}

static const char *
humanize_duration(uint32_t sec, char *buf, int lbuf)
{
	char  fbuf[128];
	int   hour, min;

	hour = sec / (60 * 60);
	min = sec / 60;
	min %= 60;

	if (lbuf <= 0)
		return (buf);
	buf[0] = '\0';
	if (hour || min) {
		strlcat(buf, "(", lbuf);
		if (hour) {
			snprintf(fbuf, sizeof(fbuf),
			    "%d hour%s", hour, (hour > 1)? "s" : "");
			strlcat(buf, fbuf, lbuf);
		}
		if (hour && min)
			strlcat(buf, " and ", lbuf);
		if (min) {
			snprintf(fbuf, sizeof(fbuf),
			    "%d minute%s", min, (min > 1)? "s" : "");
			strlcat(buf, fbuf, lbuf);
		}
		strlcat(buf, ")", lbuf);
	}

	return (buf);
}

static const char *
humanize_bytes(double val, char *buf, int lbuf)
{
	if (lbuf <= 0)
		return (buf);

	if (val >= 1000 * 1024 * 1024)
		snprintf(buf, lbuf, " (%.1f GB)",
		    (double)val / (1024 * 1024 * 1024));
	else if (val >= 1000 * 1024)
		snprintf(buf, lbuf, " (%.1f MB)", (double)val / (1024 * 1024));
	else if (val >= 1000)
		snprintf(buf, lbuf, " (%.1f KB)", (double)val / 1024);
	else
		buf[0] = '\0';

	return (buf);
}

static int
imsg_wait_command_completion(void)
{
	int  n;

	if (imsg_flush(&ctl_ibuf) == -1)
		return (-1);
	do {
		if ((n = imsg_get(&ctl_ibuf, &ctl_imsg)) == -1)
			return (-1);
		if (n != 0)
			break;
		if (((n = imsg_read(&ctl_ibuf)) == -1 && errno != EAGAIN) ||
		    n == 0)
			return (-1);
	} while (1);

	return (ctl_imsg.hdr.type);
}