chiark / gitweb /
admin.c (a_format): New function formats token sequences to strings.
[tripe] / server / admin.c
CommitLineData
410c8acf 1/* -*-c-*-
2 *
410c8acf 3 * Admin interface for configuration
4 *
5 * (c) 2001 Straylight/Edgeware
6 */
7
e04c2d50 8/*----- Licensing notice --------------------------------------------------*
410c8acf 9 *
10 * This file is part of Trivial IP Encryption (TrIPE).
11 *
12 * TrIPE is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
e04c2d50 16 *
410c8acf 17 * TrIPE is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
e04c2d50 21 *
410c8acf 22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
410c8acf 27/*----- Header files ------------------------------------------------------*/
28
29#include "tripe.h"
30
31/*----- Global variables --------------------------------------------------*/
32
33#ifndef NTRACE
34
35const trace_opt tr_opts[] = {
36 { 't', T_TUNNEL, "tunnel events" },
37 { 'r', T_PEER, "peer events" },
38 { 'a', T_ADMIN, "admin interface" },
410c8acf 39 { 's', T_KEYSET, "symmetric keyset management" },
40 { 'x', T_KEYEXCH, "key exchange" },
41 { 'm', T_KEYMGMT, "key management" },
37941236 42 { 'l', T_CHAL, "challenge management" },
388e0319 43 { 'v', T_PRIVSEP, "privilege separation" },
37941236 44 { 'p', T_PACKET, "packet contents" },
45 { 'c', T_CRYPTO, "crypto details" },
410c8acf 46 { 'A', T_ALL, "all of the above" },
47 { 0, 0, 0 }
48};
49
50unsigned tr_flags = 0;
51#endif
52
3cdc3f3a 53static const trace_opt w_opts[] = {
54 { 't', AF_TRACE, "trace messages" },
55 { 'n', AF_NOTE, "asynchronous notifications" },
56 { 'w', AF_WARN, "warnings" },
57 { 'A', AF_ALLMSGS, "all of the above" },
58 { 0, 0, 0 }
59};
60
410c8acf 61/*----- Static variables --------------------------------------------------*/
62
63static admin *admins;
c511e1f9 64static admin *a_dead;
410c8acf 65static sel_file sock;
66static const char *sockname;
be6a1b7a 67static sym_table a_svcs;
410c8acf 68static unsigned flags = 0;
69static admin *a_stdin = 0;
70static sig s_term, s_int, s_hup;
71
72#define F_DAEMON 1u
73#define F_INIT 2u
46dde080 74#define F_FOREGROUND 4u
410c8acf 75
76#define T_RESOLVE SEC(30)
0ba8de86 77#define T_PING SEC(5)
410c8acf 78
fd3cf232 79static void a_destroy(admin */*a*/);
fd3cf232 80
060ca767 81#define BOOL(x) ((x) ? "t" : "nil")
82
fd3cf232 83/*----- Output functions --------------------------------------------------*/
84
85/* --- @trywrite@ --- *
86 *
87 * Arguments: @admin *a@ = pointer to an admin block
88 * @const char *p@ = pointer to buffer to write
89 * @size_t sz@ = size of data to write
90 *
91 * Returns: The number of bytes written, or less than zero on error.
92 *
93 * Use: Attempts to write data to a client.
94 */
95
96static ssize_t trywrite(admin *a, const char *p, size_t sz)
97{
98 ssize_t n, done = 0;
99
100again:
101 if (!sz)
102 return (done);
103 n = write(a->w.fd, p, sz);
104 if (n > 0) {
105 done += n;
106 p += n;
107 sz -= n;
108 goto again;
109 }
110 if (n < 0) {
111 if (errno == EINTR)
112 goto again;
113 if (errno != EAGAIN && errno != EWOULDBLOCK) {
114 a_destroy(a);
f43df819 115 a_warn("ADMIN", "client-write-error", "?ERRNO", A_END);
fd3cf232 116 return (-1);
117 }
118 }
119 return (done);
120}
121
de014da6 122/* --- @doqueue@ -- *
fd3cf232 123 *
de014da6 124 * Arguments: @oqueue *q@ = pointer to output queue
fd3cf232 125 * @const char *p@ = pointer to buffer to write
de014da6 126 * @size_t sz@ = size of buffer
fd3cf232 127 *
de014da6 128 * Returns: Nonzero if the queue was previously empty.
fd3cf232 129 *
de014da6 130 * Use: Queues data to be written later.
fd3cf232 131 */
132
de014da6 133static int doqueue(oqueue *q, const char *p, size_t sz)
fd3cf232 134{
fd3cf232 135 obuf *o;
de014da6 136 int rc = 0;
137 size_t n;
fd3cf232 138
de014da6 139 o = q->tl;
fd3cf232 140 if (!o)
de014da6 141 rc = 1;
fd3cf232 142 else if (o->p_in < o->buf + OBUFSZ)
143 goto noalloc;
144
145 do {
146 o = xmalloc(sizeof(obuf));
147 o->next = 0;
148 o->p_in = o->p_out = o->buf;
de014da6 149 if (q->tl)
150 q->tl->next = o;
fd3cf232 151 else
de014da6 152 q->hd = o;
153 q->tl = o;
fd3cf232 154
155 noalloc:
156 n = o->buf + OBUFSZ - o->p_in;
157 if (n > sz)
158 n = sz;
159 memcpy(o->p_in, p, n);
160 o->p_in += n;
161 p += n;
162 sz -= n;
163 } while (sz);
de014da6 164
165 return (rc);
166}
167
168/* --- @dosend@ --- *
169 *
170 * Arguemnts: @admin *a@ = pointer to an admin block
171 * @const char *p@ = pointer to buffer to write
172 * @size_t sz@ = size of data to write
173 *
174 * Returns: ---
175 *
176 * Use: Sends data to an admin client.
177 */
178
179static void dosend(admin *a, const char *p, size_t sz)
180{
181 ssize_t n;
182
183 if (a->f & AF_DEAD)
184 return;
185 if (!a->out.hd) {
186 if ((n = trywrite(a, p, sz)) < 0)
187 return;
188 p += n;
189 sz -= n;
190 if (!sz)
191 return;
192 }
193 if (doqueue(&a->out, p, sz))
194 sel_addfile(&a->w);
fd3cf232 195}
196
197/* --- @a_flush@ --- *
198 *
199 * Arguments: @int fd@ = file descriptor
200 * @unsigned mode@ = what's happening
201 * @void *v@ = pointer to my admin block
202 *
203 * Returns: ---
204 *
205 * Use: Flushes buffers when a client is ready to read again.
206 */
207
208static void a_flush(int fd, unsigned mode, void *v)
209{
210 admin *a = v;
211 obuf *o, *oo;
212 ssize_t n;
213
de014da6 214 o = a->out.hd;
fd3cf232 215 while (o) {
216 if ((n = trywrite(a, o->p_out, o->p_in - o->p_out)) < 0)
217 return;
218 o->p_out += n;
219 if (o->p_in < o->p_out)
220 break;
221 oo = o;
222 o = o->next;
223 xfree(oo);
224 }
de014da6 225 a->out.hd = o;
fd3cf232 226 if (!o) {
de014da6 227 a->out.tl = 0;
fd3cf232 228 sel_rmfile(&a->w);
229 }
230}
231
410c8acf 232/*----- Utility functions -------------------------------------------------*/
233
f43df819
MW
234/* --- @a_vformat@ --- *
235 *
236 * Arguments: @dstr *d@ = where to leave the formatted message
237 * @const char *fmt@ = pointer to format string
238 * @va_list ap@ = arguments in list
239 *
240 * Returns: ---
241 *
7f73baaf
MW
242 * Use: Main message token formatting driver. The arguments are
243 * interleaved formatting tokens and their parameters, finally
244 * terminated by an entry @A_END@.
245 *
246 * Tokens recognized:
247 *
248 * * "*..." ... -- pretokenized @dstr_putf@-like string
249 *
250 * * "?ADDR" SOCKADDR -- a socket address, to be converted
251 *
252 * * "?B64" BUFFER SIZE -- binary data to be base64-encoded
253 *
254 * * "?TOKENS" VECTOR -- null-terminated vector of tokens
255 *
256 * * "?PEER" PEER -- peer's name
257 *
258 * * "?ERRNO" ERRNO -- system error code
259 *
260 * * "[!]..." ... -- @dstr_putf@-like string as single token
f43df819
MW
261 */
262
7f73baaf 263void a_vformat(dstr *d, const char *fmt, va_list ap)
f43df819
MW
264{
265 dstr dd = DSTR_INIT;
266
267 while (fmt) {
268 if (*fmt == '*') {
6ebbf072 269 if (d->len) dstr_putc(d, ' ');
f43df819
MW
270 dstr_vputf(d, fmt + 1, &ap);
271 } else if (*fmt == '?') {
272 if (strcmp(fmt, "?ADDR") == 0) {
273 const addr *a = va_arg(ap, const addr *);
274 switch (a->sa.sa_family) {
275 case AF_INET:
0ed0735f
MW
276 u_quotify(d, "INET");
277 u_quotify(d, inet_ntoa(a->sin.sin_addr));
f43df819
MW
278 dstr_putf(d, " %u", (unsigned)ntohs(a->sin.sin_port));
279 break;
280 default:
281 abort();
282 }
283 } else if (strcmp(fmt, "?B64") == 0) {
284 const octet *p = va_arg(ap, const octet *);
285 size_t n = va_arg(ap, size_t);
286 base64_ctx b64;
287 dstr_putc(d, ' ');
288 base64_init(&b64);
289 b64.indent = "";
290 b64.maxline = 0;
291 base64_encode(&b64, p, n, d);
292 base64_encode(&b64, 0, 0, d);
293 while (d->len && d->buf[d->len - 1] == '=') d->len--;
3331936b
MW
294 } else if (strcmp(fmt, "?TOKENS") == 0) {
295 const char *const *av = va_arg(ap, const char *const *);
0ed0735f 296 while (*av) u_quotify(d, *av++);
f43df819 297 } else if (strcmp(fmt, "?PEER") == 0)
0ed0735f 298 u_quotify(d, p_name(va_arg(ap, peer *)));
f43df819
MW
299 else if (strcmp(fmt, "?ERRNO") == 0) {
300 dstr_putf(d, " E%d", errno);
0ed0735f 301 u_quotify(d, strerror(errno));
f43df819
MW
302 } else
303 abort();
304 } else {
305 if (*fmt == '!') fmt++;
306 DRESET(&dd);
307 dstr_vputf(&dd, fmt, &ap);
0ed0735f 308 u_quotify(d, dd.buf);
f43df819
MW
309 }
310 fmt = va_arg(ap, const char *);
311 }
312
313 dstr_destroy(&dd);
314}
315
f241e36c
MW
316/* --- @a_format@ --- *
317 *
318 * Arguments: @dstr *d@ = where to leave the formatted message
319 * @const char *fmt@ = pointer to format string
320 *
321 * Returns: ---
322 *
323 * Use: Writes a tokenized message into a string, for later
324 * presentation.
325 */
326
327void a_format(dstr *d, const char *fmt, ...)
328{
329 va_list ap;
330
331 va_start(ap, fmt);
332 a_vformat(d, fmt, ap);
333 va_end(ap);
334}
335
3cdc3f3a 336/* --- @a_write@, @a_vwrite@ --- *
410c8acf 337 *
338 * Arguments: @admin *a@ = admin connection to write to
de014da6 339 * @const char *status@ = status code to report
340 * @const char *tag@ = tag string, or null
410c8acf 341 * @const char *fmt@ = pointer to format string
3cdc3f3a 342 * @va_list ap@ = arguments in list
410c8acf 343 * @...@ = other arguments
344 *
345 * Returns: ---
346 *
347 * Use: Sends a message to an admin connection.
348 */
349
de014da6 350static void a_vwrite(admin *a, const char *status, const char *tag,
351 const char *fmt, va_list ap)
410c8acf 352{
410c8acf 353 dstr d = DSTR_INIT;
f98df549 354
de014da6 355 if (tag) dstr_puts(&d, "BG");
356 dstr_puts(&d, status);
0ed0735f 357 if (tag) u_quotify(&d, tag);
f43df819 358 a_vformat(&d, fmt, ap);
3cdc3f3a 359 dstr_putc(&d, '\n');
360 dosend(a, d.buf, d.len);
361 dstr_destroy(&d);
362}
363
de014da6 364static void a_write(admin *a, const char *status, const char *tag,
365 const char *fmt, ...)
3cdc3f3a 366{
367 va_list ap;
f98df549 368
410c8acf 369 va_start(ap, fmt);
de014da6 370 a_vwrite(a, status, tag, fmt, ap);
410c8acf 371 va_end(ap);
3cdc3f3a 372}
373
374/* --- @a_ok@, @a_info@, @a_fail@ --- *
375 *
376 * Arguments: @admin *a@ = connection
377 * @const char *fmt@ = format string
378 * @...@ = other arguments
379 *
380 * Returns: ---
381 *
382 * Use: Convenience functions for @a_write@.
383 */
384
f43df819 385static void a_ok(admin *a) { a_write(a, "OK", 0, A_END); }
3cdc3f3a 386
387static void a_info(admin *a, const char *fmt, ...)
388{
389 va_list ap;
f98df549 390
3cdc3f3a 391 va_start(ap, fmt);
de014da6 392 a_vwrite(a, "INFO", 0, fmt, ap);
3cdc3f3a 393 va_end(ap);
394}
395
396static void a_fail(admin *a, const char *fmt, ...)
397{
398 va_list ap;
f98df549 399
3cdc3f3a 400 va_start(ap, fmt);
de014da6 401 a_vwrite(a, "FAIL", 0, fmt, ap);
3cdc3f3a 402 va_end(ap);
403}
404
405/* --- @a_alert@, @a_valert@, @a_rawalert@ --- *
406 *
407 * Arguments: @unsigned f_and, f_eq@ = filter for connections
de014da6 408 * @const char *status@ = status string
3cdc3f3a 409 * @const char *fmt@ = pointer to format string
de014da6 410 * @const char *p@ = pointer to raw string
3cdc3f3a 411 * @size_t sz@ = size of raw string
412 * @va_list ap@ = arguments in list
413 * @...@ = other arguments
414 *
415 * Returns: ---
416 *
417 * Use: Write a message to all admin connections matched by the given
418 * filter.
419 */
420
de014da6 421static void a_rawalert(unsigned f_and, unsigned f_eq, const char *status,
3cdc3f3a 422 const char *p, size_t sz)
423{
424 admin *a, *aa;
425 dstr d = DSTR_INIT;
e04c2d50 426
3cdc3f3a 427 if (!(flags & F_INIT))
428 return;
de014da6 429 dstr_puts(&d, status);
430 if (p) {
431 dstr_putc(&d, ' ');
3cdc3f3a 432 dstr_putm(&d, p, sz);
de014da6 433 }
3cdc3f3a 434 dstr_putc(&d, '\n');
435 p = d.buf;
436 sz = d.len;
437 for (a = admins; a; a = aa) {
438 aa = a->next;
439 if ((a->f & f_and) == f_eq)
440 dosend(a, d.buf, d.len);
441 }
410c8acf 442 dstr_destroy(&d);
443}
444
b9adb829 445static void a_valert(unsigned f_and, unsigned f_eq, const char *status,
3cdc3f3a 446 const char *fmt, va_list ap)
447{
448 dstr d = DSTR_INIT;
449
450 if (!(flags & F_INIT))
451 return;
f43df819 452 a_vformat(&d, fmt, ap);
b9adb829 453 a_rawalert(f_and, f_eq, status, fmt ? d.buf : 0, fmt ? d.len : 0);
3cdc3f3a 454 dstr_destroy(&d);
455}
456
b9adb829 457static void a_alert(unsigned f_and, unsigned f_eq, const char *status,
3cdc3f3a 458 const char *fmt, ...)
459{
460 va_list ap;
f98df549 461
3cdc3f3a 462 va_start(ap, fmt);
b9adb829 463 a_valert(f_and, f_eq, status, fmt, ap);
3cdc3f3a 464 va_end(ap);
465}
3cdc3f3a 466
410c8acf 467/* --- @a_warn@ --- *
468 *
469 * Arguments: @const char *fmt@ = pointer to format string
470 * @...@ = other arguments
471 *
472 * Returns: ---
473 *
474 * Use: Informs all admin connections of a warning.
475 */
476
477void a_warn(const char *fmt, ...)
478{
479 va_list ap;
410c8acf 480
410c8acf 481 va_start(ap, fmt);
3cdc3f3a 482 if (flags & F_INIT)
483 a_valert(0, 0, "WARN", fmt, ap);
410c8acf 484 else {
f43df819 485 dstr d = DSTR_INIT;
3cdc3f3a 486 fprintf(stderr, "%s: ", QUIS);
f43df819
MW
487 a_vformat(&d, fmt, ap);
488 dstr_putc(&d, '\n');
489 dstr_write(&d, stderr);
490 dstr_destroy(&d);
410c8acf 491 }
3cdc3f3a 492 va_end(ap);
410c8acf 493}
494
495/* --- @a_trace@ --- *
496 *
497 * Arguments: @const char *p@ = pointer to a buffer
498 * @size_t sz@ = size of the buffer
499 * @void *v@ = uninteresting pointer
500 *
501 * Returns: ---
502 *
3cdc3f3a 503 * Use: Custom trace output handler. Sends trace messages to
504 * interested admin connections.
410c8acf 505 */
506
507#ifndef NTRACE
508static void a_trace(const char *p, size_t sz, void *v)
de014da6 509 { a_rawalert(AF_TRACE, AF_TRACE, "TRACE", p, sz); }
410c8acf 510#endif
511
3cdc3f3a 512/* --- @a_notify@ --- *
513 *
514 * Arguments: @const char *fmt@ = pointer to format string
515 * @...@ = other arguments
516 *
517 * Returns: ---
518 *
519 * Use: Sends a notification to interested admin connections.
520 */
521
522void a_notify(const char *fmt, ...)
523{
524 va_list ap;
525
526 va_start(ap, fmt);
527 a_valert(AF_NOTE, AF_NOTE, "NOTE", fmt, ap);
528 va_end(ap);
529}
530
410c8acf 531/* --- @a_quit@ --- *
532 *
533 * Arguments: ---
534 *
535 * Returns: ---
536 *
537 * Use: Shuts things down nicely.
538 */
539
540void a_quit(void)
541{
542 close(sock.fd);
543 unlink(sockname);
c8e02c8a 544 FOREACH_PEER(p, { p_destroy(p); });
388e0319 545 ps_quit();
410c8acf 546 exit(0);
547}
548
549/* --- @a_sigdie@ --- *
550 *
551 * Arguments: @int sig@ = signal number
552 * @void *v@ = an uninteresting argument
553 *
554 * Returns: ---
555 *
556 * Use Shuts down on receipt of a fatal signal.
557 */
558
559static void a_sigdie(int sig, void *v)
560{
561 char *p;
562 char buf[20];
563
564 switch (sig) {
565 case SIGTERM: p = "SIGTERM"; break;
566 case SIGINT: p = "SIGINT"; break;
567 default:
3cdc3f3a 568 sprintf(buf, "%i", sig);
410c8acf 569 p = buf;
570 break;
571 }
f43df819 572 a_warn("SERVER", "quit", "signal", "%s", p, A_END);
410c8acf 573 a_quit();
574}
575
576/* --- @a_sighup@ --- *
577 *
578 * Arguments: @int sig@ = signal number
579 * @void *v@ = an uninteresting argument
580 *
581 * Returns: ---
582 *
583 * Use Logs a message about SIGHUP not being useful.
584 */
585
586static void a_sighup(int sig, void *v)
f98df549 587 { a_warn("SERVER", "ignore", "signal", "SIGHUP", A_END); }
410c8acf 588
0ba8de86 589/* --- @a_parsetime@ --- *
590 *
591 * Arguments; @const char *p@ = time string to parse
592 *
593 * Returns: Time in seconds, or @< 0@ on error.
594 */
595
596static long a_parsetime(const char *p)
597{
598 char *q;
599 long t = strtol(p, &q, 0);
600
601 switch (*q) {
602 case 'd': t *= 24;
603 case 'h': t *= 60;
604 case 'm': t *= 60;
605 case 's': if (q[1] != 0)
e04c2d50 606 default: t = -1;
0ba8de86 607 case 0: break;
608 }
e04c2d50 609 return (t);
0ba8de86 610}
611
37941236 612/* --- @a_findpeer@ --- *
613 *
614 * Arguments: @admin *a@ = admin connection
615 * @const char *pn@ = peer name
616 *
617 * Returns: The peer, or null if not there.
618 *
619 * Use: Finds a peer, reporting an error if it failed.
620 */
621
622static peer *a_findpeer(admin *a, const char *pn)
623{
624 peer *p;
625
626 if ((p = p_find(pn)) == 0)
f43df819 627 a_fail(a, "unknown-peer", "%s", pn, A_END);
37941236 628 return (p);
629}
630
de014da6 631/*----- Backgrounded operations -------------------------------------------*/
632
060ca767 633#define BGTAG(bg) \
634 (((admin_bgop *)(bg))->tag ? ((admin_bgop *)(bg))->tag : "<foreground>")
635
ff92ffd3
MW
636/* --- @a_bgfind@ --- *
637 *
638 * Arguments: @admin *a@ = a client block
639 * @const char *tag@ = the requested tag
640 *
641 * Returns: The requested background job, or null.
642 */
643
644static admin_bgop *a_bgfind(admin *a, const char *tag)
645{
646 admin_bgop *bg;
647
648 for (bg = a->bg; bg; bg = bg->next) {
649 if (bg->tag && strcmp(tag, bg->tag) == 0)
650 return (bg);
651 }
652 return (0);
653}
654
de014da6 655/* --- @a_bgrelease@ --- *
656 *
657 * Arguments: @admin_bgop *bg@ = backgrounded operation
658 *
659 * Returns: ---
660 *
661 * Use: Removes a backgrounded operation from the queue, since
662 * (presumably) it's done.
663 */
664
665static void a_bgrelease(admin_bgop *bg)
666{
667 admin *a = bg->a;
668
060ca767 669 T( trace(T_ADMIN, "admin: release bgop %s", BGTAG(bg)); )
670 if (bg->tag) xfree(bg->tag);
671 else selbuf_enable(&a->b);
672 if (bg->next) bg->next->prev = bg->prev;
673 if (bg->prev) bg->prev->next = bg->next;
674 else a->bg = bg->next;
de014da6 675 xfree(bg);
547a9c13 676 if (!a->bg && (a->f & AF_CLOSE)) a_destroy(a);
de014da6 677}
678
679/* --- @a_bgok@, @a_bginfo@, @a_bgfail@ --- *
680 *
681 * Arguments: @admin_bgop *bg@ = backgrounded operation
682 * @const char *fmt@ = format string
683 * @...@ = other arguments
684 *
685 * Returns: ---
686 *
687 * Use: Convenience functions for @a_write@.
688 */
689
690static void a_bgok(admin_bgop *bg)
f43df819 691 { a_write(bg->a, "OK", bg->tag, A_END); }
de014da6 692
693static void a_bginfo(admin_bgop *bg, const char *fmt, ...)
694{
695 va_list ap;
696 va_start(ap, fmt);
697 a_vwrite(bg->a, "INFO", bg->tag, fmt, ap);
698 va_end(ap);
699}
700
701static void a_bgfail(admin_bgop *bg, const char *fmt, ...)
702{
703 va_list ap;
704 va_start(ap, fmt);
705 a_vwrite(bg->a, "FAIL", bg->tag, fmt, ap);
706 va_end(ap);
707}
708
709/* --- @a_bgadd@ --- *
710 *
711 * Arguments: @admin *a@ = administration connection
712 * @admin_bgop *bg@ = pointer to background operation
713 * @const char *tag@ = background tag, or null for foreground
714 * @void (*cancel)(admin_bgop *)@ = cancel function
715 *
ff92ffd3 716 * Returns: Zero for success, nonzero on failure.
de014da6 717 *
718 * Use: Links a background job into the list.
719 */
720
ff92ffd3
MW
721static int a_bgadd(admin *a, admin_bgop *bg, const char *tag,
722 void (*cancel)(admin_bgop *))
de014da6 723{
ff92ffd3
MW
724 if (tag) {
725 if (a_bgfind(a, tag)) {
726 a_fail(a, "tag-exists", "%s", tag, A_END);
727 return (-1);
728 }
de014da6 729 bg->tag = xstrdup(tag);
ff92ffd3 730 }
de014da6 731 else {
732 bg->tag = 0;
733 selbuf_disable(&a->b);
734 }
735 bg->a = a;
736 bg->cancel = cancel;
737 bg->next = a->bg;
738 bg->prev = 0;
060ca767 739 if (a->bg) a->bg->prev = bg;
de014da6 740 a->bg = bg;
060ca767 741 T( trace(T_ADMIN, "admin: add bgop %s", BGTAG(bg)); )
f43df819 742 if (tag) a_write(a, "DETACH", tag, A_END);
ff92ffd3 743 return (0);
de014da6 744}
745
5d46c0f8
MW
746/*----- Job table manipulation --------------------------------------------*/
747
748#define JOB_SHIFT 16
749#define JOB_INDEXMASK ((1ul << JOB_SHIFT) - 1)
750#define JOB_SEQMASK ((1ul << (32 - JOB_SHIFT)) - 1)
751
752#define JOB_END 0xfffffffful
753
754static unsigned long a_joboffset;
755
756/* --- @a_jobidencode@ --- *
757 *
758 * Arguments: @admin_svcop *svc@ = pointer to a service operation
759 *
760 * Returns: A jobid for this job, in an internal static buffer.
761 *
762 * Use: Constructs a jobid. In order to dissuade people from
763 * predicting jobids, we obfuscate them.
764 *
765 * A `raw' jobid consists of two 16-bit fields. The low 16 bits
766 * are an index into a big array. The high 16 bits are a
767 * sequence number recording how many times that slot has been
768 * reused.
769 *
770 * This `raw' jobid is then obfuscated by adding a randomly-
771 * generated offset, and multiplying (mod %$2^{32}$%) by a fixed
772 * odd constant.
773 */
774
775static const char *a_jobidencode(admin_svcop *svc)
776{
777 admin_jobtable *j = &svc->prov->j;
778 static char buf[10];
779 unsigned long pre;
780 unsigned seq;
781
782 assert(svc->index <= JOB_INDEXMASK);
783 seq = j->v[svc->index].seq;
784 assert(seq <= JOB_SEQMASK);
785 pre = (unsigned long)svc->index | ((unsigned long)seq << JOB_SHIFT);
786 sprintf(buf, "J%08lx", ((pre + a_joboffset) * 0x0f87a7a3ul) & 0xffffffff);
787 return (buf);
788}
789
790/* --- @a_jobiddecode@ --- *
791 *
792 * Arguments: @admin_jobtable *j@ = pointer to a job table
793 * @const char *jid@ = pointer to a jobid string
794 *
795 * Returns: A pointer to the job's @svcop@ structure.
796 */
797
798static admin_svcop *a_jobiddecode(admin_jobtable *j, const char *jid)
799{
800 unsigned i;
801 unsigned long pre;
802
803 if (jid[0] != 'J')
804 return (0);
805 for (i = 1; i < 9; i++) {
806 if (!isxdigit((unsigned char)jid[i]))
807 return (0);
808 }
809 if (jid[9] != 0)
810 return (0);
811 pre = strtoul(jid + 1, 0, 16);
812 pre = ((pre * 0xbd11c40bul) - a_joboffset) & 0xffffffff;
813 i = pre & JOB_INDEXMASK;
814 if (i >= j->n || j->v[i].seq != (pre >> JOB_SHIFT))
815 return (0);
816 return (j->v[i].u.op);
817}
818
819/* --- @a_jobcreate@ --- *
820 *
821 * Arguments: @admin *a@ = pointer to administration client
822 *
823 * Returns: A pointer to a freshly-allocated @svcop@, or null.
824 *
825 * Use: Allocates a fresh @svcop@ and links it into a job table.
826 */
827
828static admin_svcop *a_jobcreate(admin *a)
829{
830 admin_svcop *svc;
831 unsigned i;
832 unsigned sz;
833 admin_jobtable *j = &a->j;
834
835 if (j->free != JOB_END) {
836 i = j->free;
837 j->free = j->v[i].u.next;
838 } else {
839 if (j->n == j->sz) {
840 if (j->sz > JOB_INDEXMASK)
841 return (0);
842 sz = j->sz;
843 if (!sz) {
844 j->sz = 16;
845 j->v = xmalloc(j->sz * sizeof(*j->v));
846 } else {
847 j->sz = sz << 1;
848 j->v = xrealloc(j->v, j->sz * sizeof(*j->v), sz * sizeof(*j->v));
849 }
850 }
851 i = j->n++;
852 j->v[i].seq = 0;
853 }
854 svc = xmalloc(sizeof(*svc));
855 svc->index = i;
856 svc->prov = a;
857 svc->next = j->active;
858 svc->prev = 0;
859 if (j->active) j->active->prev = svc;
860 j->active = svc;
861 j->v[i].u.op = svc;
862 IF_TRACING(T_ADMIN, {
863 trace(T_ADMIN, "admin: created job %s (%u)", a_jobidencode(svc), i);
864 })
865 return (svc);
866}
867
868/* --- @a_jobdestroy@ --- *
869 *
870 * Arguments: @admin_svcop *svc@ = pointer to job block
871 *
872 * Returns: ---
873 *
874 * Use: Frees up a completed (or cancelled) job.
875 */
876
877static void a_jobdestroy(admin_svcop *svc)
878{
879 admin *a = svc->prov;
880 admin_jobtable *j = &a->j;
881 unsigned i = svc->index;
882
883 IF_TRACING(T_ADMIN, {
884 trace(T_ADMIN, "admin: destroying job %s (%u)", a_jobidencode(svc), i);
885 })
886 assert(j->v[i].u.op = svc);
887 j->v[i].u.next = j->free;
888 j->v[i].seq++;
889 j->free = i;
890 if (svc->next) svc->next->prev = svc->prev;
891 if (svc->prev) svc->prev->next = svc->next;
892 else j->active = svc->next;
893}
894
895/* --- @a_jobtableinit@ --- *
896 *
897 * Arguments: @admin_jobtable *j@ = pointer to job table
898 *
899 * Returns: ---
900 *
901 * Use: Initializes a job table.
902 */
903
904static void a_jobtableinit(admin_jobtable *j)
905{
906 if (!a_joboffset)
907 a_joboffset = GR_RANGE(&rand_global, 0xffffffff) + 1;
908 j->n = j->sz = 0;
909 j->active = 0;
910 j->free = JOB_END;
911 j->v = 0;
912}
913
914/* --- @a_jobtablefinal@ --- *
915 *
916 * Arguments: @admin_jobtable *j@ = pointer to job table
917 *
918 * Returns: ---
919 *
920 * Use: Closes down a job table.
921 */
922
923static void a_jobtablefinal(admin_jobtable *j)
924{
925 admin_svcop *svc, *ssvc;
926
927 for (svc = j->active; svc; svc = ssvc) {
928 ssvc = svc->next;
929 a_bgfail(&svc->bg, "provider-failed", A_END);
930 a_bgrelease(&svc->bg);
931 }
932 if (j->v) xfree(j->v);
933}
934
be6a1b7a
MW
935/*----- Services infrastructure -------------------------------------------*/
936
937/* --- @a_svcfind@ --- *
938 *
939 * Arguments: @admin *a@ = the requesting client
940 * @const char *name@ = service name wanted
941 *
942 * Returns: The service requested, or null.
943 *
944 * Use: Finds a service; reports an error if the service couldn't be
945 * found.
946 */
947
948static admin_service *a_svcfind(admin *a, const char *name)
949{
950 admin_service *svc;
951
952 if ((svc = sym_find(&a_svcs, name, -1, 0, 0)) == 0) {
953 a_fail(a, "unknown-service", "%s", name, A_END);
954 return (0);
955 }
956 return (svc);
957}
958
959/* --- @a_svcunlink@ --- *
960 *
961 * Arguments: @admin_service *svc@ = pointer to service structure
962 *
963 * Returns: ---
964 *
965 * Use: Unlinks the service from its provider, without issuing a
966 * message or freeing the structure. The version string is
967 * freed, however.
968 */
969
970static void a_svcunlink(admin_service *svc)
971{
972 if (svc->next)
973 svc->next->prev = svc->prev;
974 if (svc->prev)
975 svc->prev->next = svc->next;
976 else
977 svc->prov->svcs = svc->next;
978 xfree(svc->version);
979}
980
981/* --- @a_svcrelease@ --- *
982 *
983 * Arguments: @admin_service *svc@ = pointer to service structure
984 *
985 * Returns: ---
986 *
987 * Use: Releases a service and frees its structure.
988 */
989
990static void a_svcrelease(admin_service *svc)
991{
992 a_notify("SVCRELEASE", "%s", SYM_NAME(svc), A_END);
993 a_svcunlink(svc);
994 sym_remove(&a_svcs, svc);
de014da6 995}
996
37941236 997/*----- Name resolution operations ----------------------------------------*/
de014da6 998
37941236 999/* --- @a_resolved@ --- *
de014da6 1000 *
37941236 1001 * Arguments: @struct hostent *h@ = pointer to resolved hostname
1002 * @void *v@ = pointer to resolver operation
de014da6 1003 *
1004 * Returns: ---
1005 *
37941236 1006 * Use: Handles a completed name resolution.
de014da6 1007 */
1008
37941236 1009static void a_resolved(struct hostent *h, void *v)
de014da6 1010{
37941236 1011 admin_resop *r = v;
1012
1013 T( trace(T_ADMIN, "admin: resop %s resolved", BGTAG(r)); )
1014 TIMER;
1015 if (!h) {
f43df819 1016 a_bgfail(&r->bg, "resolve-error", "%s", r->addr, A_END);
37941236 1017 r->func(r, ARES_FAIL);
1018 } else {
1019 memcpy(&r->sa.sin.sin_addr, h->h_addr, sizeof(struct in_addr));
1020 r->func(r, ARES_OK);
1021 }
1022 sel_rmtimer(&r->t);
1023 xfree(r->addr);
1024 a_bgrelease(&r->bg);
e04c2d50 1025}
de014da6 1026
37941236 1027/* --- @a_restimer@ --- *
de014da6 1028 *
37941236 1029 * Arguments: @struct timeval *tv@ = timer
1030 * @void *v@ = pointer to resolver operation
de014da6 1031 *
1032 * Returns: ---
1033 *
37941236 1034 * Use: Times out a resolver.
de014da6 1035 */
1036
37941236 1037static void a_restimer(struct timeval *tv, void *v)
de014da6 1038{
37941236 1039 admin_resop *r = v;
1040
1041 T( trace(T_ADMIN, "admin: resop %s timeout", BGTAG(r)); )
f43df819 1042 a_bgfail(&r->bg, "resolver-timeout", "%s", r->addr, A_END);
37941236 1043 r->func(r, ARES_FAIL);
1044 bres_abort(&r->r);
1045 xfree(r->addr);
1046 a_bgrelease(&r->bg);
de014da6 1047}
1048
37941236 1049/* --- @a_rescancel@ --- *
de014da6 1050 *
37941236 1051 * Arguments: @admin_bgop *bg@ = background operation
de014da6 1052 *
1053 * Returns: ---
1054 *
37941236 1055 * Use: Cancels an add operation.
de014da6 1056 */
1057
37941236 1058static void a_rescancel(admin_bgop *bg)
de014da6 1059{
37941236 1060 admin_resop *r = (admin_resop *)bg;
1061
1062 T( trace(T_ADMIN, "admin: cancel resop %s", BGTAG(r)); )
1063 r->func(r, ARES_FAIL);
1064 sel_rmtimer(&r->t);
1065 xfree(r->addr);
1066 bres_abort(&r->r);
de014da6 1067}
37941236 1068
1069/* --- @a_resolve@ --- *
410c8acf 1070 *
37941236 1071 * Arguments: @admin *a@ = administration connection
1072 * @admin_resop *r@ = resolver operation to run
1073 * @const char *tag@ = background operation tag
1074 * @void (*func)(struct admin_resop *, int@ = handler function
1075 * @unsigned ac@ = number of remaining arguments
1076 * @char *av[]@ = pointer to remaining arguments
410c8acf 1077 *
1078 * Returns: ---
1079 *
37941236 1080 * Use: Cranks up a resolver job.
410c8acf 1081 */
1082
37941236 1083static void a_resolve(admin *a, admin_resop *r, const char *tag,
1084 void (*func)(struct admin_resop *, int),
1085 unsigned ac, char *av[])
410c8acf 1086{
37941236 1087 struct timeval tv;
1088 unsigned long pt;
1089 char *p;
1090 int i = 0;
fd3cf232 1091
37941236 1092 /* --- Fill in the easy bits of address --- */
1093
452bf3f6 1094 r->bg.tag = "<starting>";
37941236 1095 r->addr = 0;
1096 r->func = func;
1097 if (mystrieq(av[i], "inet")) i++;
165efde7
MW
1098 if (ac - i != 1 && ac - i != 2) {
1099 a_fail(a, "bad-addr-syntax", "[inet] ADDRESS [PORT]", A_END);
37941236 1100 goto fail;
1101 }
1102 r->sa.sin.sin_family = AF_INET;
1103 r->sasz = sizeof(r->sa.sin);
1104 r->addr = xstrdup(av[i]);
6f88042a 1105 if (!av[i + 1])
165efde7
MW
1106 pt = TRIPE_PORT;
1107 else {
1108 pt = strtoul(av[i + 1], &p, 0);
1109 if (*p) {
1110 struct servent *s = getservbyname(av[i + 1], "udp");
1111 if (!s) {
1112 a_fail(a, "unknown-service", "%s", av[i + 1], A_END);
1113 goto fail;
1114 }
1115 pt = ntohs(s->s_port);
37941236 1116 }
410c8acf 1117 }
37941236 1118 if (pt == 0 || pt >= 65536) {
f43df819 1119 a_fail(a, "invalid-port", "%lu", pt, A_END);
37941236 1120 goto fail;
1121 }
1122 r->sa.sin.sin_port = htons(pt);
1123
1124 /* --- Report backgrounding --- *
1125 *
1126 * Do this for consistency of interface, even if we're going to get the
1127 * answer straight away.
1128 */
1129
ff92ffd3
MW
1130 if (a_bgadd(a, &r->bg, tag, a_rescancel))
1131 goto fail;
37941236 1132 T( trace(T_ADMIN, "admin: %u, resop %s, hostname `%s'",
1133 a->seq, BGTAG(r), r->addr); )
1134
1135 /* --- If the name is numeric, do it the easy way --- */
e04c2d50 1136
37941236 1137 if (inet_aton(av[i], &r->sa.sin.sin_addr)) {
1138 T( trace(T_ADMIN, "admin: resop %s done the easy way", BGTAG(r)); )
1139 func(r, ARES_OK);
1140 xfree(r->addr);
1141 a_bgrelease(&r->bg);
1142 return;
1143 }
1144
1145 /* --- Store everything for later and crank up the resolver --- */
1146
1147 gettimeofday(&tv, 0);
1148 tv.tv_sec += T_RESOLVE;
1149 sel_addtimer(&sel, &r->t, &tv, a_restimer, r);
1150 bres_byname(&r->r, r->addr, a_resolved, r);
1151 return;
1152
1153fail:
1154 func(r, ARES_FAIL);
1155 if (r->addr) xfree(r->addr);
1156 xfree(r);
410c8acf 1157}
1158
e7a4d919
MW
1159/*----- Option parsing ----------------------------------------------------*/
1160
1161#define OPTIONS(argc, argv, guts) do { \
1162 char **o_av = argv; \
1163 for (;; o_av++) { \
1164 if (!*o_av) \
1165 break; \
1166 if (mystrieq(*o_av, "--")) { \
1167 o_av++; \
1168 break; \
1169 } \
1170 guts \
1171 if (**o_av == '-') \
1172 goto bad_syntax; \
1173 break; \
1174 } \
1175 argc -= o_av - argv; \
1176 argv = o_av; \
1177} while (0)
1178
1179#define OPT(name, guts) if (mystrieq(*o_av, name)) { guts continue; }
1180
1181#define OPTARG(name, arg, guts) OPT(name, { \
1182 const char *arg; \
1183 arg = *++o_av; \
1184 if (!arg) goto bad_syntax; \
1185 guts \
1186})
1187
1188#define OPTTIME(name, arg, guts) OPTARG(name, o_arg, { \
1189 long arg; \
1190 if ((arg = a_parsetime(o_arg)) < 0) { \
1191 a_fail(a, "bad-time-spec", "%s", o_arg, A_END); \
1192 goto fail; \
1193 } \
1194 guts \
1195})
1196
37941236 1197/*----- Adding peers ------------------------------------------------------*/
1198
1199/* --- @a_doadd@ --- *
410c8acf 1200 *
37941236 1201 * Arguments: @admin_resop *r@ = resolver operation
1202 * @int rc@ = how it worked
410c8acf 1203 *
1204 * Returns: ---
1205 *
37941236 1206 * Use: Handles a completed resolution.
410c8acf 1207 */
1208
37941236 1209static void a_doadd(admin_resop *r, int rc)
410c8acf 1210{
37941236 1211 admin_addop *add = (admin_addop *)r;
1212
1213 T( trace(T_ADMIN, "admin: done add op %s", BGTAG(add)); )
1214
1215 if (rc == ARES_OK) {
1216 add->peer.sasz = add->r.sasz;
1217 add->peer.sa = add->r.sa;
c8e02c8a
MW
1218 if (p_findbyaddr(&add->r.sa))
1219 a_bgfail(&add->r.bg, "peer-addr-exists", "?ADDR", &add->r.sa, A_END);
1220 else if (p_find(add->peer.name))
f43df819 1221 a_bgfail(&add->r.bg, "peer-exists", "%s", add->peer.name, A_END);
37941236 1222 else if (!p_create(&add->peer))
f43df819 1223 a_bgfail(&add->r.bg, "peer-create-fail", "%s", add->peer.name, A_END);
37941236 1224 else
1225 a_bgok(&add->r.bg);
1226 }
de014da6 1227
48b84569 1228 if (add->peer.tag) xfree(add->peer.tag);
37941236 1229 xfree(add->peer.name);
410c8acf 1230}
1231
1232/* --- @acmd_add@ --- *
1233 *
1234 * Arguments: @admin *a@ = connection which requested the addition
1235 * @unsigned ac@ = argument count
1236 * @char *av[]@ = pointer to the argument list
1237 *
1238 * Returns: ---
1239 *
1240 * Use: Adds a new peer.
1241 */
1242
1243static void acmd_add(admin *a, unsigned ac, char *av[])
1244{
de014da6 1245 const char *tag = 0;
9986f0b5 1246 admin_addop *add;
410c8acf 1247
0ba8de86 1248 /* --- Set stuff up --- */
1249
de014da6 1250 add = xmalloc(sizeof(*add));
9986f0b5 1251 add->peer.name = 0;
48b84569 1252 add->peer.tag = 0;
de014da6 1253 add->peer.t_ka = 0;
1254 add->peer.tops = tun_default;
8743c776 1255 add->peer.f = 0;
37941236 1256
42da2a58 1257 /* --- Parse options --- */
1258
e7a4d919
MW
1259 OPTIONS(ac, av, {
1260 OPTARG("-background", arg, { tag = arg; })
1261 OPTARG("-tunnel", arg, {
1262 unsigned i;
1263 for (i = 0;; i++) {
1264 if (!tunnels[i]) {
1265 a_fail(a, "unknown-tunnel", "%s", arg, A_END);
37941236 1266 goto fail;
42da2a58 1267 }
e7a4d919
MW
1268 if (mystrieq(arg, tunnels[i]->name)) {
1269 add->peer.tops = tunnels[i];
42da2a58 1270 break;
1271 }
1272 }
e7a4d919
MW
1273 })
1274 OPTTIME("-keepalive", t, { add->peer.t_ka = t; })
8743c776 1275 OPT("-cork", { add->peer.f |= KXF_CORK; })
48b84569
MW
1276 OPTARG("-key", arg, {
1277 if (add->peer.tag)
1278 xfree(add->peer.tag);
1279 add->peer.tag = xstrdup(arg);
1280 })
6411163d 1281 OPT("-mobile", { add->peer.f |= PSF_MOBILE; })
e7a4d919 1282 });
42da2a58 1283
9986f0b5
MW
1284 /* --- Make sure someone's not got there already --- */
1285
bcf3764a 1286 if (!av[0] || !av[1])
9986f0b5 1287 goto bad_syntax;
e7a4d919
MW
1288 if (p_find(*av)) {
1289 a_fail(a, "peer-exists", "%s", *av, A_END);
9986f0b5 1290 goto fail;
42da2a58 1291 }
e7a4d919
MW
1292 add->peer.name = xstrdup(*av++);
1293 ac--;
42da2a58 1294
37941236 1295 /* --- Crank up the resolver --- */
de014da6 1296
e7a4d919 1297 a_resolve(a, &add->r, tag, a_doadd, ac, av);
42da2a58 1298 return;
1299
37941236 1300 /* --- Clearing up --- */
1301
42da2a58 1302bad_syntax:
9986f0b5 1303 a_fail(a, "bad-syntax", "add", "[OPTIONS] PEER ADDR ...", A_END);
de014da6 1304fail:
9986f0b5 1305 if (add->peer.name) xfree(add->peer.name);
48b84569 1306 if (add->peer.tag) xfree(add->peer.tag);
37941236 1307 xfree(add);
0ba8de86 1308 return;
1309}
1310
1311/*----- Ping --------------------------------------------------------------*/
1312
de014da6 1313/* --- @a_pingcancel@ --- *
1314 *
1315 * Arguments: @admin_bgop *bg@ = background operation block
1316 *
1317 * Returns: ---
1318 *
1319 * Use: Cancels a running ping.
1320 */
1321
1322static void a_pingcancel(admin_bgop *bg)
1323{
1324 admin_pingop *pg = (admin_pingop *)bg;
060ca767 1325 T( trace(T_ADMIN, "admin: cancel ping op %s", BGTAG(pg)); )
de014da6 1326 p_pingdone(&pg->ping, PING_NONOTIFY);
1327}
1328
0ba8de86 1329/* --- @a_pong@ --- *
1330 *
1331 * Arguments: @int rc@ = return code
de014da6 1332 * @void *v@ = ping operation block
0ba8de86 1333 *
1334 * Returns: ---
1335 *
1336 * Use: Collects what happened to a ping message.
1337 */
1338
de014da6 1339static void a_pong(int rc, void *v)
0ba8de86 1340{
de014da6 1341 admin_pingop *pg = v;
0ba8de86 1342 struct timeval tv;
1343 double millis;
1344
0ba8de86 1345 switch (rc) {
1346 case PING_OK:
1347 gettimeofday(&tv, 0);
de014da6 1348 tv_sub(&tv, &tv, &pg->pingtime);
0ba8de86 1349 millis = (double)tv.tv_sec * 1000 + (double)tv.tv_usec/1000;
f43df819 1350 a_bginfo(&pg->bg, "ping-ok", "%.1f", millis, A_END);
de014da6 1351 a_bgok(&pg->bg);
0ba8de86 1352 break;
1353 case PING_TIMEOUT:
f43df819 1354 a_bginfo(&pg->bg, "ping-timeout", A_END);
de014da6 1355 a_bgok(&pg->bg);
0ba8de86 1356 break;
1357 case PING_PEERDIED:
f43df819 1358 a_bginfo(&pg->bg, "ping-peer-died", A_END);
de014da6 1359 a_bgok(&pg->bg);
0ba8de86 1360 break;
1361 default:
1362 abort();
1363 }
060ca767 1364 T( trace(T_ADMIN, "admin: ponged ping op %s", BGTAG(pg)); )
de014da6 1365 a_bgrelease(&pg->bg);
0ba8de86 1366}
1367
1368/* --- @acmd_ping@, @acmd_eping@ --- *
1369 *
1370 * Arguments: @admin *a@ = connection which requested the ping
1371 * @unsigned ac@ = argument count
1372 * @char *av[]@ = pointer to the argument list
1373 *
1374 * Returns: ---
1375 *
1376 * Use: Pings a peer.
1377 */
1378
1379static void a_ping(admin *a, unsigned ac, char *av[],
1380 const char *cmd, unsigned msg)
1381{
1382 long t = T_PING;
0ba8de86 1383 peer *p;
de014da6 1384 admin_pingop *pg = 0;
1385 const char *tag = 0;
0ba8de86 1386
e7a4d919
MW
1387 OPTIONS(ac, av, {
1388 OPTARG("-background", arg, { tag = arg; })
1389 OPTTIME("-timeout", arg, { t = arg; })
1390 });
1391 if (!*av || av[1]) goto bad_syntax;
1392 if ((p = a_findpeer(a, *av)) == 0)
0ba8de86 1393 return;
de014da6 1394 pg = xmalloc(sizeof(*pg));
1395 gettimeofday(&pg->pingtime, 0);
ff92ffd3
MW
1396 if (a_bgadd(a, &pg->bg, tag, a_pingcancel))
1397 goto fail;
060ca767 1398 T( trace(T_ADMIN, "admin: ping op %s: %s to %s",
1399 BGTAG(pg), cmd, p_name(p)); )
de014da6 1400 if (p_pingsend(p, &pg->ping, msg, t, a_pong, pg)) {
f43df819 1401 a_bgfail(&pg->bg, "ping-send-failed", A_END);
de014da6 1402 a_bgrelease(&pg->bg);
1403 }
0ba8de86 1404 return;
e04c2d50 1405
0ba8de86 1406bad_syntax:
f43df819 1407 a_fail(a, "bad-syntax", "%s", cmd, "[OPTIONS] PEER", cmd, A_END);
e7a4d919 1408fail:
ff92ffd3 1409 if (pg) xfree(pg);
42da2a58 1410 return;
410c8acf 1411}
1412
0ba8de86 1413static void acmd_ping(admin *a, unsigned ac, char *av[])
1414 { a_ping(a, ac, av, "ping", MISC_PING); }
1415static void acmd_eping(admin *a, unsigned ac, char *av[])
1416 { a_ping(a, ac, av, "eping", MISC_EPING); }
0ba8de86 1417
be6a1b7a
MW
1418/*----- Service commands --------------------------------------------------*/
1419
1420static void acmd_svcclaim(admin *a, unsigned ac, char *av[])
1421{
1422 admin_service *svc;
1423 unsigned f;
1424
1425 svc = sym_find(&a_svcs, av[0], -1, sizeof(*svc), &f);
1426 if (f) {
1427 if (versioncmp(av[1], svc->version) <= 0) {
1428 a_fail(a,
1429 "service-exists",
1430 "%s", SYM_NAME(svc),
1431 "%s", svc->version,
1432 A_END);
1433 return;
1434 }
1435 a_write(svc->prov, "SVCCLAIM", 0, "%s", av[0], "%s", av[1], A_END);
1436 a_svcunlink(svc);
1437 }
1438 svc->prov = a;
1439 svc->version = xstrdup(av[1]);
1440 svc->next = a->svcs;
1441 svc->prev = 0;
1442 if (a->svcs) a->svcs->prev = svc;
1443 a->svcs = svc;
1444 a_notify("SVCCLAIM", "%s", SYM_NAME(svc), "%s", svc->version, A_END);
1445 a_ok(a);
1446}
1447
1448static void acmd_svcrelease(admin *a, unsigned ac, char *av[])
1449{
1450 admin_service *svc;
1451
1452 if ((svc = a_svcfind(a, av[0])) == 0)
1453 return;
1454 if (svc->prov != a) {
1455 a_fail(a, "not-service-provider", "%s", SYM_NAME(svc), A_END);
1456 return;
1457 }
1458 a_svcrelease(svc);
1459 a_ok(a);
1460}
1461
1462static void acmd_svcensure(admin *a, unsigned ac, char *av[])
1463{
1464 admin_service *svc;
1465
1466 if ((svc = a_svcfind(a, av[0])) == 0)
1467 return;
1468 if (av[1] && versioncmp(svc->version, av[1]) < 0) {
1469 a_fail(a, "service-too-old",
1470 "%s", SYM_NAME(svc),
1471 "%s", svc->version,
1472 A_END);
1473 return;
1474 }
1475 a_ok(a);
1476}
1477
1478static void acmd_svcquery(admin *a, unsigned ac, char *av[])
1479{
1480 admin_service *svc;
1481
1482 if ((svc = a_svcfind(a, av[0])) != 0) {
1483 a_info(a, "name=%s", SYM_NAME(svc), "version=%s", svc->version, A_END);
1484 a_ok(a);
1485 }
1486}
1487
1488static void acmd_svclist(admin *a, unsigned ac, char *av[])
1489{
1490 admin_service *svc;
1491 sym_iter i;
1492
1493 for (sym_mkiter(&i, &a_svcs); (svc = sym_next(&i)) != 0; )
1494 a_info(a, "%s", SYM_NAME(svc), "%s", svc->version, A_END);
1495 a_ok(a);
1496}
1497
ef2f29c9
MW
1498static void a_canceljob(admin_bgop *bg)
1499{
1500 admin_svcop *svc = (admin_svcop *)bg;
1501
1502 a_write(svc->prov, "SVCCANCEL", 0, "%s", a_jobidencode(svc), A_END);
1503 a_jobdestroy(svc);
1504}
1505
1506static void acmd_svcsubmit(admin *a, unsigned ac, char *av[])
1507{
1508 const char *tag = 0;
1509 admin_service *svc;
1510 admin_svcop *svcop;
1511 const char *ver = 0;
1512 dstr d = DSTR_INIT;
1513
1514 OPTIONS(ac, av, {
1515 OPTARG("-background", arg, { tag = arg; })
1516 OPTARG("-version", arg, { ver = arg; })
1517 });
1518 if (!*av) goto bad_syntax;
1519 if ((svc = a_svcfind(a, *av)) == 0) goto fail;
1520 if (ver && versioncmp(svc->version, ver) < 0) {
1521 a_fail(a, "service-too-old",
1522 "%s", SYM_NAME(svc),
1523 "%s", svc->version,
1524 A_END);
1525 goto fail;
1526 }
1527 if ((svcop = a_jobcreate(svc->prov)) == 0) {
1528 a_fail(a, "provider-overloaded", A_END);
1529 goto fail;
1530 }
1531 if (a_bgadd(a, &svcop->bg, tag, a_canceljob)) {
1532 a_jobdestroy(svcop);
1533 goto fail;
1534 }
1535 a_write(svc->prov, "SVCJOB", 0,
1536 "%s", a_jobidencode(svcop),
1537 "?TOKENS", av,
1538 A_END);
1539 goto done;
1540
1541bad_syntax:
1542 a_fail(a, "bad-syntax", "svcsubmit", "[OPTIONS] SERVICE ARGS...", A_END);
1543fail:
1544done:
1545 dstr_destroy(&d);
1546 return;
1547}
1548
1549static void a_replycmd(admin *a, const char *status, int donep, char *av[])
1550{
1551 admin_svcop *svc;
1552
1553 if ((svc = a_jobiddecode(&a->j, av[0])) == 0) {
1554 a_fail(a, "unknown-jobid", av[0], A_END);
1555 return;
1556 }
1557 a_write(svc->bg.a, status, svc->bg.tag, "?TOKENS", av + 1, A_END);
1558 if (donep) {
1559 a_jobdestroy(svc);
1560 a_bgrelease(&svc->bg);
1561 }
1562 a_ok(a);
1563}
1564
1565static void acmd_svcok(admin *a, unsigned ac, char *av[])
1566 { a_replycmd(a, "OK", 1, av); }
1567static void acmd_svcinfo(admin *a, unsigned ac, char *av[])
1568 { a_replycmd(a, "INFO", 0, av); }
1569static void acmd_svcfail(admin *a, unsigned ac, char *av[])
1570 { a_replycmd(a, "FAIL", 1, av); }
1571
410c8acf 1572/*----- Administration commands -------------------------------------------*/
1573
1574/* --- Miscellaneous commands --- */
1575
3cdc3f3a 1576/* --- @traceish@ --- *
1577 *
1578 * Arguments: @admin *a@ = connection to complain on
1579 * @unsigned ac@ = number of arguments
1580 * @char *av[]@ = vector of arguments
1581 * @const char *what@ = what we're messing with
1582 * @const trace_opt *tt@ = options table
1583 * @unsigned *ff@ = where the flags are
1584 *
1585 * Returns: Nonzero if anything changed.
1586 *
1587 * Use: Guts of trace-ish commands like `trace' and `watch'.
1588 */
410c8acf 1589
3cdc3f3a 1590static int traceish(admin *a, unsigned ac, char *av[],
1591 const char *what, const trace_opt *tt, unsigned *ff)
410c8acf 1592{
3cdc3f3a 1593 int ch = 0;
1594
410c8acf 1595 if (!ac || strcmp(av[0], "?") == 0) {
1596 const trace_opt *t;
3cdc3f3a 1597 for (t = tt; t->ch; t++) {
f43df819
MW
1598 a_info(a, "*%c%c %s",
1599 t->ch, (*ff & t->f) == t->f ? '+' : ' ', t->help, A_END);
410c8acf 1600 }
1601 } else {
1602 unsigned sense = 1;
3cdc3f3a 1603 unsigned f = *ff;
1604 const trace_opt *t;
410c8acf 1605 char *p = av[0];
1606
1607 while (*p) {
1608 switch (*p) {
1609 case '+': sense = 1; break;
1610 case '-': sense = 0; break;
1611 default:
3cdc3f3a 1612 for (t = tt; t->ch; t++) {
1613 if (t->ch == *p) {
1614 if (sense) f |= t->f;
1615 else f &= ~t->f;
410c8acf 1616 goto tropt_ok;
1617 }
1618 }
f43df819 1619 a_fail(a, "bad-%s-option", what, "%c", *p, A_END);
3cdc3f3a 1620 return (0);
e04c2d50 1621 tropt_ok:;
410c8acf 1622 break;
1623 }
1624 p++;
1625 }
3cdc3f3a 1626 *ff = f;
1627 ch = 1;
410c8acf 1628 }
3cdc3f3a 1629 a_ok(a);
1630 return (ch);
1631}
1632
1633#ifndef NTRACE
1634
1635static void acmd_trace(admin *a, unsigned ac, char *av[])
1636{
1637 if (traceish(a, ac, av, "trace", tr_opts, &tr_flags))
1638 trace_level(tr_flags);
410c8acf 1639}
1640
1641#endif
1642
3cdc3f3a 1643static void acmd_watch(admin *a, unsigned ac, char *av[])
f98df549 1644 { traceish(a, ac, av, "watch", w_opts, &a->f); }
3cdc3f3a 1645
3cdc3f3a 1646static void alertcmd(admin *a, unsigned f_and, unsigned f_eq,
3331936b
MW
1647 const char *status, char *av[])
1648 { a_alert(f_and, f_eq, status, "USER", "?TOKENS", av, A_END); a_ok(a); }
3cdc3f3a 1649static void acmd_notify(admin *a, unsigned ac, char *av[])
3331936b 1650 { alertcmd(a, AF_NOTE, AF_NOTE, "NOTE", av); }
3cdc3f3a 1651static void acmd_warn(admin *a, unsigned ac, char *av[])
3331936b 1652 { alertcmd(a, AF_WARN, AF_WARN, "WARN", av); }
3cdc3f3a 1653
410c8acf 1654static void acmd_port(admin *a, unsigned ac, char *av[])
f98df549 1655 { a_info(a, "%u", p_port(), A_END); a_ok(a); }
410c8acf 1656
410c8acf 1657static void acmd_daemon(admin *a, unsigned ac, char *av[])
1658{
1659 if (flags & F_DAEMON)
f43df819 1660 a_fail(a, "already-daemon", A_END);
410c8acf 1661 else {
f43df819 1662 a_notify("DAEMON", A_END);
93bee2c4 1663 if (a_stdin)
410c8acf 1664 a_destroy(a_stdin);
19dd2531 1665 if (daemonize())
f43df819 1666 a_fail(a, "daemon-error", "?ERRNO", A_END);
93bee2c4 1667 else {
410c8acf 1668 flags |= F_DAEMON;
3cdc3f3a 1669 a_ok(a);
93bee2c4 1670 }
410c8acf 1671 }
1672}
1673
ff92ffd3
MW
1674static void acmd_jobs(admin *a, unsigned ac, char *av[])
1675{
1676 admin_bgop *bg;
1677
1678 for (bg = a->bg; bg; bg = bg->next) {
1679 assert(bg->tag);
1680 a_info(a, "%s", bg->tag, A_END);
1681 }
1682 a_ok(a);
1683}
1684
1685static void acmd_bgcancel(admin *a, unsigned ac, char *av[])
1686{
1687 admin_bgop *bg;
1688
1689 if ((bg = a_bgfind(a, av[0])) == 0)
1690 a_fail(a, "unknown-tag", "%s", av[0], A_END);
1691 else {
1692 bg->cancel(bg);
1693 a_bgrelease(bg);
1694 a_ok(a);
1695 }
1696}
1697
449991a3
MW
1698static void acmd_algs(admin *a, unsigned ac, char *av[])
1699{
1700 a_info(a,
1701 "kx-group=%s", gg->ops->name,
1702 "kx-group-order-bits=%lu", (unsigned long)mp_bits(gg->r),
1703 "kx-group-elt-bits=%lu", (unsigned long)gg->nbits,
1704 A_END);
1705 a_info(a,
1706 "hash=%s", algs.h->name,
1707 "mgf=%s", algs.mgf->name,
1708 "hash-sz=%lu", (unsigned long)algs.h->hashsz,
1709 A_END);
1710 a_info(a,
1711 "cipher=%s", algs.c->name,
1712 "cipher-keysz=%lu", (unsigned long)algs.cksz,
1713 "cipher-blksz=%lu", (unsigned long)algs.c->blksz,
1714 A_END);
1715 a_info(a,
1716 "cipher-data-limit=%lu", (unsigned long)algs.expsz,
1717 A_END);
1718 a_info(a,
1719 "mac=%s", algs.m->name,
1720 "mac-keysz=%lu", (unsigned long)algs.mksz,
1721 "mac-tagsz=%lu", (unsigned long)algs.tagsz,
1722 A_END);
1723 a_ok(a);
1724}
1725
410c8acf 1726static void acmd_list(admin *a, unsigned ac, char *av[])
1727{
c8e02c8a 1728 FOREACH_PEER(p, { a_info(a, "%s", p_name(p), A_END); });
3cdc3f3a 1729 a_ok(a);
410c8acf 1730}
1731
1732static void acmd_ifname(admin *a, unsigned ac, char *av[])
1733{
1734 peer *p;
1735
37941236 1736 if ((p = a_findpeer(a, av[0])) != 0) {
f43df819 1737 a_info(a, "%s", p_ifname(p), A_END);
3cdc3f3a 1738 a_ok(a);
1739 }
410c8acf 1740}
1741
64cf2223
MW
1742static void acmd_setifname(admin *a, unsigned ac, char *av[])
1743{
1744 peer *p;
1745
1746 if ((p = a_findpeer(a, av[0])) != 0) {
1747 a_notify("NEWIFNAME", "?PEER", p, "%s", p_ifname(p), "%s", av[1], A_END);
1748 p_setifname(p, av[1]);
1749 a_ok(a);
e04c2d50 1750 }
64cf2223
MW
1751}
1752
37941236 1753static void acmd_getchal(admin *a, unsigned ac, char *av[])
1754{
1755 buf b;
1756
1757 buf_init(&b, buf_i, PKBUFSZ);
1758 c_new(&b);
f43df819 1759 a_info(a, "?B64", BBASE(&b), (size_t)BLEN(&b), A_END);
37941236 1760 a_ok(a);
1761}
1762
1763static void acmd_checkchal(admin *a, unsigned ac, char *av[])
1764{
1765 base64_ctx b64;
1766 buf b;
1767 dstr d = DSTR_INIT;
1768
1769 base64_init(&b64);
1770 base64_decode(&b64, av[0], strlen(av[0]), &d);
1771 base64_decode(&b64, 0, 0, &d);
1772 buf_init(&b, d.buf, d.len);
1773 if (c_check(&b) || BBAD(&b) || BLEFT(&b))
f43df819 1774 a_fail(a, "invalid-challenge", A_END);
37941236 1775 else
1776 a_ok(a);
1777 dstr_destroy(&d);
1778}
1779
1780static void acmd_greet(admin *a, unsigned ac, char *av[])
1781{
1782 peer *p;
1783 base64_ctx b64;
1784 dstr d = DSTR_INIT;
1785
1786 if ((p = a_findpeer(a, av[0])) != 0) {
1787 base64_init(&b64);
1788 base64_decode(&b64, av[1], strlen(av[1]), &d);
1789 base64_decode(&b64, 0, 0, &d);
1790 p_greet(p, d.buf, d.len);
1791 dstr_destroy(&d);
1792 a_ok(a);
1793 }
1794}
1795
410c8acf 1796static void acmd_addr(admin *a, unsigned ac, char *av[])
1797{
1798 peer *p;
1799 const addr *ad;
1800
37941236 1801 if ((p = a_findpeer(a, av[0])) != 0) {
410c8acf 1802 ad = p_addr(p);
1803 assert(ad->sa.sa_family == AF_INET);
f43df819 1804 a_info(a, "?ADDR", ad, A_END);
3cdc3f3a 1805 a_ok(a);
410c8acf 1806 }
1807}
1808
060ca767 1809static void acmd_peerinfo(admin *a, unsigned ac, char *av[])
1810{
1811 peer *p;
1812 const peerspec *ps;
1813
37941236 1814 if ((p = a_findpeer(a, av[0])) != 0) {
1815 ps = p_spec(p);
f43df819 1816 a_info(a, "tunnel=%s", ps->tops->name, A_END);
e55761b1 1817 a_info(a, "key=%s", p_tag(p), A_END);
f43df819 1818 a_info(a, "keepalive=%lu", ps->t_ka, A_END);
37941236 1819 a_ok(a);
060ca767 1820 }
060ca767 1821}
1822
1823static void acmd_servinfo(admin *a, unsigned ac, char *av[])
1824{
f43df819
MW
1825 a_info(a, "implementation=edgeware-tripe", A_END);
1826 a_info(a, "version=%s", VERSION, A_END);
1827 a_info(a, "daemon=%s", BOOL(flags & F_DAEMON), A_END);
060ca767 1828 a_ok(a);
1829}
1830
c7053da9 1831static void acmd_stats(admin *a, unsigned ac, char *av[])
1832{
1833 peer *p;
1834 stats *st;
1835
37941236 1836 if ((p = a_findpeer(a, av[0])) == 0)
060ca767 1837 return;
060ca767 1838
1839 st = p_stats(p);
f43df819
MW
1840 a_info(a, "start-time=%s", timestr(st->t_start), A_END);
1841 a_info(a, "last-packet-time=%s", timestr(st->t_last), A_END);
1842 a_info(a, "last-keyexch-time=%s", timestr(st->t_kx), A_END);
18ad8913
MW
1843 a_info(a, "packets-in=%lu", st->n_in, "bytes-in=%lu", st->sz_in, A_END);
1844 a_info(a,
1845 "packets-out=%lu", st->n_out,
1846 "bytes-out=%lu", st->sz_out,
1847 A_END);
1848 a_info(a,
1849 "keyexch-packets-in=%lu", st->n_kxin,
1850 "keyexch-bytes-in=%lu", st->sz_kxin,
1851 A_END);
1852 a_info(a,
1853 "keyexch-packets-out=%lu", st->n_kxout,
1854 "keyexch-bytes-out=%lu", st->sz_kxout,
1855 A_END);
1856 a_info(a,
1857 "ip-packets-in=%lu", st->n_ipin,
1858 "ip-bytes-in=%lu", st->sz_ipin,
1859 A_END);
1860 a_info(a,
e04c2d50 1861 "ip-packets-out=%lu", st->n_ipout,
18ad8913
MW
1862 "ip-bytes-out=%lu", st->sz_ipout,
1863 A_END);
f43df819 1864 a_info(a, "rejected-packets=%lu", st->n_reject, A_END);
060ca767 1865 a_ok(a);
c7053da9 1866}
1867
410c8acf 1868static void acmd_kill(admin *a, unsigned ac, char *av[])
1869{
1870 peer *p;
f98df549 1871
37941236 1872 if ((p = a_findpeer(a, av[0])) != 0) {
410c8acf 1873 p_destroy(p);
3cdc3f3a 1874 a_ok(a);
410c8acf 1875 }
1876}
1877
0ba8de86 1878static void acmd_forcekx(admin *a, unsigned ac, char *av[])
1879{
1880 peer *p;
f98df549 1881
37941236 1882 if ((p = a_findpeer(a, av[0])) != 0) {
de014da6 1883 kx_start(&p->kx, 1);
0ba8de86 1884 a_ok(a);
1885 }
1886}
1887
de014da6 1888static void acmd_reload(admin *a, unsigned ac, char *av[])
1889 { p_keyreload(); a_ok(a); }
1890
410c8acf 1891static void acmd_quit(admin *a, unsigned ac, char *av[])
1892{
f43df819 1893 a_warn("SERVER", "quit", "admin-request", A_END);
3cdc3f3a 1894 a_ok(a);
410c8acf 1895 a_quit();
1896}
1897
3cdc3f3a 1898static void acmd_version(admin *a, unsigned ac, char *av[])
1899{
f43df819 1900 a_info(a, "%s", PACKAGE, "%s", VERSION, A_END);
3cdc3f3a 1901 a_ok(a);
1902}
1903
42da2a58 1904static void acmd_tunnels(admin *a, unsigned ac, char *av[])
1905{
1906 int i;
f98df549 1907
42da2a58 1908 for (i = 0; tunnels[i]; i++)
f43df819 1909 a_info(a, "%s", tunnels[i]->name, A_END);
42da2a58 1910 a_ok(a);
1911}
1912
410c8acf 1913/* --- The command table and help --- */
1914
1915typedef struct acmd {
1916 const char *name;
1917 const char *help;
1918 unsigned argmin, argmax;
1919 void (*func)(admin */*a*/, unsigned /*ac*/, char */*av*/[]);
1920} acmd;
1921
1922static void acmd_help(admin */*a*/, unsigned /*ac*/, char */*av*/[]);
1923
1924static const acmd acmdtab[] = {
9986f0b5 1925 { "add", "[OPTIONS] PEER ADDR ...", 2, 0xffff, acmd_add },
f43df819 1926 { "addr", "PEER", 1, 1, acmd_addr },
449991a3 1927 { "algs", 0, 0, 0, acmd_algs },
ff92ffd3 1928 { "bgcancel", "TAG", 1, 1, acmd_bgcancel },
f43df819
MW
1929 { "checkchal", "CHAL", 1, 1, acmd_checkchal },
1930 { "daemon", 0, 0, 0, acmd_daemon },
1931 { "eping", "[OPTIONS] PEER", 1, 0xffff, acmd_eping },
1932 { "forcekx", "PEER", 1, 1, acmd_forcekx },
1933 { "getchal", 0, 0, 0, acmd_getchal },
1934 { "greet", "PEER CHAL", 2, 2, acmd_greet },
1935 { "help", 0, 0, 0, acmd_help },
1936 { "ifname", "PEER", 1, 1, acmd_ifname },
ff92ffd3 1937 { "jobs", 0, 0, 0, acmd_jobs },
f43df819
MW
1938 { "kill", "PEER", 1, 1, acmd_kill },
1939 { "list", 0, 0, 0, acmd_list },
1940 { "notify", "MESSAGE ...", 1, 0xffff, acmd_notify },
1941 { "peerinfo", "PEER", 1, 1, acmd_peerinfo },
1942 { "ping", "[OPTIONS] PEER", 1, 0xffff, acmd_ping },
1943 { "port", 0, 0, 0, acmd_port },
1944 { "quit", 0, 0, 0, acmd_quit },
1945 { "reload", 0, 0, 0, acmd_reload },
1946 { "servinfo", 0, 0, 0, acmd_servinfo },
64cf2223 1947 { "setifname", "PEER NEW-NAME", 2, 2, acmd_setifname },
be6a1b7a
MW
1948 { "svcclaim", "SERVICE VERSION", 2, 2, acmd_svcclaim },
1949 { "svcensure", "SERVICE [VERSION]", 1, 2, acmd_svcensure },
ef2f29c9
MW
1950 { "svcfail", "JOBID TOKENS...", 1, 0xffff, acmd_svcfail },
1951 { "svcinfo", "JOBID TOKENS...", 1, 0xffff, acmd_svcinfo },
be6a1b7a 1952 { "svclist", 0, 0, 0, acmd_svclist },
ef2f29c9 1953 { "svcok", "JOBID", 1, 1, acmd_svcok },
be6a1b7a
MW
1954 { "svcquery", "SERVICE", 1, 1, acmd_svcquery },
1955 { "svcrelease", "SERVICE", 1, 1, acmd_svcrelease },
ef2f29c9
MW
1956 { "svcsubmit", "[OPTIONS] SERVICE TOKENS...",
1957 2, 0xffff, acmd_svcsubmit },
f43df819 1958 { "stats", "PEER", 1, 1, acmd_stats },
de014da6 1959#ifndef NTRACE
f43df819 1960 { "trace", "[OPTIONS]", 0, 1, acmd_trace },
de014da6 1961#endif
f43df819
MW
1962 { "tunnels", 0, 0, 0, acmd_tunnels },
1963 { "version", 0, 0, 0, acmd_version },
1964 { "warn", "MESSAGE ...", 1, 0xffff, acmd_warn },
e04c2d50 1965 { "watch", "[OPTIONS]", 0, 1, acmd_watch },
410c8acf 1966 { 0, 0, 0, 0, 0 }
1967};
1968
1969static void acmd_help(admin *a, unsigned ac, char *av[])
1970{
1971 const acmd *c;
f98df549 1972
f43df819
MW
1973 for (c = acmdtab; c->name; c++) {
1974 if (c->help)
1975 a_info(a, "%s", c->name, "*%s", c->help, A_END);
e04c2d50 1976 else
f43df819
MW
1977 a_info(a, "%s", c->name, A_END);
1978 }
3cdc3f3a 1979 a_ok(a);
410c8acf 1980}
1981
1982/*----- Connection handling -----------------------------------------------*/
1983
c511e1f9 1984/* --- @a_destroypending@ --- *
410c8acf 1985 *
c511e1f9 1986 * Arguments: ---
fd3cf232 1987 *
1988 * Returns: ---
1989 *
c511e1f9 1990 * Use: Destroys pending admin connections at a safe time.
fd3cf232 1991 */
1992
c511e1f9 1993static void a_destroypending(void)
410c8acf 1994{
94593d1b 1995 admin *a, *aa, *head;
de014da6 1996 admin_bgop *bg, *bbg;
be6a1b7a 1997 admin_service *svc, *ssvc;
de014da6 1998
94593d1b
MW
1999 /* --- Destroy connections marked as pending --- *
2000 *
2001 * Slightly messy. Killing clients may cause others to finally die. Make
2002 * sure that they can be put on the list without clobbering anything or
2003 * getting lost.
2004 */
fd3cf232 2005
94593d1b
MW
2006 while (a_dead) {
2007 head = a_dead;
2008 a_dead = 0;
2009 for (a = head; a; a = aa) {
2010 aa = a->next;
2011 assert(a->f & AF_DEAD);
c511e1f9 2012
94593d1b 2013 /* --- Report what we're doing --- */
c511e1f9 2014
94593d1b
MW
2015 T( trace(T_ADMIN, "admin: completing destruction of connection %u",
2016 a->seq); )
c511e1f9 2017
94593d1b 2018 /* --- If this is the foreground client then shut down --- */
46dde080 2019
94593d1b
MW
2020 if (a->f & AF_FOREGROUND) {
2021 T( trace(T_ADMIN, "admin: foreground client quit: shutting down"); )
2022 a_warn("SERVER", "quit", "foreground-eof", A_END);
2023 a_quit();
2024 }
46dde080 2025
94593d1b 2026 /* --- Abort any background jobs in progress --- */
c511e1f9 2027
94593d1b
MW
2028 for (bg = a->bg; bg; bg = bbg) {
2029 bbg = bg->next;
2030 bg->cancel(bg);
2031 if (bg->tag) xfree(bg->tag);
2032 xfree(bg);
2033 }
c511e1f9 2034
94593d1b 2035 /* --- Release services I hold, and abort pending jobs --- */
be6a1b7a 2036
94593d1b
MW
2037 for (svc = a->svcs; svc; svc = ssvc) {
2038 ssvc = svc->next;
2039 a_svcrelease(svc);
2040 }
2041 a_jobtablefinal(&a->j);
be6a1b7a 2042
94593d1b 2043 /* --- Close file descriptors and selectory --- */
c511e1f9 2044
94593d1b
MW
2045 selbuf_destroy(&a->b);
2046 if (a->b.reader.fd != a->w.fd) close(a->b.reader.fd);
2047 close(a->w.fd);
2048 if (a_stdin == a) a_stdin = 0;
c511e1f9 2049
94593d1b 2050 /* --- Done --- */
c511e1f9 2051
94593d1b
MW
2052 DESTROY(a);
2053 }
410c8acf 2054 }
060ca767 2055}
2056
fd3cf232 2057/* --- @a_destroy@ --- *
2058 *
2059 * Arguments: @admin *a@ = pointer to an admin block
2060 *
2061 * Returns: ---
2062 *
2063 * Use: Destroys an admin block. This requires a certain amount of
2064 * care.
2065 */
2066
de014da6 2067static void freequeue(oqueue *q)
2068{
2069 obuf *o, *oo;
2070
2071 for (o = q->hd; o; o = oo) {
2072 oo = o->next;
2073 xfree(o);
2074 }
2075 q->hd = q->tl = 0;
2076}
2077
fd3cf232 2078static void a_destroy(admin *a)
2079{
fd3cf232 2080 if (a->f & AF_DEAD)
2081 return;
2082
c511e1f9
MW
2083 if (a->next) a->next->prev = a->prev;
2084 if (a->prev) a->prev->next = a->next;
2085 else admins = a->next;
fd3cf232 2086
c511e1f9 2087 if (a->out.hd) sel_rmfile(&a->w);
de014da6 2088 freequeue(&a->out);
fd3cf232 2089
c511e1f9
MW
2090 a->f |= AF_DEAD;
2091 a->next = a_dead;
2092 a_dead = a;
fd3cf232 2093
c511e1f9 2094 T( trace(T_ADMIN, "admin: killing connection %u", a->seq); )
fd3cf232 2095}
2096
410c8acf 2097/* --- @a_line@ --- *
2098 *
2099 * Arguments: @char *p@ = pointer to the line read
3008eabf 2100 * @size_t len@ = length of the line
410c8acf 2101 * @void *vp@ = pointer to my admin block
2102 *
2103 * Returns: ---
2104 *
2105 * Use: Handles a line of input.
2106 */
2107
3008eabf 2108static void a_line(char *p, size_t len, void *vp)
410c8acf 2109{
2110 admin *a = vp;
2111 const acmd *c;
6f88042a 2112 char *av[16 + 1];
410c8acf 2113 size_t ac;
2114
8d0c7a83 2115 TIMER;
fd3cf232 2116 if (a->f & AF_DEAD)
2117 return;
410c8acf 2118 if (!p) {
de014da6 2119 if (!a->bg)
2120 a_destroy(a);
2121 else {
2122 a->f |= AF_CLOSE;
2123 selbuf_disable(&a->b);
2124 }
410c8acf 2125 return;
2126 }
6f88042a 2127 ac = str_qsplit(p, av, N(av) - 1, 0, STRF_QUOTE);
410c8acf 2128 if (!ac)
2129 return;
6f88042a 2130 av[ac] = 0;
410c8acf 2131 for (c = acmdtab; c->name; c++) {
3cdc3f3a 2132 if (mystrieq(av[0], c->name)) {
410c8acf 2133 ac--;
f43df819
MW
2134 if (c->argmin > ac || ac > c->argmax) {
2135 if (!c->help)
2136 a_fail(a, "bad-syntax", "%s", c->name, "", A_END);
e04c2d50 2137 else
f43df819 2138 a_fail(a, "bad-syntax", "%s", c->name, "%s", c->help, A_END);
c511e1f9 2139 } else
410c8acf 2140 c->func(a, ac, av + 1);
2141 return;
2142 }
2143 }
f43df819 2144 a_fail(a, "unknown-command", "%s", av[0], A_END);
410c8acf 2145}
2146
2147/* --- @a_create@ --- *
2148 *
2149 * Arguments: @int fd_in, fd_out@ = file descriptors to use
3cdc3f3a 2150 * @unsigned f@ = initial flags to set
410c8acf 2151 *
2152 * Returns: ---
2153 *
2154 * Use: Creates a new admin connection.
2155 */
2156
3cdc3f3a 2157void a_create(int fd_in, int fd_out, unsigned f)
410c8acf 2158{
2159 admin *a = CREATE(admin);
3cdc3f3a 2160
93bee2c4 2161 T( static unsigned seq = 0;
2162 a->seq = seq++; )
410c8acf 2163 T( trace(T_ADMIN, "admin: accepted connection %u", a->seq); )
de014da6 2164 a->bg = 0;
042d5c20 2165 a->ref = 0;
be6a1b7a 2166 a->svcs = 0;
5d46c0f8 2167 a_jobtableinit(&a->j);
3cdc3f3a 2168 a->f = f;
de014da6 2169 if (fd_in == STDIN_FILENO) a_stdin = a;
fd3cf232 2170 fdflags(fd_in, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
410c8acf 2171 if (fd_out != fd_in)
fd3cf232 2172 fdflags(fd_out, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
410c8acf 2173 selbuf_init(&a->b, &sel, fd_in, a_line, a);
fd3cf232 2174 sel_initfile(&sel, &a->w, fd_out, SEL_WRITE, a_flush, a);
de014da6 2175 a->out.hd = a->out.tl = 0;
410c8acf 2176 a->next = admins;
2177 a->prev = 0;
de014da6 2178 if (admins) admins->prev = a;
410c8acf 2179 admins = a;
2180}
2181
2182/* --- @a_accept@ --- *
2183 *
2184 * Arguments: @int fd@ = file descriptor to accept
2185 * @unsigned mode@ = what to do
2186 * @void *v@ = uninteresting pointer
2187 *
2188 * Returns: ---
2189 *
2190 * Use: Accepts a new admin connection.
2191 */
2192
2193static void a_accept(int fd, unsigned mode, void *v)
2194{
2195 int nfd;
2196 struct sockaddr_un sun;
2197 size_t sz = sizeof(sun);
2198
2199 if ((nfd = accept(fd, (struct sockaddr *)&sun, &sz)) < 0) {
1ecee057 2200 if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK &&
2201 errno != ECONNABORTED && errno != EPROTO)
f43df819 2202 a_warn("ADMIN", "accept-error", "?ERRNO", A_END);
410c8acf 2203 return;
2204 }
3cdc3f3a 2205 a_create(nfd, nfd, 0);
410c8acf 2206}
2207
c511e1f9
MW
2208/* --- @a_preselect@ --- *
2209 *
2210 * Arguments: ---
2211 *
2212 * Returns: ---
2213 *
2214 * Use: Informs the admin module that we're about to select again,
2215 * and that it should do cleanup things it has delayed until a
2216 * `safe' time.
2217 */
2218
2219void a_preselect(void) { if (a_dead) a_destroypending(); }
2220
410c8acf 2221/* --- @a_daemon@ --- *
2222 *
2223 * Arguments: ---
2224 *
2225 * Returns: ---
2226 *
2227 * Use: Informs the admin module that it's a daemon.
2228 */
2229
f98df549 2230void a_daemon(void) { flags |= F_DAEMON; }
410c8acf 2231
2232/* --- @a_init@ --- *
2233 *
2234 * Arguments: @const char *name@ = socket name to create
aa2405e8
MW
2235 * @uid_t u@ = user to own the socket
2236 * @gid_t g@ = group to own the socket
a9279e37 2237 * @mode_t m@ = permissions to set on the socket
410c8acf 2238 *
2239 * Returns: ---
2240 *
2241 * Use: Creates the admin listening socket.
2242 */
2243
a9279e37 2244void a_init(const char *name, uid_t u, gid_t g, mode_t m)
410c8acf 2245{
2246 int fd;
2247 int n = 5;
2248 struct sockaddr_un sun;
2249 struct sigaction sa;
2250 size_t sz;
879483d7 2251 mode_t omask;
410c8acf 2252
be6a1b7a
MW
2253 /* --- Create services table --- */
2254
2255 sym_create(&a_svcs);
2256
410c8acf 2257 /* --- Set up the socket address --- */
2258
2259 sz = strlen(name) + 1;
2260 if (sz > sizeof(sun.sun_path))
2261 die(EXIT_FAILURE, "socket name `%s' too long", name);
2262 BURN(sun);
2263 sun.sun_family = AF_UNIX;
2264 memcpy(sun.sun_path, name, sz);
2265 sz += offsetof(struct sockaddr_un, sun_path);
2266
2267 /* --- Attempt to bind to the socket --- */
2268
879483d7 2269 omask = umask(0077);
410c8acf 2270again:
2271 if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2272 die(EXIT_FAILURE, "couldn't create socket: %s", strerror(errno));
2273 if (bind(fd, (struct sockaddr *)&sun, sz) < 0) {
2274 struct stat st;
2275 int e = errno;
2276 if (errno != EADDRINUSE) {
2277 die(EXIT_FAILURE, "couldn't bind to address `%s': %s",
2278 sun.sun_path, strerror(e));
2279 }
2280 if (!n)
2281 die(EXIT_FAILURE, "too many retries; giving up");
2282 n--;
2283 if (!connect(fd, (struct sockaddr *)&sun, sz)) {
2284 die(EXIT_FAILURE, "server already listening on admin socket `%s'",
2285 sun.sun_path);
2286 }
2287 if (errno != ECONNREFUSED)
2288 die(EXIT_FAILURE, "couldn't bind to address: %s", strerror(e));
2289 if (stat(sun.sun_path, &st)) {
2290 die(EXIT_FAILURE, "couldn't stat `%s': %s",
2291 sun.sun_path, strerror(errno));
2292 }
2293 if (!S_ISSOCK(st.st_mode))
2294 die(EXIT_FAILURE, "object `%s' isn't a socket", sun.sun_path);
c7053da9 2295 T( trace(T_ADMIN, "admin: stale socket found; removing it"); )
410c8acf 2296 unlink(sun.sun_path);
2297 close(fd);
2298 goto again;
2299 }
aa2405e8 2300 if (chown(sun.sun_path, u, g)) {
9e0161ce
MW
2301 die(EXIT_FAILURE, "failed to set socket owner: %s",
2302 strerror(errno));
aa2405e8 2303 }
a9279e37
MW
2304 if (chmod(sun.sun_path, m)) {
2305 die(EXIT_FAILURE, "failed to set socket permissions: %s",
2306 strerror(errno));
2307 }
879483d7 2308 umask(omask);
410c8acf 2309 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
2310 if (listen(fd, 5))
2311 die(EXIT_FAILURE, "couldn't listen on socket: %s", strerror(errno));
2312
2313 /* --- Listen to the socket --- */
2314
2315 sel_initfile(&sel, &sock, fd, SEL_READ, a_accept, 0);
2316 sel_addfile(&sock);
2317 sockname = name;
2318 bres_init(&sel);
2319 T( trace_custom(a_trace, 0);
2320 trace(T_ADMIN, "admin: enabled custom tracing"); )
2321 flags |= F_INIT;
2322
2323 /* --- Set up signal handlers --- */
2324
2325 sig_add(&s_term, SIGTERM, a_sigdie, 0);
2326 sig_add(&s_hup, SIGHUP, a_sighup, 0);
3cdc3f3a 2327 signal(SIGPIPE, SIG_IGN);
410c8acf 2328 sigaction(SIGINT, 0, &sa);
2329 if (sa.sa_handler != SIG_IGN)
2330 sig_add(&s_int, SIGINT, a_sigdie, 0);
2331}
2332
2333/*----- That's all, folks -------------------------------------------------*/