chiark / gitweb /
server/: Institute `address family table'; contemplate multiple sockets.
[tripe] / server / tripe.h
1 /* -*-c-*-
2  *
3  * Main header file for TrIPE
4  *
5  * (c) 2001 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Trivial IP Encryption (TrIPE).
11  *
12  * TrIPE is free software: you can redistribute it and/or modify it under
13  * the terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your
15  * option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20  * for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE.  If not, see <https://www.gnu.org/licenses/>.
24  */
25
26 #ifndef TRIPE_H
27 #define TRIPE_H
28
29 #ifdef __cplusplus
30   extern "C" {
31 #endif
32
33 /*----- Header files ------------------------------------------------------*/
34
35 #include "config.h"
36
37 #include <assert.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <limits.h>
41 #include <signal.h>
42 #include <stdarg.h>
43 #include <stddef.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <time.h>
48
49 #include <sys/types.h>
50 #include <sys/time.h>
51 #include <unistd.h>
52 #include <fcntl.h>
53 #include <sys/stat.h>
54 #include <sys/wait.h>
55
56 #include <sys/socket.h>
57 #include <sys/un.h>
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
60 #include <netdb.h>
61
62 #include <pwd.h>
63 #include <grp.h>
64
65 #include <mLib/alloc.h>
66 #include <mLib/arena.h>
67 #include <mLib/base64.h>
68 #include <mLib/bres.h>
69 #include <mLib/codec.h>
70 #include <mLib/daemonize.h>
71 #include <mLib/dstr.h>
72 #include <mLib/env.h>
73 #include <mLib/fdflags.h>
74 #include <mLib/fdpass.h>
75 #include <mLib/fwatch.h>
76 #include <mLib/hash.h>
77 #include <mLib/macros.h>
78 #include <mLib/mdup.h>
79 #include <mLib/mdwopt.h>
80 #include <mLib/quis.h>
81 #include <mLib/report.h>
82 #include <mLib/sel.h>
83 #include <mLib/selbuf.h>
84 #include <mLib/sig.h>
85 #include <mLib/str.h>
86 #include <mLib/sub.h>
87 #include <mLib/trace.h>
88 #include <mLib/tv.h>
89 #include <mLib/versioncmp.h>
90
91 #include <catacomb/buf.h>
92 #include <catacomb/ct.h>
93
94 #include <catacomb/chacha.h>
95 #include <catacomb/gcipher.h>
96 #include <catacomb/gmac.h>
97 #include <catacomb/grand.h>
98 #include <catacomb/key.h>
99 #include <catacomb/paranoia.h>
100 #include <catacomb/poly1305.h>
101 #include <catacomb/salsa20.h>
102
103 #include <catacomb/noise.h>
104 #include <catacomb/rand.h>
105
106 #include <catacomb/mp.h>
107 #include <catacomb/mpmont.h>
108 #include <catacomb/mprand.h>
109 #include <catacomb/dh.h>
110 #include <catacomb/ec.h>
111 #include <catacomb/ec-raw.h>
112 #include <catacomb/ec-keys.h>
113 #include <catacomb/x25519.h>
114 #include <catacomb/x448.h>
115
116 #include "priv.h"
117 #include "protocol.h"
118 #include "slip.h"
119 #include "util.h"
120
121 #undef sun
122
123 /*----- Magic numbers -----------------------------------------------------*/
124
125 /* --- Trace flags --- */
126
127 #define T_TUNNEL 1u
128 #define T_PEER 2u
129 #define T_PACKET 4u
130 #define T_ADMIN 8u
131 #define T_CRYPTO 16u
132 #define T_KEYSET 32u
133 #define T_KEYEXCH 64u
134 #define T_KEYMGMT 128u
135 #define T_CHAL 256u
136 /* T_PRIVSEP  in priv.h */
137
138 #define T_ALL 1023u
139
140 /* --- Units --- */
141
142 #define SEC(n) (n##u)
143 #define MIN(n) (n##u * 60u)
144 #define F_2P32 (65536.0*65536.0)
145 #define MEG(n) (n##ul * 1024ul * 1024ul)
146
147 /* --- Timing parameters --- */
148
149 #define T_EXP MIN(60)                   /* Expiry time for a key */
150 #define T_REGEN MIN(40)                 /* Regeneration time for a key */
151
152 #define T_VALID SEC(20)                 /* Challenge validity period */
153 #define T_RETRYMIN SEC(2)               /* Minimum retry interval */
154 #define T_RETRYMAX MIN(5)               /* Maximum retry interval */
155 #define T_RETRYGROW (5.0/4.0)           /* Retry interval growth factor */
156
157 #define T_WOBBLE (1.0/3.0)              /* Relative timer randomness */
158
159 /* --- Other things --- */
160
161 #define PKBUFSZ 65536
162
163 /*----- Cipher selections -------------------------------------------------*/
164
165 typedef struct keyset keyset;
166 typedef struct algswitch algswitch;
167 typedef struct kdata kdata;
168 typedef struct admin admin;
169
170 typedef struct dhgrp {
171   const struct dhops *ops;
172   size_t scsz;
173 } dhgrp;
174
175 typedef struct dhsc dhsc;
176 typedef struct dhge dhge;
177
178 enum {
179   DHFMT_STD,                /* Fixed-width format, suitable for encryption */
180   DHFMT_HASH,                /* Deterministic format, suitable for hashing */
181   DHFMT_VAR                    /* Variable-width-format, mostly a bad idea */
182 };
183
184 typedef struct bulkalgs {
185   const struct bulkops *ops;
186 } bulkalgs;
187
188 typedef struct bulkctx {
189   const struct bulkops *ops;
190 } bulkctx;
191
192 typedef struct bulkchal {
193   const struct bulkops *ops;
194   size_t tagsz;
195 } bulkchal;
196
197 struct rawkey;
198
199 typedef struct dhops {
200   const char *name;
201
202   int (*ldpriv)(key_file */*kf*/, key */*k*/, key_data */*d*/,
203                 kdata */*kd*/, dstr */*t*/, dstr */*e*/);
204         /* Load a private key from @d@, storing the data in @kd@.  The key's
205          * file and key object are in @kf@ and @k@, mostly in case its
206          * attributes are interesting; the key tag is in @t@; errors are
207          * reported by writing tokens to @e@ and returning nonzero.
208          */
209
210   int (*ldpub)(key_file */*kf*/, key */*k*/, key_data */*d*/,
211                kdata */*kd*/, dstr */*t*/, dstr */*e*/);
212         /* Load a public key from @d@, storing the data in @kd@.  The key's
213          * file and key object are in @kf@ and @k@, mostly in case its
214          * attributes are interesting; the key tag is in @t@; errors are
215          * reported by writing tokens to @e@ and returning nonzero.
216          */
217
218   const char *(*checkgrp)(const dhgrp */*g*/);
219         /* Check that the group is valid; return null on success, or an error
220          * string.
221          */
222
223   void (*grpinfo)(const dhgrp */*g*/, admin */*a*/);
224         /* Report on the group to an admin client. */
225
226   T( void (*tracegrp)(const dhgrp */*g*/); )
227         /* Trace a description of the group. */
228
229   int (*samegrpp)(const dhgrp */*g*/, const dhgrp */*gg*/);
230         /* Return nonzero if the two group objects represent the same
231          * group.
232          */
233
234   void (*freegrp)(dhgrp */*g*/);
235         /* Free a group and the resources it holds. */
236
237   dhsc *(*ldsc)(const dhgrp */*g*/, const void */*p*/, size_t /*sz*/);
238         /* Load a scalar from @p@, @sz@ and return it.  Return null on
239          * error.
240          */
241
242   int (*stsc)(const dhgrp */*g*/,
243                void */*p*/, size_t /*sz*/, const dhsc */*x*/);
244         /* Store a scalar at @p@, @sz@.  Return nonzero on error. */
245
246   dhsc *(*randsc)(const dhgrp */*g*/);
247         /* Return a random scalar. */
248
249   T( const char *(*scstr)(const dhgrp */*g*/, const dhsc */*x*/); )
250         /* Return a human-readable representation of @x@; @buf_t@ may be used
251          * to hold it.
252          */
253
254   void (*freesc)(const dhgrp */*g*/, dhsc */*x*/);
255         /* Free a scalar and the resources it holds. */
256
257   dhge *(*ldge)(const dhgrp */*g*/, buf */*b*/, int /*fmt*/);
258         /* Load a group element from @b@, encoded using format @fmt@.  Return
259          * null on error.
260          */
261
262   int (*stge)(const dhgrp */*g*/, buf */*b*/,
263               const dhge */*Y*/, int /*fmt*/);
264         /* Store a group element in @b@, encoded using format @fmt@.  Return
265          * nonzero on error.
266          */
267
268   int (*checkge)(const dhgrp */*h*/, const dhge */*Y*/);
269         /* Check a group element for validity.  Return zero if everything
270          * checks out; nonzero on failure.
271          */
272
273   int (*eq)(const dhgrp */*g*/, const dhge */*Y*/, const dhge */*Z*/);
274         /* Return nonzero if @Y@ and @Z@ are equal. */
275
276   dhge *(*mul)(const dhgrp */*g*/, const dhsc */*x*/, const dhge */*Y*/);
277         /* Multiply a group element by a scalar, resulting in a shared-secret
278          * group element.  If @y@ is null, then multiply the well-known
279          * generator.
280          */
281
282   T( const char *(*gestr)(const dhgrp */*g*/, const dhge */*Y*/); )
283         /* Return a human-readable representation of @Y@; @buf_t@ may be used
284          * to hold it.
285          */
286
287   void (*freege)(const dhgrp */*g*/, dhge */*Y*/);
288         /* Free a group element and the resources it holds. */
289
290 } dhops;
291
292 typedef struct bulkops {
293   const char *name;
294
295   bulkalgs *(*getalgs)(const algswitch */*asw*/, dstr */*e*/,
296                        key_file */*kf*/, key */*k*/);
297         /* Determine algorithms to use and return a @bulkalgs@ object
298          * representing the decision.  On error, write tokens to @e@ and
299          * return null.
300          */
301
302   T( void (*tracealgs)(const bulkalgs */*a*/); )
303         /* Write trace information about the algorithm selection. */
304
305   int (*checkalgs)(bulkalgs */*a*/, const algswitch */*asw*/, dstr */*e*/);
306         /* Check that the algorithms in @a@ and @asw@ are acceptable.  On
307          * error, write tokens to @e@ and return @-1@; otherwise return zero.
308          */
309
310   int (*samealgsp)(const bulkalgs */*a*/, const bulkalgs */*aa*/);
311         /* If @a@ and @aa@ represent the same algorithm selection, return
312          * nonzero; if not, return zero.
313          */
314
315   void (*alginfo)(const bulkalgs */*a*/, admin */*adm*/);
316         /* Report on the algorithm selection to an admin client: call
317          * @a_info@ with appropriate key-value pairs.
318          */
319
320   size_t (*overhead)(const bulkalgs */*a*/);
321         /* Return the per-packet overhead of the bulk transform, in bytes. */
322
323   size_t (*expsz)(const bulkalgs */*a*/);
324         /* Return the total size limit for the bulk transform, in bytes,
325          * after which the keys must no longer be used.
326          */
327
328   bulkctx *(*genkeys)(const bulkalgs */*a*/, const struct rawkey */*rk*/);
329         /* Generate session keys and construct and return an appropriate
330          * context for using them, by calling @ks_derive@.
331          */
332
333   bulkchal *(*genchal)(const bulkalgs */*a*/);
334         /* Construct and return a challenge issuing and verification
335          * context with a fresh random key.
336          */
337
338   void (*freealgs)(bulkalgs */*a*/);
339         /* Release an algorithm selection object.  (Associated bulk
340          * encryption contexts and challenge contexts may still exist and
341          * must remain valid.)
342          */
343
344   int (*encrypt)(bulkctx */*bc*/, unsigned /*ty*/,
345                  buf */*b*/, buf */*bb*/, uint32 /*seq*/);
346         /* Encrypt the packet in @b@, with type @ty@ (which doesn't need
347          * encoding separately) and sequence number @seq@ (which must be
348          * recoverable by @decrypt@), and write the result to @bb@.  On
349          * error, return a @KSERR_...@ code and/or break the output buffer.
350          */
351
352   int (*decrypt)(bulkctx */*bc*/, unsigned /*ty*/,
353                  buf */*b*/, buf */*bb*/, uint32 */*seq*/);
354         /* Decrypt the packet in @b@, with type @ty@, writing the result to
355          * @bb@ and storing the incoming (claimed) sequence number in @seq@.
356          * On error, return a @KSERR_...@ code.
357          */
358
359   void (*freectx)(bulkctx */*a*/);
360         /* Release a bulk encryption context and the resources it holds. */
361
362   int (*chaltag)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
363                  void */*t*/);
364         /* Calculate a tag for the challenge in @m@, @msz@, and write it to
365          * @t@.  Return @-1@ on error, zero on success.
366          */
367
368   int (*chalvrf)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
369                  const void */*t*/);
370         /* Check the tag @t@ on @m@, @msz@: return zero if the tag is OK,
371          * nonzero if it's bad.
372          */
373
374   void (*freechal)(bulkchal */*bc*/);
375         /* Release a challenge context and the resources it holds. */
376
377 } bulkops;
378
379 struct algswitch {
380   const gchash *h; size_t hashsz;       /* Hash function */
381   const gccipher *mgf;                  /* Mask-generation function */
382   bulkalgs *bulk;                       /* Bulk crypto algorithms */
383 };
384
385 struct kdata {
386   unsigned ref;                         /* Reference counter */
387   struct knode *kn;                     /* Pointer to cache entry */
388   char *tag;                            /* Full tag name of the key */
389   dhgrp *grp;                           /* The group we work in */
390   dhsc *k;                              /* The private key (or null) */
391   dhge *K;                              /* The public key */
392   time_t t_exp;                         /* Expiry time of the key */
393   algswitch algs;                       /* Collection of algorithms */
394 };
395
396 typedef struct knode {
397   sym_base _b;                          /* Symbol table intrusion */
398   unsigned f;                           /* Various flags */
399 #define KNF_BROKEN 1u                   /*   Don't use this key any more */
400   struct keyhalf *kh;                   /* Pointer to the home keyhalf */
401   kdata *kd;                            /* Pointer to the key data */
402 } knode;
403
404 #define MAXHASHSZ 64                    /* Largest possible hash size */
405
406 #define HASH_STRING(h, s) GH_HASH((h), (s), sizeof(s))
407
408 extern const dhops dhtab[];
409 extern const bulkops bulktab[];
410
411 /*----- Data structures ---------------------------------------------------*/
412
413 /* --- The address-family table --- */
414
415 #define ADDRFAM(_)                                                      \
416   _(INET)
417
418 enum {
419 #define ENUM(af) AFIX_##af,
420   ADDRFAM(ENUM)
421 #undef ENUM
422   NADDRFAM
423 };
424
425 extern const struct addrfam {
426   int af;
427   const char *name;
428 } aftab[NADDRFAM];
429
430 /* --- Socket addresses --- *
431  *
432  * A magic union of supported socket addresses.
433  */
434
435 typedef union addr {
436   struct sockaddr sa;
437   struct sockaddr_in sin;
438 } addr;
439
440 /* --- Mapping keyed on addresses --- */
441
442 typedef struct addrmap {
443   hash_table t;
444   size_t load;
445 } addrmap;
446
447 typedef struct addrmap_base {
448   hash_base b;
449   addr a;
450 } addrmap_base;
451
452 /* --- Sequence number checking --- */
453
454 typedef struct seqwin {
455   uint32 seq;                           /* First acceptable input sequence */
456   uint32 win;                           /* Window of acceptable numbers */
457 } seqwin;
458
459 #define SEQ_WINSZ 32                    /* Bits in sequence number window */
460
461 /* --- A symmetric keyset --- *
462  *
463  * A keyset contains a set of symmetric keys for encrypting and decrypting
464  * packets.  Keysets are stored in a list, sorted in reverse order of
465  * creation, so that the most recent keyset (the one most likely to be used)
466  * is first.
467  *
468  * Each keyset has a time limit and a data limit.  The keyset is destroyed
469  * when either it has existed for too long, or it has been used to encrypt
470  * too much data.  New key exchanges are triggered when keys are close to
471  * expiry.
472  */
473
474 enum { DIR_IN, DIR_OUT, NDIR };
475
476 struct keyset {
477   struct keyset *next;                  /* Next active keyset in the list */
478   unsigned ref;                         /* Reference count for keyset */
479   struct peer *p;                       /* Pointer to peer structure */
480   time_t t_exp;                         /* Expiry time for this keyset */
481   unsigned long sz_exp, sz_regen;       /* Data limits for the keyset */
482   T( unsigned seq; )                    /* Sequence number for tracing */
483   unsigned f;                           /* Various useful flags */
484   bulkctx *bulk;                        /* Bulk crypto transform */
485   uint32 oseq;                          /* Outbound sequence number */
486   seqwin iseq;                          /* Inbound sequence number */
487 };
488
489 #define KSF_LISTEN 1u                   /* Don't encrypt packets yet */
490 #define KSF_LINK 2u                     /* Key is in a linked list */
491
492 #define KSERR_REGEN -1                  /* Regenerate keys */
493 #define KSERR_NOKEYS -2                 /* No keys left */
494 #define KSERR_DECRYPT -3                /* Unable to decrypt message */
495 #define KSERR_SEQ -4                    /* Incorrect sequence number */
496 #define KSERR_MALFORMED -5              /* Input ciphertext is broken */
497
498 /* --- Key exchange --- *
499  *
500  * TrIPE uses the Wrestlers Protocol for its key exchange.  The Wrestlers
501  * Protocol has a number of desirable features (e.g., perfect forward
502  * secrecy, and zero-knowledge authentication) which make it attractive for
503  * use in TrIPE.  The Wrestlers Protocol was designed by Mark Wooding and
504  * Clive Jones.
505  */
506
507 typedef struct retry {
508   double t;                             /* Current retry time */
509 } retry;
510
511 #define KX_NCHAL 16u
512
513 typedef struct kxchal {
514   struct keyexch *kx;                   /* Pointer back to key exchange */
515   dhge *C;                              /* Responder's challenge */
516   dhge *R;                              /* My reply to the challenge */
517   keyset *ks;                           /* Pointer to temporary keyset */
518   unsigned f;                           /* Various useful flags */
519   sel_timer t;                          /* Response timer for challenge */
520   retry rs;                             /* Retry state */
521   octet hc[MAXHASHSZ];                  /* Hash of his challenge */
522   octet ck[MAXHASHSZ];                  /* His magical check value */
523   octet hswrq_in[MAXHASHSZ];            /* Inbound switch request message */
524   octet hswok_in[MAXHASHSZ];            /* Inbound switch confirmation */
525   octet hswrq_out[MAXHASHSZ];           /* Outbound switch request message */
526   octet hswok_out[MAXHASHSZ];           /* Outbound switch confirmation */
527 } kxchal;
528
529 typedef struct keyexch {
530   struct peer *p;                       /* Pointer back to the peer */
531   kdata *kpriv;                         /* Private key and related info */
532   kdata *kpub;                          /* Peer's public key */
533   keyset **ks;                          /* Peer's list of keysets */
534   unsigned f;                           /* Various useful flags */
535   unsigned s;                           /* Current state in exchange */
536   sel_timer t;                          /* Timer for next exchange */
537   retry rs;                             /* Retry state */
538   dhsc *a;                              /* My temporary secret */
539   dhge *C;                              /* My challenge */
540   dhge *RX;                             /* The expected response */
541   unsigned nr;                          /* Number of extant responses */
542   time_t t_valid;                       /* When this exchange goes bad */
543   octet hc[MAXHASHSZ];                  /* Hash of my challenge */
544   kxchal *r[KX_NCHAL];                  /* Array of challenges */
545 } keyexch;
546
547 #define KXF_TIMER 1u                    /* Waiting for a timer to go off */
548 #define KXF_DEAD 2u                     /* The key-exchanger isn't up */
549 #define KXF_PUBKEY 4u                   /* Key exchanger has a public key */
550 #define KXF_CORK 8u                     /* Don't send anything yet */
551
552 enum {
553   KXS_DEAD,                             /* Uninitialized state (magical) */
554   KXS_CHAL,                             /* Main answer-challenges state */
555   KXS_COMMIT,                           /* Committed: send switch request */
556   KXS_SWITCH                            /* Switched: send confirmation */
557 };
558
559 /* --- Tunnel structure --- *
560  *
561  * Used to maintain system-specific information about the tunnel interface.
562  */
563
564 typedef struct tunnel tunnel;
565 struct peer;
566
567 typedef struct tunnel_ops {
568   const char *name;                     /* Name of this tunnel driver */
569   unsigned flags;                       /* Various interesting flags */
570 #define TUNF_PRIVOPEN 1u                /*   Need helper to open file */
571   void (*init)(void);                   /* Initializes the system */
572   tunnel *(*create)(struct peer */*p*/, int /*fd*/, char **/*ifn*/);
573                                         /* Initializes a new tunnel */
574   void (*setifname)(tunnel */*t*/, const char */*ifn*/);
575                                         /*  Notifies ifname change */
576   void (*inject)(tunnel */*t*/, buf */*b*/); /* Sends packet through if */
577   void (*destroy)(tunnel */*t*/);       /* Destroys a tunnel */
578 } tunnel_ops;
579
580 #ifndef TUN_INTERNALS
581 struct tunnel { const tunnel_ops *ops; };
582 #endif
583
584 /* --- Peer statistics --- *
585  *
586  * Contains various interesting and not-so-interesting statistics about a
587  * peer.  This is updated by various parts of the code.  The format of the
588  * structure isn't considered private, and @p_stats@ returns a pointer to the
589  * statistics block for a given peer.
590  */
591
592 typedef struct stats {
593   unsigned long sz_in, sz_out;          /* Size of all data in and out */
594   unsigned long sz_kxin, sz_kxout;      /* Size of key exchange messages */
595   unsigned long sz_ipin, sz_ipout;      /* Size of encapsulated IP packets */
596   time_t t_start, t_last, t_kx;         /* Time peer created, last pk, kx */
597   unsigned long n_reject;               /* Number of rejected packets */
598   unsigned long n_in, n_out;            /* Number of packets in and out */
599   unsigned long n_kxin, n_kxout;        /* Number of key exchange packets */
600   unsigned long n_ipin, n_ipout;        /* Number of encrypted packets */
601 } stats;
602
603 /* --- Peer structure --- *
604  *
605  * The main structure which glues everything else together.
606  */
607
608 typedef struct peerspec {
609   char *name;                           /* Peer's name */
610   char *privtag;                        /* Private key tag */
611   char *tag;                            /* Public key tag */
612   const tunnel_ops *tops;               /* Tunnel operations */
613   unsigned long t_ka;                   /* Keep alive interval */
614   addr sa;                              /* Socket address to speak to */
615   unsigned f;                           /* Flags for the peer */
616 #define PSF_KXMASK 255u                 /*   Key-exchange flags to set */
617 #define PSF_MOBILE 256u                 /*   Address may change rapidly */
618 } peerspec;
619
620 typedef struct peer_byname {
621   sym_base _b;
622   struct peer *p;
623 } peer_byname;
624
625 typedef struct peer_byaddr {
626   addrmap_base _b;
627   struct peer *p;
628 } peer_byaddr;
629
630 typedef struct peer {
631   peer_byname *byname;                  /* Lookup-by-name block */
632   peer_byaddr *byaddr;                  /* Lookup-by-address block */
633   struct ping *pings;                   /* Pings we're waiting for */
634   peerspec spec;                        /* Specifications for this peer */
635   int afix;                             /* Index of address family */
636   tunnel *t;                            /* Tunnel for local packets */
637   char *ifname;                         /* Interface name for tunnel */
638   keyset *ks;                           /* List head for keysets */
639   buf b;                                /* Buffer for sending packets */
640   stats st;                             /* Statistics */
641   keyexch kx;                           /* Key exchange protocol block */
642   sel_timer tka;                        /* Timer for keepalives */
643 } peer;
644
645 typedef struct peer_iter { sym_iter i; } peer_iter;
646
647 typedef struct ping {
648   struct ping *next, *prev;             /* Links to next and previous */
649   peer *p;                              /* Peer so we can free it */
650   unsigned msg;                         /* Kind of response expected */
651   uint32 id;                            /* Id so we can recognize response */
652   octet magic[32];                      /* Some random data */
653   sel_timer t;                          /* Timeout for ping */
654   void (*func)(int /*rc*/, void */*arg*/); /* Function to call when done */
655   void *arg;                            /* Argument for callback */
656 } ping;
657
658 enum {
659   PING_NONOTIFY = -1,
660   PING_OK = 0,
661   PING_TIMEOUT,
662   PING_PEERDIED,
663   PING_MAX
664 };
665
666 /* --- Admin structure --- */
667
668 #define OBUFSZ 16384u
669
670 typedef struct obuf {
671   struct obuf *next;                    /* Next buffer in list */
672   char *p_in, *p_out;                   /* Pointers into the buffer */
673   char buf[OBUFSZ];                     /* The actual buffer */
674 } obuf;
675
676 typedef struct oqueue {
677   obuf *hd, *tl;                        /* Head and tail pointers */
678 } oqueue;
679
680 struct admin;
681
682 typedef struct admin_bgop {
683   struct admin_bgop *next, *prev;       /* Links to next and previous */
684   struct admin *a;                      /* Owner job */
685   char *tag;                            /* Tag string for messages */
686   void (*cancel)(struct admin_bgop *);  /* Destructor function */
687 } admin_bgop;
688
689 typedef struct admin_resop {
690   admin_bgop bg;                        /* Background operation header */
691   char *addr;                           /* Hostname to be resolved */
692   bres_client r;                        /* Background resolver task */
693   sel_timer t;                          /* Timer for resolver */
694   addr sa;                              /* Socket address */
695   size_t sasz;                          /* Socket address size */
696   void (*func)(struct admin_resop *, int); /* Handler */
697 } admin_resop;
698
699 enum { ARES_OK, ARES_FAIL };
700
701 typedef struct admin_addop {
702   admin_resop r;                        /* Name resolution header */
703   peerspec peer;                        /* Peer pending creation */
704 } admin_addop;
705
706 typedef struct admin_pingop {
707   admin_bgop bg;                        /* Background operation header */
708   ping ping;                            /* Ping pending response */
709   struct timeval pingtime;              /* Time last ping was sent */
710 } admin_pingop;
711
712 typedef struct admin_service {
713   sym_base _b;                          /* Hash table base structure */
714   char *version;                        /* The provided version */
715   struct admin *prov;                   /* Which client provides me */
716   struct admin_service *next, *prev;    /* Client's list of services */
717 } admin_service;
718
719 typedef struct admin_svcop {
720   admin_bgop bg;                        /* Background operation header */
721   struct admin *prov;                   /* Client servicing this job */
722   unsigned index;                       /* This job's index */
723   struct admin_svcop *next, *prev;      /* Links for provider's jobs */
724 } admin_svcop;
725
726 typedef struct admin_jobentry {
727   unsigned short seq;                   /* Zero if unused */
728   union {
729     admin_svcop *op;                    /* Operation, if slot in use, ... */
730     uint32 next;                        /* ... or index of next free slot */
731   } u;
732 } admin_jobentry;
733
734 typedef struct admin_jobtable {
735   uint32 n, sz;                         /* Used slots and table size */
736   admin_svcop *active;                  /* List of active jobs */
737   uint32 free;                          /* Index of first free slot */
738   admin_jobentry *v;                    /* And the big array of entries */
739 } admin_jobtable;
740
741 struct admin {
742   struct admin *next, *prev;            /* Links to next and previous */
743   unsigned f;                           /* Various useful flags */
744   unsigned ref;                         /* Reference counter */
745 #ifndef NTRACE
746   unsigned seq;                         /* Sequence number for tracing */
747 #endif
748   oqueue out;                           /* Output buffer list */
749   oqueue delay;                         /* Delayed output buffer list */
750   admin_bgop *bg;                       /* Backgrounded operations */
751   admin_service *svcs;                  /* Which services I provide */
752   admin_jobtable j;                     /* Table of outstanding jobs */
753   selbuf b;                             /* Line buffer for commands */
754   sel_file w;                           /* Selector for write buffering */
755 };
756
757 #define AF_DEAD 1u                      /* Destroy this admin block */
758 #define AF_CLOSE 2u                     /* Client closed connection */
759 #define AF_NOTE 4u                      /* Catch notifications */
760 #define AF_WARN 8u                      /* Catch warning messages */
761 #ifndef NTRACE
762 #  define AF_TRACE 16u                  /* Catch tracing */
763 #endif
764 #define AF_FOREGROUND 32u               /* Quit server when client closes */
765
766 #ifndef NTRACE
767 #  define AF_ALLMSGS (AF_NOTE | AF_TRACE | AF_WARN)
768 #else
769 #  define AF_ALLMSGS (AF_NOTE | AF_WARN)
770 #endif
771
772 /*----- Global variables --------------------------------------------------*/
773
774 extern sel_state sel;                   /* Global I/O event state */
775 extern octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
776 extern const tunnel_ops *tunnels[];     /* Table of tunnels (0-term) */
777 extern const tunnel_ops *tun_default;   /* Default tunnel to use */
778 extern sel_file udpsock[NADDRFAM];      /* The master UDP sockets */
779 extern kdata *master;                   /* Default private key */
780 extern const char *tag_priv;            /* Default private key tag */
781
782 #ifndef NTRACE
783 extern const trace_opt tr_opts[];       /* Trace options array */
784 extern unsigned tr_flags;               /* Trace options flags */
785 #endif
786
787 /*----- Other macros ------------------------------------------------------*/
788
789 #define QUICKRAND                                                       \
790   do { rand_quick(RAND_GLOBAL); noise_timer(RAND_GLOBAL); } while (0)
791
792 /*----- Key management ----------------------------------------------------*/
793
794 /* --- @km_init@ --- *
795  *
796  * Arguments:   @const char *privkr@ = private keyring file
797  *              @const char *pubkr@ = public keyring file
798  *              @const char *ptag@ = default private-key tag
799  *
800  * Returns:     ---
801  *
802  * Use:         Initializes the key-management machinery, loading the
803  *              keyrings and so on.
804  */
805
806 extern void km_init(const char */*privkr*/, const char */*pubkr*/,
807                     const char */*ptag*/);
808
809 /* --- @km_reload@ --- *
810  *
811  * Arguments:   ---
812  *
813  * Returns:     Zero if OK, nonzero to force reloading of keys.
814  *
815  * Use:         Checks the keyrings to see if they need reloading.
816  */
817
818 extern int km_reload(void);
819
820 /* --- @km_findpub@, @km_findpriv@ --- *
821  *
822  * Arguments:   @const char *tag@ = key tag to load
823  *
824  * Returns:     Pointer to the kdata object if successful, or null on error.
825  *
826  * Use:         Fetches a public or private key from the keyring.
827  */
828
829 extern kdata *km_findpub(const char */*tag*/);
830 extern kdata *km_findpriv(const char */*tag*/);
831
832 /* --- @km_samealgsp@ --- *
833  *
834  * Arguments:   @const kdata *kdx, *kdy@ = two key data objects
835  *
836  * Returns:     Nonzero if their two algorithm selections are the same.
837  *
838  * Use:         Checks sameness of algorithm selections: used to ensure that
839  *              peers are using sensible algorithms.
840  */
841
842 extern int km_samealgsp(const kdata */*kdx*/, const kdata */*kdy*/);
843
844 /* --- @km_ref@ --- *
845  *
846  * Arguments:   @kdata *kd@ = pointer to the kdata object
847  *
848  * Returns:     ---
849  *
850  * Use:         Claim a new reference to a kdata object.
851  */
852
853 extern void km_ref(kdata */*kd*/);
854
855 /* --- @km_unref@ --- *
856  *
857  * Arguments:   @kdata *kd@ = pointer to the kdata object
858  *
859  * Returns:     ---
860  *
861  * Use:         Releases a reference to a kdata object.
862  */
863
864 extern void km_unref(kdata */*kd*/);
865
866 /* --- @km_tag@ --- *
867  *
868  * Arguments:   @kdata *kd@ - pointer to the kdata object
869  *
870  * Returns:     A pointer to the short tag by which the kdata was loaded.
871  */
872
873 extern const char *km_tag(kdata */*kd*/);
874
875 /*----- Key exchange ------------------------------------------------------*/
876
877 /* --- @kx_start@ --- *
878  *
879  * Arguments:   @keyexch *kx@ = pointer to key exchange context
880  *              @int forcep@ = nonzero to ignore the quiet timer
881  *
882  * Returns:     ---
883  *
884  * Use:         Stimulates a key exchange.  If a key exchage is in progress,
885  *              a new challenge is sent (unless the quiet timer forbids
886  *              this); if no exchange is in progress, one is commenced.
887  */
888
889 extern void kx_start(keyexch */*kx*/, int /*forcep*/);
890
891 /* --- @kx_message@ --- *
892  *
893  * Arguments:   @keyexch *kx@ = pointer to key exchange context
894  *              @unsigned msg@ = the message code
895  *              @buf *b@ = pointer to buffer containing the packet
896  *
897  * Returns:     ---
898  *
899  * Use:         Reads a packet containing key exchange messages and handles
900  *              it.
901  */
902
903 extern void kx_message(keyexch */*kx*/, unsigned /*msg*/, buf */*b*/);
904
905 /* --- @kx_free@ --- *
906  *
907  * Arguments:   @keyexch *kx@ = pointer to key exchange context
908  *
909  * Returns:     ---
910  *
911  * Use:         Frees everything in a key exchange context.
912  */
913
914 extern void kx_free(keyexch */*kx*/);
915
916 /* --- @kx_newkeys@ --- *
917  *
918  * Arguments:   @keyexch *kx@ = pointer to key exchange context
919  *
920  * Returns:     ---
921  *
922  * Use:         Informs the key exchange module that its keys may have
923  *              changed.  If fetching the new keys fails, the peer will be
924  *              destroyed, we log messages and struggle along with the old
925  *              keys.
926  */
927
928 extern void kx_newkeys(keyexch */*kx*/);
929
930 /* --- @kx_init@ --- *
931  *
932  * Arguments:   @keyexch *kx@ = pointer to key exchange context
933  *              @peer *p@ = pointer to peer context
934  *              @keyset **ks@ = pointer to keyset list
935  *              @unsigned f@ = various useful flags
936  *
937  * Returns:     Zero if OK, nonzero if it failed.
938  *
939  * Use:         Initializes a key exchange module.  The module currently
940  *              contains no keys, and will attempt to initiate a key
941  *              exchange.
942  */
943
944 extern int kx_init(keyexch */*kx*/, peer */*p*/,
945                    keyset **/*ks*/, unsigned /*f*/);
946
947 /*----- Keysets and symmetric cryptography --------------------------------*/
948
949 /* --- @ks_drop@ --- *
950  *
951  * Arguments:   @keyset *ks@ = pointer to a keyset
952  *
953  * Returns:     ---
954  *
955  * Use:         Decrements a keyset's reference counter.  If the counter hits
956  *              zero, the keyset is freed.
957  */
958
959 extern void ks_drop(keyset */*ks*/);
960
961 /* --- @ks_derivekey@ --- *
962  *
963  * Arguments:   @octet *k@ = pointer to an output buffer of at least
964  *                      @MAXHASHSZ@ bytes
965  *              @size_t ksz@ = actual size wanted (for tracing)
966  *              @const struct rawkey *rk@ = a raw key, as passed into
967  *                      @genkeys@
968  *              @int dir@ = direction for the key (@DIR_IN@ or @DIR_OUT@)
969  *              @const char *what@ = label for the key (input to derivation)
970  *
971  * Returns:     ---
972  *
973  * Use:         Derives a session key, for use on incoming or outgoing data.
974  *              This function is part of a private protocol between @ks_gen@
975  *              and the bulk crypto transform @genkeys@ operation.
976  */
977
978 extern void ks_derivekey(octet */*k*/, size_t /*ksz*/,
979                          const struct rawkey */*rk*/,
980                          int /*dir*/, const char */*what*/);
981
982 /* --- @ks_gen@ --- *
983  *
984  * Arguments:   @const void *k@ = pointer to key material
985  *              @size_t x, y, z@ = offsets into key material (see below)
986  *              @peer *p@ = pointer to peer information
987  *
988  * Returns:     A pointer to the new keyset.
989  *
990  * Use:         Derives a new keyset from the given key material.  The
991  *              offsets @x@, @y@ and @z@ separate the key material into three
992  *              parts.  Between the @k@ and @k + x@ is `my' contribution to
993  *              the key material; between @k + x@ and @k + y@ is `your'
994  *              contribution; and between @k + y@ and @k + z@ is a shared
995  *              value we made together.  These are used to construct two
996  *              collections of symmetric keys: one for outgoing messages, the
997  *              other for incoming messages.
998  *
999  *              The new key is marked so that it won't be selected for output
1000  *              by @ksl_encrypt@.  You can still encrypt data with it by
1001  *              calling @ks_encrypt@ directly.
1002  */
1003
1004 extern keyset *ks_gen(const void */*k*/,
1005                       size_t /*x*/, size_t /*y*/, size_t /*z*/,
1006                       peer */*p*/);
1007
1008 /* --- @ks_activate@ --- *
1009  *
1010  * Arguments:   @keyset *ks@ = pointer to a keyset
1011  *
1012  * Returns:     ---
1013  *
1014  * Use:         Activates a keyset, so that it can be used for encrypting
1015  *              outgoing messages.
1016  */
1017
1018 extern void ks_activate(keyset */*ks*/);
1019
1020 /* --- @ks_encrypt@ --- *
1021  *
1022  * Arguments:   @keyset *ks@ = pointer to a keyset
1023  *              @unsigned ty@ = message type
1024  *              @buf *b@ = pointer to input buffer
1025  *              @buf *bb@ = pointer to output buffer
1026  *
1027  * Returns:     Zero if successful; @KSERR_REGEN@ if we should negotiate a
1028  *              new key; @KSERR_NOKEYS@ if the key is not usable.  Also
1029  *              returns zero if there was insufficient buffer (but the output
1030  *              buffer is broken in this case).
1031  *
1032  * Use:         Encrypts a block of data using the key.  Note that the `key
1033  *              ought to be replaced' notification is only ever given once
1034  *              for each key.  Also note that this call forces a keyset to be
1035  *              used even if it's marked as not for data output.
1036  *
1037  *              The encryption transform is permitted to corrupt @buf_u@ for
1038  *              its own purposes.  Neither the source nor destination should
1039  *              be within @buf_u@; and callers mustn't expect anything stored
1040  *              in @buf_u@ to still
1041  */
1042
1043 extern int ks_encrypt(keyset */*ks*/, unsigned /*ty*/,
1044                       buf */*b*/, buf */*bb*/);
1045
1046 /* --- @ks_decrypt@ --- *
1047  *
1048  * Arguments:   @keyset *ks@ = pointer to a keyset
1049  *              @unsigned ty@ = expected type code
1050  *              @buf *b@ = pointer to an input buffer
1051  *              @buf *bb@ = pointer to an output buffer
1052  *
1053  * Returns:     Zero on success; @KSERR_DECRYPT@ on failure.  Also returns
1054  *              zero if there was insufficient buffer (but the output buffer
1055  *              is broken in this case).
1056  *
1057  * Use:         Attempts to decrypt a message using a given key.  Note that
1058  *              requesting decryption with a key directly won't clear a
1059  *              marking that it's not for encryption.
1060  *
1061  *              The decryption transform is permitted to corrupt @buf_u@ for
1062  *              its own purposes.  Neither the source nor destination should
1063  *              be within @buf_u@; and callers mustn't expect anything stored
1064  *              in @buf_u@ to still
1065  */
1066
1067 extern int ks_decrypt(keyset */*ks*/, unsigned /*ty*/,
1068                       buf */*b*/, buf */*bb*/);
1069
1070 /* --- @ksl_free@ --- *
1071  *
1072  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
1073  *
1074  * Returns:     ---
1075  *
1076  * Use:         Frees (releases references to) all of the keys in a keyset.
1077  */
1078
1079 extern void ksl_free(keyset **/*ksroot*/);
1080
1081 /* --- @ksl_link@ --- *
1082  *
1083  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
1084  *              @keyset *ks@ = pointer to a keyset
1085  *
1086  * Returns:     ---
1087  *
1088  * Use:         Links a keyset into a list.  A keyset can only be on one list
1089  *              at a time.  Bad things happen otherwise.
1090  */
1091
1092 extern void ksl_link(keyset **/*ksroot*/, keyset */*ks*/);
1093
1094 /* --- @ksl_prune@ --- *
1095  *
1096  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
1097  *
1098  * Returns:     ---
1099  *
1100  * Use:         Prunes the keyset list by removing keys which mustn't be used
1101  *              any more.
1102  */
1103
1104 extern void ksl_prune(keyset **/*ksroot*/);
1105
1106 /* --- @ksl_encrypt@ --- *
1107  *
1108  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
1109  *              @unsigned ty@ = message type
1110  *              @buf *b@ = pointer to input buffer
1111  *              @buf *bb@ = pointer to output buffer
1112  *
1113  * Returns:     Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
1114  *              new key; @KSERR_NOKEYS@ if there are no suitable keys
1115  *              available.  Also returns zero if there was insufficient
1116  *              buffer space (but the output buffer is broken in this case).
1117  *
1118  * Use:         Encrypts a packet.
1119  */
1120
1121 extern int ksl_encrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1122                        buf */*b*/, buf */*bb*/);
1123
1124 /* --- @ksl_decrypt@ --- *
1125  *
1126  * Arguments:   @keyset **ksroot@ = pointer to keyset list head
1127  *              @unsigned ty@ = expected type code
1128  *              @buf *b@ = pointer to input buffer
1129  *              @buf *bb@ = pointer to output buffer
1130  *
1131  * Returns:     Zero on success; @KSERR_DECRYPT@ on failure.  Also returns
1132  *              zero if there was insufficient buffer (but the output buffer
1133  *              is broken in this case).
1134  *
1135  * Use:         Decrypts a packet.
1136  */
1137
1138 extern int ksl_decrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1139                        buf */*b*/, buf */*bb*/);
1140
1141 /*----- Challenges --------------------------------------------------------*/
1142
1143 /* --- @c_new@ --- *
1144  *
1145  * Arguments:   @buf *b@ = where to put the challenge
1146  *
1147  * Returns:     Zero if OK, nonzero on error.
1148  *
1149  * Use:         Issues a new challenge.
1150  */
1151
1152 extern int c_new(buf */*b*/);
1153
1154 /* --- @c_check@ --- *
1155  *
1156  * Arguments:   @buf *b@ = where to find the challenge
1157  *
1158  * Returns:     Zero if OK, nonzero if it didn't work.
1159  *
1160  * Use:         Checks a challenge.  On failure, the buffer is broken.
1161  */
1162
1163 extern int c_check(buf */*b*/);
1164
1165 /*----- Administration interface ------------------------------------------*/
1166
1167 #define A_END ((char *)0)
1168
1169 /* --- @a_vformat@ --- *
1170  *
1171  * Arguments:   @dstr *d@ = where to leave the formatted message
1172  *              @const char *fmt@ = pointer to format string
1173  *              @va_list *ap@ = arguments in list
1174  *
1175  * Returns:     ---
1176  *
1177  * Use:         Main message token formatting driver.  The arguments are
1178  *              interleaved formatting tokens and their parameters, finally
1179  *              terminated by an entry @A_END@.
1180  *
1181  *              Tokens recognized:
1182  *
1183  *                * "*..." ... -- pretokenized @dstr_putf@-like string
1184  *
1185  *                * "?ADDR" SOCKADDR -- a socket address, to be converted
1186  *
1187  *                * "?B64" BUFFER SIZE -- binary data to be base64-encoded
1188  *
1189  *                * "?TOKENS" VECTOR -- null-terminated vector of tokens
1190  *
1191  *                * "?PEER" PEER -- peer's name
1192  *
1193  *                * "?ERRNO" ERRNO -- system error code
1194  *
1195  *                * "[!]..." ... -- @dstr_putf@-like string as single token
1196  */
1197
1198 extern void a_vformat(dstr */*d*/, const char */*fmt*/, va_list */*ap*/);
1199
1200 /* --- @a_format@ --- *
1201  *
1202  * Arguments:   @dstr *d@ = where to leave the formatted message
1203  *              @const char *fmt@ = pointer to format string
1204  *
1205  * Returns:     ---
1206  *
1207  * Use:         Writes a tokenized message into a string, for later
1208  *              presentation.
1209  */
1210
1211 extern void EXECL_LIKE(0) a_format(dstr */*d*/, const char */*fmt*/, ...);
1212
1213 /* --- @a_info@ --- *
1214  *
1215  * Arguments:   @admin *a@ = connection
1216  *              @const char *fmt@ = format string
1217  *              @...@ = other arguments
1218  *
1219  * Returns:     ---
1220  *
1221  * Use:         Report information to an admin client.
1222  */
1223
1224 extern void EXECL_LIKE(0) a_info(admin */*a*/, const char */*fmt*/, ...);
1225
1226 /* --- @a_warn@ --- *
1227  *
1228  * Arguments:   @const char *fmt@ = pointer to format string
1229  *              @...@ = other arguments
1230  *
1231  * Returns:     ---
1232  *
1233  * Use:         Informs all admin connections of a warning.
1234  */
1235
1236 extern void EXECL_LIKE(0) a_warn(const char */*fmt*/, ...);
1237
1238 /* --- @a_notify@ --- *
1239  *
1240  * Arguments:   @const char *fmt@ = pointer to format string
1241  *              @...@ = other arguments
1242  *
1243  * Returns:     ---
1244  *
1245  * Use:         Sends a notification to interested admin connections.
1246  */
1247
1248 extern void EXECL_LIKE(0) a_notify(const char */*fmt*/, ...);
1249
1250 /* --- @a_create@ --- *
1251  *
1252  * Arguments:   @int fd_in, fd_out@ = file descriptors to use
1253  *              @unsigned f@ = initial flags to set
1254  *
1255  * Returns:     ---
1256  *
1257  * Use:         Creates a new admin connection.
1258  */
1259
1260 extern void a_create(int /*fd_in*/, int /*fd_out*/, unsigned /*f*/);
1261
1262 /* --- @a_quit@ --- *
1263  *
1264  * Arguments:   ---
1265  *
1266  * Returns:     ---
1267  *
1268  * Use:         Shuts things down nicely.
1269  */
1270
1271 extern void a_quit(void);
1272
1273 /* --- @a_preselect@ --- *
1274  *
1275  * Arguments:   ---
1276  *
1277  * Returns:     ---
1278  *
1279  * Use:         Informs the admin module that we're about to select again,
1280  *              and that it should do cleanup things it has delayed until a
1281  *              `safe' time.
1282  */
1283
1284 extern void a_preselect(void);
1285
1286 /* --- @a_daemon@ --- *
1287  *
1288  * Arguments:   ---
1289  *
1290  * Returns:     ---
1291  *
1292  * Use:         Informs the admin module that it's a daemon.
1293  */
1294
1295 extern void a_daemon(void);
1296
1297 /* --- @a_init@ --- *
1298  *
1299  * Arguments:   @const char *sock@ = socket name to create
1300  *              @uid_t u@ = user to own the socket
1301  *              @gid_t g@ = group to own the socket
1302  *              @mode_t m@ = permissions to set on the socket
1303  *
1304  * Returns:     ---
1305  *
1306  * Use:         Creates the admin listening socket.
1307  */
1308
1309 extern void a_init(const char */*sock*/,
1310                    uid_t /*u*/, gid_t /*g*/, mode_t /*m*/);
1311
1312 /*----- Mapping with addresses as keys ------------------------------------*/
1313
1314 /* --- @am_create@ --- *
1315  *
1316  * Arguments:   @addrmap *m@ = pointer to map
1317  *
1318  * Returns:     ---
1319  *
1320  * Use:         Create an address map, properly set up.
1321  */
1322
1323 extern void am_create(addrmap */*m*/);
1324
1325 /* --- @am_destroy@ --- *
1326  *
1327  * Arguments:   @addrmap *m@ = pointer to map
1328  *
1329  * Returns:     ---
1330  *
1331  * Use:         Destroy an address map, throwing away all the entries.
1332  */
1333
1334 extern void am_destroy(addrmap */*m*/);
1335
1336 /* --- @am_find@ --- *
1337  *
1338  * Arguments:   @addrmap *m@ = pointer to map
1339  *              @const addr *a@ = address to look up
1340  *              @size_t sz@ = size of block to allocate
1341  *              @unsigned *f@ = where to store flags
1342  *
1343  * Returns:     Pointer to found item, or null.
1344  *
1345  * Use:         Finds a record with the given IP address, set @*f@ nonzero
1346  *              and returns it.  If @sz@ is zero, and no match was found,
1347  *              return null; otherwise allocate a new block of @sz@ bytes,
1348  *              clear @*f@ to zero and return the block pointer.
1349  */
1350
1351 extern void *am_find(addrmap */*m*/, const addr */*a*/,
1352                      size_t /*sz*/, unsigned */*f*/);
1353
1354 /* --- @am_remove@ --- *
1355  *
1356  * Arguments:   @addrmap *m@ = pointer to map
1357  *              @void *i@ = pointer to the item
1358  *
1359  * Returns:     ---
1360  *
1361  * Use:         Removes an item from the map.
1362  */
1363
1364 extern void am_remove(addrmap */*m*/, void */*i*/);
1365
1366 /*----- Privilege separation ----------------------------------------------*/
1367
1368 /* --- @ps_trace@ --- *
1369  *
1370  * Arguments:   @unsigned mask@ = trace mask to check
1371  *              @const char *fmt@ = message format
1372  *              @...@ = values for placeholders
1373  *
1374  * Returns:     ---
1375  *
1376  * Use:         Writes a trace message.
1377  */
1378
1379 T( extern void PRINTF_LIKE(2, 3)
1380      ps_trace(unsigned /*mask*/, const char */*fmt*/, ...); )
1381
1382 /* --- @ps_warn@ --- *
1383  *
1384  * Arguments:   @const char *fmt@ = message format
1385  *              @...@ = values for placeholders
1386  *
1387  * Returns:     ---
1388  *
1389  * Use:         Writes a warning message.
1390  */
1391
1392 extern void PRINTF_LIKE(1, 2) ps_warn(const char */*fmt*/, ...);
1393
1394 /* --- @ps_tunfd@ --- *
1395  *
1396  * Arguments:   @const tunnel_ops *tops@ = pointer to tunnel operations
1397  *              @char **ifn@ = where to put the interface name
1398  *
1399  * Returns:     The file descriptor, or @-1@ on error.
1400  *
1401  * Use:         Fetches a file descriptor for a tunnel driver.
1402  */
1403
1404 extern int ps_tunfd(const tunnel_ops */*tops*/, char **/*ifn*/);
1405
1406 /* --- @ps_split@ --- *
1407  *
1408  * Arguments:   @int detachp@ = whether to detach the child from its terminal
1409  *
1410  * Returns:     ---
1411  *
1412  * Use:         Separates off the privileged tunnel-opening service from the
1413  *              rest of the server.
1414  */
1415
1416 extern void ps_split(int /*detachp*/);
1417
1418 /* --- @ps_quit@ --- *
1419  *
1420  * Arguments:   ---
1421  *
1422  * Returns:     ---
1423  *
1424  * Use:         Detaches from the helper process.
1425  */
1426
1427 extern void ps_quit(void);
1428
1429 /*----- Peer management ---------------------------------------------------*/
1430
1431 /* --- @p_updateaddr@ --- *
1432  *
1433  * Arguments:   @peer *p@ = pointer to peer block
1434  *              @const addr *a@ = address to associate with this peer
1435  *
1436  * Returns:     Zero if the address was changed; @+1@ if it was already
1437  *              right.
1438  *
1439  * Use:         Updates our idea of @p@'s address.
1440  */
1441
1442 extern int p_updateaddr(peer */*p*/, const addr */*a*/);
1443
1444 /* --- @p_txstart@ --- *
1445  *
1446  * Arguments:   @peer *p@ = pointer to peer block
1447  *              @unsigned msg@ = message type code
1448  *
1449  * Returns:     A pointer to a buffer to write to.
1450  *
1451  * Use:         Starts sending to a peer.  Only one send can happen at a
1452  *              time.
1453  */
1454
1455 extern buf *p_txstart(peer */*p*/, unsigned /*msg*/);
1456
1457 /* --- @p_txend@ --- *
1458  *
1459  * Arguments:   @peer *p@ = pointer to peer block
1460  *
1461  * Returns:     ---
1462  *
1463  * Use:         Sends a packet to the peer.
1464  */
1465
1466 extern void p_txend(peer */*p*/);
1467
1468 /* --- @p_pingsend@ --- *
1469  *
1470  * Arguments:   @peer *p@ = destination peer
1471  *              @ping *pg@ = structure to fill in
1472  *              @unsigned type@ = message type
1473  *              @unsigned long timeout@ = how long to wait before giving up
1474  *              @void (*func)(int, void *)@ = callback function
1475  *              @void *arg@ = argument for callback
1476  *
1477  * Returns:     Zero if successful, nonzero if it failed.
1478  *
1479  * Use:         Sends a ping to a peer.  Call @func@ with a nonzero argument
1480  *              if we get an answer within the timeout, or zero if no answer.
1481  */
1482
1483 extern int p_pingsend(peer */*p*/, ping */*pg*/, unsigned /*type*/,
1484                       unsigned long /*timeout*/,
1485                       void (*/*func*/)(int, void *), void */*arg*/);
1486
1487 /* --- @p_pingdone@ --- *
1488  *
1489  * Arguments:   @ping *p@ = ping structure
1490  *              @int rc@ = return code to pass on
1491  *
1492  * Returns:     ---
1493  *
1494  * Use:         Disposes of a ping structure, maybe sending a notification.
1495  */
1496
1497 extern void p_pingdone(ping */*p*/, int /*rc*/);
1498
1499 /* --- @p_greet@ --- *
1500  *
1501  * Arguments:   @peer *p@ = peer to send to
1502  *              @const void *c@ = pointer to challenge
1503  *              @size_t sz@ = size of challenge
1504  *
1505  * Returns:     ---
1506  *
1507  * Use:         Sends a greeting packet.
1508  */
1509
1510 extern void p_greet(peer */*p*/, const void */*c*/, size_t /*sz*/);
1511
1512 /* --- @p_tun@ --- *
1513  *
1514  * Arguments:   @peer *p@ = pointer to peer block
1515  *              @buf *b@ = buffer containing incoming packet
1516  *
1517  * Returns:     ---
1518  *
1519  * Use:         Handles a packet which needs to be sent to a peer.
1520  */
1521
1522 extern void p_tun(peer */*p*/, buf */*b*/);
1523
1524 /* --- @p_keyreload@ --- *
1525  *
1526  * Arguments:   ---
1527  *
1528  * Returns:     ---
1529  *
1530  * Use:         Forces a check of the daemon's keyring files.
1531  */
1532
1533 extern void p_keyreload(void);
1534
1535 /* --- @p_interval@ --- *
1536  *
1537  * Arguments:   ---
1538  *
1539  * Returns:     ---
1540  *
1541  * Use:         Called periodically to do tidying.
1542  */
1543
1544 extern void p_interval(void);
1545
1546 /* --- @p_stats@ --- *
1547  *
1548  * Arguments:   @peer *p@ = pointer to a peer block
1549  *
1550  * Returns:     A pointer to the peer's statistics.
1551  */
1552
1553 extern stats *p_stats(peer */*p*/);
1554
1555 /* --- @p_ifname@ --- *
1556  *
1557  * Arguments:   @peer *p@ = pointer to a peer block
1558  *
1559  * Returns:     A pointer to the peer's interface name.
1560  */
1561
1562 extern const char *p_ifname(peer */*p*/);
1563
1564 /* --- @p_setifname@ --- *
1565  *
1566  * Arguments:   @peer *p@ = pointer to a peer block
1567  *              @const char *name@ = pointer to the new name
1568  *
1569  * Returns:     ---
1570  *
1571  * Use:         Changes the name held for a peer's interface.
1572  */
1573
1574 extern void p_setifname(peer */*p*/, const char */*name*/);
1575
1576 /* --- @p_addr@ --- *
1577  *
1578  * Arguments:   @peer *p@ = pointer to a peer block
1579  *
1580  * Returns:     A pointer to the peer's address.
1581  */
1582
1583 extern const addr *p_addr(peer */*p*/);
1584
1585 /* --- @p_init@ --- *
1586  *
1587  * Arguments:   @struct in_addr addr@ = address to bind to
1588  *              @unsigned port@ = port number to listen to
1589  *
1590  * Returns:     ---
1591  *
1592  * Use:         Initializes the peer system; creates the socket.
1593  */
1594
1595 extern void p_init(struct in_addr /*addr*/, unsigned /*port*/);
1596
1597 /* --- @p_port@ --- *
1598  *
1599  * Arguments:   @int i@ = address family index to retrieve
1600  *
1601  * Returns:     Port number used for socket.
1602  */
1603
1604 extern unsigned p_port(int /*i*/);
1605
1606 /* --- @p_create@ --- *
1607  *
1608  * Arguments:   @peerspec *spec@ = information about this peer
1609  *
1610  * Returns:     Pointer to the peer block, or null if it failed.
1611  *
1612  * Use:         Creates a new named peer block.  No peer is actually attached
1613  *              by this point.
1614  */
1615
1616 extern peer *p_create(peerspec */*spec*/);
1617
1618 /* --- @p_name@ --- *
1619  *
1620  * Arguments:   @peer *p@ = pointer to a peer block
1621  *
1622  * Returns:     A pointer to the peer's name.
1623  *
1624  * Use:         Equivalent to @p_spec(p)->name@.
1625  */
1626
1627 extern const char *p_name(peer */*p*/);
1628
1629 /* --- @p_tag@ --- *
1630  *
1631  * Arguments:   @peer *p@ = pointer to a peer block
1632  *
1633  * Returns:     A pointer to the peer's public key tag.
1634  */
1635
1636 extern const char *p_tag(peer */*p*/);
1637
1638 /* --- @p_privtag@ --- *
1639  *
1640  * Arguments:   @peer *p@ = pointer to a peer block
1641  *
1642  * Returns:     A pointer to the peer's private key tag.
1643  */
1644
1645 extern const char *p_privtag(peer */*p*/);
1646
1647 /* --- @p_spec@ --- *
1648  *
1649  * Arguments:   @peer *p@ = pointer to a peer block
1650  *
1651  * Returns:     Pointer to the peer's specification
1652  */
1653
1654 extern const peerspec *p_spec(peer */*p*/);
1655
1656 /* --- @p_findbyaddr@ --- *
1657  *
1658  * Arguments:   @const addr *a@ = address to look up
1659  *
1660  * Returns:     Pointer to the peer block, or null if not found.
1661  *
1662  * Use:         Finds a peer by address.
1663  */
1664
1665 extern peer *p_findbyaddr(const addr */*a*/);
1666
1667 /* --- @p_find@ --- *
1668  *
1669  * Arguments:   @const char *name@ = name to look up
1670  *
1671  * Returns:     Pointer to the peer block, or null if not found.
1672  *
1673  * Use:         Finds a peer by name.
1674  */
1675
1676 extern peer *p_find(const char */*name*/);
1677
1678 /* --- @p_destroy@ --- *
1679  *
1680  * Arguments:   @peer *p@ = pointer to a peer
1681  *
1682  * Returns:     ---
1683  *
1684  * Use:         Destroys a peer.
1685  */
1686
1687 extern void p_destroy(peer */*p*/);
1688
1689 /* --- @FOREACH_PEER@ --- *
1690  *
1691  * Arguments:   @p@ = name to bind to each peer
1692  *              @stuff@ = thing to do for each item
1693  *
1694  * Use:         Does something for each current peer.
1695  */
1696
1697 #define FOREACH_PEER(p, stuff) do {                                     \
1698   peer_iter i_;                                                         \
1699   peer *p;                                                              \
1700   for (p_mkiter(&i_); (p = p_next(&i_)) != 0; ) stuff                   \
1701 } while (0)
1702
1703 /* --- @p_mkiter@ --- *
1704  *
1705  * Arguments:   @peer_iter *i@ = pointer to an iterator
1706  *
1707  * Returns:     ---
1708  *
1709  * Use:         Initializes the iterator.
1710  */
1711
1712 extern void p_mkiter(peer_iter */*i*/);
1713
1714 /* --- @p_next@ --- *
1715  *
1716  * Arguments:   @peer_iter *i@ = pointer to an iterator
1717  *
1718  * Returns:     Next peer, or null if at the end.
1719  *
1720  * Use:         Returns the next peer.
1721  */
1722
1723 extern peer *p_next(peer_iter */*i*/);
1724
1725 /*----- Tunnel drivers ----------------------------------------------------*/
1726
1727 #ifdef TUN_LINUX
1728   extern const tunnel_ops tun_linux;
1729 #endif
1730
1731 #ifdef TUN_UNET
1732   extern const tunnel_ops tun_unet;
1733 #endif
1734
1735 #ifdef TUN_BSD
1736   extern const tunnel_ops tun_bsd;
1737 #endif
1738
1739 extern const tunnel_ops tun_slip;
1740
1741 /*----- Other handy utilities ---------------------------------------------*/
1742
1743 /* --- @timestr@ --- *
1744  *
1745  * Arguments:   @time_t t@ = a time to convert
1746  *
1747  * Returns:     A pointer to a textual representation of the time.
1748  *
1749  * Use:         Converts a time to a textual representation.  Corrupts
1750  *              @buf_u@.
1751  */
1752
1753 extern const char *timestr(time_t /*t*/);
1754
1755 /* --- @mystrieq@ --- *
1756  *
1757  * Arguments:   @const char *x, *y@ = two strings
1758  *
1759  * Returns:     True if @x@ and @y are equal, up to case.
1760  */
1761
1762 extern int mystrieq(const char */*x*/, const char */*y*/);
1763
1764 /* --- @afix@ --- *
1765  *
1766  * Arguments:   @int af@ = an address family code
1767  *
1768  * Returns:     The index of the address family's record in @aftab@, or @-1@.
1769  */
1770
1771 extern int afix(int af);
1772
1773 /* --- @addrsz@ --- *
1774  *
1775  * Arguments:   @const addr *a@ = a network address
1776  *
1777  * Returns:     The size of the address, for passing into the sockets API.
1778  */
1779
1780 extern socklen_t addrsz(const addr */*a*/);
1781
1782 /* --- @seq_reset@ --- *
1783  *
1784  * Arguments:   @seqwin *s@ = sequence-checking window
1785  *
1786  * Returns:     ---
1787  *
1788  * Use:         Resets a sequence number window.
1789  */
1790
1791 extern void seq_reset(seqwin */*s*/);
1792
1793 /* --- @seq_check@ --- *
1794  *
1795  * Arguments:   @seqwin *s@ = sequence-checking window
1796  *              @uint32 q@ = sequence number to check
1797  *              @const char *service@ = service to report message from
1798  *
1799  * Returns:     A @SEQ_@ code.
1800  *
1801  * Use:         Checks a sequence number against the window, updating things
1802  *              as necessary.
1803  */
1804
1805 extern int seq_check(seqwin */*s*/, uint32 /*q*/, const char */*service*/);
1806
1807 /*----- That's all, folks -------------------------------------------------*/
1808
1809 #ifdef __cplusplus
1810   }
1811 #endif
1812
1813 #endif