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