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