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