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