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