3 * Main header file for TrIPE
5 * (c) 2001 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Trivial IP Encryption (TrIPE).
12 * TrIPE is free software: you can redistribute it and/or modify it under
13 * the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your
15 * option) any later version.
17 * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE. If not, see <https://www.gnu.org/licenses/>.
33 /*----- Header files ------------------------------------------------------*/
49 #include <sys/types.h>
56 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
66 # define ADNS_FEATURE_MANYAF
70 #include <mLib/alloc.h>
71 #include <mLib/arena.h>
72 #include <mLib/base64.h>
74 # include <mLib/bres.h>
76 #include <mLib/codec.h>
77 #include <mLib/daemonize.h>
78 #include <mLib/dstr.h>
80 #include <mLib/fdflags.h>
81 #include <mLib/fdpass.h>
82 #include <mLib/fwatch.h>
83 #include <mLib/hash.h>
84 #include <mLib/macros.h>
85 #include <mLib/mdup.h>
86 #include <mLib/mdwopt.h>
87 #include <mLib/quis.h>
88 #include <mLib/report.h>
90 #include <mLib/selbuf.h>
94 #include <mLib/trace.h>
96 #include <mLib/versioncmp.h>
98 #include <catacomb/buf.h>
99 #include <catacomb/ct.h>
101 #include <catacomb/chacha.h>
102 #include <catacomb/gaead.h>
103 #include <catacomb/gcipher.h>
104 #include <catacomb/gmac.h>
105 #include <catacomb/grand.h>
106 #include <catacomb/latinpoly.h>
107 #include <catacomb/key.h>
108 #include <catacomb/paranoia.h>
109 #include <catacomb/poly1305.h>
110 #include <catacomb/salsa20.h>
112 #include <catacomb/noise.h>
113 #include <catacomb/rand.h>
115 #include <catacomb/mp.h>
116 #include <catacomb/mpmont.h>
117 #include <catacomb/mprand.h>
118 #include <catacomb/dh.h>
119 #include <catacomb/ec.h>
120 #include <catacomb/ec-raw.h>
121 #include <catacomb/ec-keys.h>
122 #include <catacomb/x25519.h>
123 #include <catacomb/x448.h>
126 #include "protocol.h"
132 /*----- Magic numbers -----------------------------------------------------*/
134 /* --- Trace flags --- */
142 #define T_KEYEXCH 64u
143 #define T_KEYMGMT 128u
145 /* T_PRIVSEP in priv.h */
151 #define SEC(n) (n##u)
152 #define MIN(n) (n##u * 60u)
153 #define F_2P32 (65536.0*65536.0)
154 #define MEG(n) (n##ul * 1024ul * 1024ul)
156 /* --- Timing parameters --- */
158 #define T_EXP MIN(60) /* Expiry time for a key */
159 #define T_REGEN MIN(40) /* Regeneration time for a key */
161 #define T_VALID SEC(20) /* Challenge validity period */
162 #define T_RETRYMIN SEC(2) /* Minimum retry interval */
163 #define T_RETRYMAX MIN(5) /* Maximum retry interval */
164 #define T_RETRYGROW (5.0/4.0) /* Retry interval growth factor */
166 #define T_WOBBLE (1.0/3.0) /* Relative timer randomness */
168 #define T_WGT 5 /* Age for who-goes-there */
170 /* --- Other things --- */
172 #define PKBUFSZ 65536
174 /*----- Cipher selections -------------------------------------------------*/
176 typedef struct keyset keyset;
177 typedef struct algswitch algswitch;
178 typedef struct kdata kdata;
179 typedef struct admin admin;
181 typedef struct dhgrp {
182 const struct dhops *ops;
186 typedef struct dhsc dhsc;
187 typedef struct dhge dhge;
190 DHFMT_STD, /* Fixed-width format, suitable for encryption */
191 DHFMT_HASH, /* Deterministic format, suitable for hashing */
192 DHFMT_VAR /* Variable-width-format, mostly a bad idea */
195 typedef struct deriveargs {
196 const char *what; /* Operation name (hashed) */
197 unsigned f; /* Flags */
198 #define DF_IN 1u /* Make incoming key */
199 #define DF_OUT 2u /* Make outgoing key */
200 const gchash *hc; /* Hash class */
201 const octet *k; /* Pointer to contributions */
202 size_t x, y, z; /* Markers in contributions */
205 typedef struct bulkalgs {
206 const struct bulkops *ops;
209 typedef struct bulkctx {
210 const struct bulkops *ops;
213 typedef struct bulkchal {
214 const struct bulkops *ops;
218 typedef struct dhops {
221 int (*ldpriv)(key_file */*kf*/, key */*k*/, key_data */*d*/,
222 kdata */*kd*/, dstr */*t*/, dstr */*e*/);
223 /* Load a private key from @d@, storing the data in @kd@. The key's
224 * file and key object are in @kf@ and @k@, mostly in case its
225 * attributes are interesting; the key tag is in @t@; errors are
226 * reported by writing tokens to @e@ and returning nonzero.
229 int (*ldpub)(key_file */*kf*/, key */*k*/, key_data */*d*/,
230 kdata */*kd*/, dstr */*t*/, dstr */*e*/);
231 /* Load a public key from @d@, storing the data in @kd@. The key's
232 * file and key object are in @kf@ and @k@, mostly in case its
233 * attributes are interesting; the key tag is in @t@; errors are
234 * reported by writing tokens to @e@ and returning nonzero.
237 const char *(*checkgrp)(const dhgrp */*g*/);
238 /* Check that the group is valid; return null on success, or an error
242 void (*grpinfo)(const dhgrp */*g*/, admin */*a*/);
243 /* Report on the group to an admin client. */
245 T( void (*tracegrp)(const dhgrp */*g*/); )
246 /* Trace a description of the group. */
248 int (*samegrpp)(const dhgrp */*g*/, const dhgrp */*gg*/);
249 /* Return nonzero if the two group objects represent the same
253 void (*freegrp)(dhgrp */*g*/);
254 /* Free a group and the resources it holds. */
256 dhsc *(*ldsc)(const dhgrp */*g*/, const void */*p*/, size_t /*sz*/);
257 /* Load a scalar from @p@, @sz@ and return it. Return null on
261 int (*stsc)(const dhgrp */*g*/,
262 void */*p*/, size_t /*sz*/, const dhsc */*x*/);
263 /* Store a scalar at @p@, @sz@. Return nonzero on error. */
265 dhsc *(*randsc)(const dhgrp */*g*/);
266 /* Return a random scalar. */
268 T( const char *(*scstr)(const dhgrp */*g*/, const dhsc */*x*/); )
269 /* Return a human-readable representation of @x@; @buf_t@ may be used
273 void (*freesc)(const dhgrp */*g*/, dhsc */*x*/);
274 /* Free a scalar and the resources it holds. */
276 dhge *(*ldge)(const dhgrp */*g*/, buf */*b*/, int /*fmt*/);
277 /* Load a group element from @b@, encoded using format @fmt@. Return
281 int (*stge)(const dhgrp */*g*/, buf */*b*/,
282 const dhge */*Y*/, int /*fmt*/);
283 /* Store a group element in @b@, encoded using format @fmt@. Return
287 int (*checkge)(const dhgrp */*h*/, const dhge */*Y*/);
288 /* Check a group element for validity. Return zero if everything
289 * checks out; nonzero on failure.
292 int (*eq)(const dhgrp */*g*/, const dhge */*Y*/, const dhge */*Z*/);
293 /* Return nonzero if @Y@ and @Z@ are equal. */
295 dhge *(*mul)(const dhgrp */*g*/, const dhsc */*x*/, const dhge */*Y*/);
296 /* Multiply a group element by a scalar, resulting in a shared-secret
297 * group element. If @y@ is null, then multiply the well-known
301 T( const char *(*gestr)(const dhgrp */*g*/, const dhge */*Y*/); )
302 /* Return a human-readable representation of @Y@; @buf_t@ may be used
306 void (*freege)(const dhgrp */*g*/, dhge */*Y*/);
307 /* Free a group element and the resources it holds. */
311 typedef struct bulkops {
314 bulkalgs *(*getalgs)(const algswitch */*asw*/, dstr */*e*/,
315 key_file */*kf*/, key */*k*/);
316 /* Determine algorithms to use and return a @bulkalgs@ object
317 * representing the decision. On error, write tokens to @e@ and
321 T( void (*tracealgs)(const bulkalgs */*a*/); )
322 /* Write trace information about the algorithm selection. */
324 int (*checkalgs)(bulkalgs */*a*/, const algswitch */*asw*/, dstr */*e*/);
325 /* Check that the algorithms in @a@ and @asw@ are acceptable. On
326 * error, write tokens to @e@ and return @-1@; otherwise return zero.
329 int (*samealgsp)(const bulkalgs */*a*/, const bulkalgs */*aa*/);
330 /* If @a@ and @aa@ represent the same algorithm selection, return
331 * nonzero; if not, return zero.
334 void (*alginfo)(const bulkalgs */*a*/, admin */*adm*/);
335 /* Report on the algorithm selection to an admin client: call
336 * @a_info@ with appropriate key-value pairs.
339 size_t (*overhead)(const bulkalgs */*a*/);
340 /* Return the per-packet overhead of the bulk transform, in bytes. */
342 size_t (*expsz)(const bulkalgs */*a*/);
343 /* Return the total size limit for the bulk transform, in bytes,
344 * after which the keys must no longer be used.
347 bulkctx *(*genkeys)(const bulkalgs */*a*/, const deriveargs */*a*/);
348 /* Generate session keys and construct and return an appropriate
349 * context for using them. The offsets @a->x@, @a->y@ and @a->z@
350 * separate the key material into three parts. Between @a->k@ and
351 * @a->k + a->x@ is `my' contribution to the key material; between
352 * @a->k + a->x@ and @a->k + a->y@ is `your' contribution; and
353 * between @a->k + a->y@ and @a->k + a->z@ is a shared value we made
354 * together. These are used to construct (up to) two collections of
355 * symmetric keys: one for outgoing messages, the other for incoming
356 * messages. If @a->x == 0@ (or @a->y == a->x@) then my (or your)
357 * contribution is omitted.
360 bulkchal *(*genchal)(const bulkalgs */*a*/);
361 /* Construct and return a challenge issuing and verification
362 * context with a fresh random key.
365 void (*freealgs)(bulkalgs */*a*/);
366 /* Release an algorithm selection object. (Associated bulk
367 * encryption contexts and challenge contexts may still exist and
368 * must remain valid.)
371 int (*encrypt)(bulkctx */*bc*/, unsigned /*ty*/,
372 buf */*b*/, buf */*bb*/, uint32 /*seq*/);
373 /* Encrypt the packet in @b@, with type @ty@ (which doesn't need
374 * encoding separately) and sequence number @seq@ (which must be
375 * recoverable by @decrypt@), and write the result to @bb@. On
376 * error, return a @KSERR_...@ code and/or break the output buffer.
379 int (*decrypt)(bulkctx */*bc*/, unsigned /*ty*/,
380 buf */*b*/, buf */*bb*/, uint32 */*seq*/);
381 /* Decrypt the packet in @b@, with type @ty@, writing the result to
382 * @bb@ and storing the incoming (claimed) sequence number in @seq@.
383 * On error, return a @KSERR_...@ code.
386 void (*freectx)(bulkctx */*a*/);
387 /* Release a bulk encryption context and the resources it holds. */
389 int (*chaltag)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
390 uint32 /*seq*/, void */*t*/);
391 /* Calculate a tag for the challenge in @m@, @msz@, with the sequence
392 * number @seq@, and write it to @t@. Return @-1@ on error, zero on
396 int (*chalvrf)(bulkchal */*bc*/, const void */*m*/, size_t /*msz*/,
397 uint32 /*seq*/, const void */*t*/);
398 /* Check the tag @t@ on @m@, @msz@ and @seq@: return zero if the tag
399 * is OK, nonzero if it's bad.
402 void (*freechal)(bulkchal */*bc*/);
403 /* Release a challenge context and the resources it holds. */
408 const gchash *h; size_t hashsz; /* Hash function */
409 const gccipher *mgf; /* Mask-generation function */
410 bulkalgs *bulk; /* Bulk crypto algorithms */
414 unsigned ref; /* Reference counter */
415 struct knode *kn; /* Pointer to cache entry */
416 uint32 id; /* The underlying key's id */
417 char *tag; /* Full tag name of the key */
418 dhgrp *grp; /* The group we work in */
419 dhsc *k; /* The private key (or null) */
420 dhge *K; /* The public key */
421 time_t t_exp; /* Expiry time of the key */
422 algswitch algs; /* Collection of algorithms */
425 typedef struct knode {
426 sym_base _b; /* Symbol table intrusion */
427 unsigned f; /* Various flags */
428 #define KNF_BROKEN 1u /* Don't use this key any more */
429 struct keyhalf *kh; /* Pointer to the home keyhalf */
430 kdata *kd; /* Pointer to the key data */
433 #define MAXHASHSZ 64 /* Largest possible hash size */
435 #define HASH_STRING(h, s) GH_HASH((h), (s), sizeof(s))
437 extern const dhops dhtab[];
438 extern const bulkops bulktab[];
440 /*----- Data structures ---------------------------------------------------*/
442 /* --- The address-family table --- */
449 #define ENUM(af, qf) AFIX_##af,
455 extern const struct addrfam {
463 /* --- Socket addresses --- *
465 * A magic union of supported socket addresses.
470 struct sockaddr_in sin;
471 struct sockaddr_in6 sin6;
474 /* --- Mapping keyed on addresses --- */
476 typedef struct addrmap {
481 typedef struct addrmap_base {
486 /* --- Sequence number checking --- */
488 typedef struct seqwin {
489 uint32 seq; /* First acceptable input sequence */
490 uint32 win; /* Window of acceptable numbers */
493 #define SEQ_WINSZ 32 /* Bits in sequence number window */
495 /* --- A symmetric keyset --- *
497 * A keyset contains a set of symmetric keys for encrypting and decrypting
498 * packets. Keysets are stored in a list, sorted in reverse order of
499 * creation, so that the most recent keyset (the one most likely to be used)
502 * Each keyset has a time limit and a data limit. The keyset is destroyed
503 * when either it has existed for too long, or it has been used to encrypt
504 * too much data. New key exchanges are triggered when keys are close to
508 enum { DIR_IN, DIR_OUT, NDIR };
511 struct keyset *next; /* Next active keyset in the list */
512 unsigned ref; /* Reference count for keyset */
513 struct peer *p; /* Pointer to peer structure */
514 time_t t_exp; /* Expiry time for this keyset */
515 unsigned long sz_exp, sz_regen; /* Data limits for the keyset */
516 T( unsigned seq; ) /* Sequence number for tracing */
517 unsigned f; /* Various useful flags */
518 bulkctx *bulk; /* Bulk crypto transform */
519 uint32 oseq; /* Outbound sequence number */
520 seqwin iseq; /* Inbound sequence number */
523 #define KSF_LISTEN 1u /* Don't encrypt packets yet */
524 #define KSF_LINK 2u /* Key is in a linked list */
526 #define KSERR_REGEN -1 /* Regenerate keys */
527 #define KSERR_NOKEYS -2 /* No keys left */
528 #define KSERR_DECRYPT -3 /* Unable to decrypt message */
529 #define KSERR_SEQ -4 /* Incorrect sequence number */
530 #define KSERR_MALFORMED -5 /* Input ciphertext is broken */
532 /* --- Key exchange --- *
534 * TrIPE uses the Wrestlers Protocol for its key exchange. The Wrestlers
535 * Protocol has a number of desirable features (e.g., perfect forward
536 * secrecy, and zero-knowledge authentication) which make it attractive for
537 * use in TrIPE. The Wrestlers Protocol was designed by Mark Wooding and
541 typedef struct retry {
542 double t; /* Current retry time */
547 typedef struct kxchal {
548 struct keyexch *kx; /* Pointer back to key exchange */
549 dhge *C; /* Responder's challenge */
550 dhge *R; /* My reply to the challenge */
551 keyset *ks; /* Pointer to temporary keyset */
552 unsigned f; /* Various useful flags */
553 sel_timer t; /* Response timer for challenge */
554 retry rs; /* Retry state */
555 octet hc[MAXHASHSZ]; /* Hash of his challenge */
556 octet ck[MAXHASHSZ]; /* His magical check value */
557 octet hswrq_in[MAXHASHSZ]; /* Inbound switch request message */
558 octet hswok_in[MAXHASHSZ]; /* Inbound switch confirmation */
559 octet hswrq_out[MAXHASHSZ]; /* Outbound switch request message */
560 octet hswok_out[MAXHASHSZ]; /* Outbound switch confirmation */
563 typedef struct keyexch {
564 struct peer *p; /* Pointer back to the peer */
565 kdata *kpriv; /* Private key and related info */
566 kdata *kpub; /* Peer's public key */
567 keyset **ks; /* Peer's list of keysets */
568 unsigned f; /* Various useful flags */
569 unsigned s; /* Current state in exchange */
570 sel_timer t; /* Timer for next exchange */
571 retry rs; /* Retry state */
572 dhsc *a; /* My temporary secret */
573 dhge *C; /* My challenge */
574 dhge *RX; /* The expected response */
575 unsigned nr; /* Number of extant responses */
576 time_t t_valid; /* When this exchange goes bad */
577 octet hc[MAXHASHSZ]; /* Hash of my challenge */
578 kxchal *r[KX_NCHAL]; /* Array of challenges */
581 #define KXF_TIMER 1u /* Waiting for a timer to go off */
582 #define KXF_DEAD 2u /* The key-exchanger isn't up */
583 #define KXF_PUBKEY 4u /* Key exchanger has a public key */
584 #define KXF_CORK 8u /* Don't send anything yet */
587 KXS_DEAD, /* Uninitialized state (magical) */
588 KXS_CHAL, /* Main answer-challenges state */
589 KXS_COMMIT, /* Committed: send switch request */
590 KXS_SWITCH /* Switched: send confirmation */
593 /* --- Tunnel structure --- *
595 * Used to maintain system-specific information about the tunnel interface.
598 typedef struct tunnel tunnel;
601 typedef struct tunnel_ops {
602 const char *name; /* Name of this tunnel driver */
603 unsigned flags; /* Various interesting flags */
604 #define TUNF_PRIVOPEN 1u /* Need helper to open file */
605 int (*init)(void); /* Initializes the system */
606 tunnel *(*create)(struct peer */*p*/, int /*fd*/, char **/*ifn*/);
607 /* Initializes a new tunnel */
608 void (*setifname)(tunnel */*t*/, const char */*ifn*/);
609 /* Notifies ifname change */
610 void (*inject)(tunnel */*t*/, buf */*b*/); /* Sends packet through if */
611 void (*destroy)(tunnel */*t*/); /* Destroys a tunnel */
614 #ifndef TUN_INTERNALS
615 struct tunnel { const tunnel_ops *ops; };
618 typedef struct tun_iter {
619 const struct tunnel_node *next;
622 /* --- Peer statistics --- *
624 * Contains various interesting and not-so-interesting statistics about a
625 * peer. This is updated by various parts of the code. The format of the
626 * structure isn't considered private, and @p_stats@ returns a pointer to the
627 * statistics block for a given peer.
630 typedef struct stats {
631 unsigned long sz_in, sz_out; /* Size of all data in and out */
632 unsigned long sz_kxin, sz_kxout; /* Size of key exchange messages */
633 unsigned long sz_ipin, sz_ipout; /* Size of encapsulated IP packets */
634 time_t t_start, t_last, t_kx; /* Time peer created, last pk, kx */
635 unsigned long n_reject; /* Number of rejected packets */
636 unsigned long n_in, n_out; /* Number of packets in and out */
637 unsigned long n_kxin, n_kxout; /* Number of key exchange packets */
638 unsigned long n_ipin, n_ipout; /* Number of encrypted packets */
641 /* --- Peer structure --- *
643 * The main structure which glues everything else together.
646 typedef struct peerspec {
647 char *name; /* Peer's name */
648 char *privtag; /* Private key tag */
649 char *tag; /* Public key tag */
650 char *knock; /* Knock string, or null */
651 const tunnel_ops *tops; /* Tunnel operations */
652 unsigned long t_ka; /* Keep alive interval */
653 addr sa; /* Socket address to speak to */
654 unsigned f; /* Flags for the peer */
655 #define PSF_KXMASK 255u /* Key-exchange flags to set */
656 #define PSF_MOBILE 256u /* Address may change rapidly */
657 #define PSF_EPHEM 512u /* Association is ephemeral */
660 typedef struct peer_byname {
665 typedef struct peer_byaddr {
670 typedef struct peer {
671 peer_byname *byname; /* Lookup-by-name block */
672 peer_byaddr *byaddr; /* Lookup-by-address block */
673 struct ping *pings; /* Pings we're waiting for */
674 peerspec spec; /* Specifications for this peer */
675 int afix; /* Index of address family */
676 tunnel *t; /* Tunnel for local packets */
677 char *ifname; /* Interface name for tunnel */
678 keyset *ks; /* List head for keysets */
679 buf b; /* Buffer for sending packets */
680 stats st; /* Statistics */
681 keyexch kx; /* Key exchange protocol block */
682 sel_timer tka; /* Timer for keepalives */
685 octet msg[WGTLEN]; /* Message prefix */
686 unsigned sz; /* Length of prefix */
687 time_t when; /* Time it was transmitted */
688 } wgt[NWGT]; /* Recently sent messages */
689 unsigned wgtix; /* Next index to transmit */
692 typedef struct peer_iter { sym_iter i; } peer_iter;
694 typedef struct udpsocket {
695 sel_file sf; /* Selector for the socket */
696 unsigned port; /* Chosen port number */
699 typedef struct ping {
700 struct ping *next, *prev; /* Links to next and previous */
701 peer *p; /* Peer so we can free it */
702 unsigned msg; /* Kind of response expected */
703 uint32 id; /* Id so we can recognize response */
704 octet magic[32]; /* Some random data */
705 sel_timer t; /* Timeout for ping */
706 void (*func)(int /*rc*/, void */*arg*/); /* Function to call when done */
707 void *arg; /* Argument for callback */
718 /* --- Admin structure --- */
720 #define OBUFSZ 16384u
722 typedef struct obuf {
723 struct obuf *next; /* Next buffer in list */
724 char *p_in, *p_out; /* Pointers into the buffer */
725 char buf[OBUFSZ]; /* The actual buffer */
728 typedef struct oqueue {
729 obuf *hd, *tl; /* Head and tail pointers */
734 typedef struct admin_bgop {
735 struct admin_bgop *next, *prev; /* Links to next and previous */
736 struct admin *a; /* Owner job */
737 char *tag; /* Tag string for messages */
738 void (*cancel)(struct admin_bgop *); /* Destructor function */
741 typedef struct admin_resop {
742 admin_bgop bg; /* Background operation header */
743 char *addr; /* Hostname to be resolved */
747 bres_client r; /* Background resolver task */
749 sel_timer t; /* Timer for resolver */
750 addr sa; /* Socket address */
751 unsigned port; /* Port number chosen */
752 size_t sasz; /* Socket address size */
753 void (*func)(struct admin_resop *, int); /* Handler */
756 enum { ARES_OK, ARES_FAIL };
758 typedef struct admin_addop {
759 admin_resop r; /* Name resolution header */
760 peerspec peer; /* Peer pending creation */
763 typedef struct admin_pingop {
764 admin_bgop bg; /* Background operation header */
765 ping ping; /* Ping pending response */
766 struct timeval pingtime; /* Time last ping was sent */
769 typedef struct admin_service {
770 sym_base _b; /* Hash table base structure */
771 char *version; /* The provided version */
772 struct admin *prov; /* Which client provides me */
773 struct admin_service *next, *prev; /* Client's list of services */
776 typedef struct admin_svcop {
777 admin_bgop bg; /* Background operation header */
778 struct admin *prov; /* Client servicing this job */
779 unsigned index; /* This job's index */
780 struct admin_svcop *next, *prev; /* Links for provider's jobs */
783 typedef struct admin_jobentry {
784 unsigned short seq; /* Zero if unused */
786 admin_svcop *op; /* Operation, if slot in use, ... */
787 uint32 next; /* ... or index of next free slot */
791 typedef struct admin_jobtable {
792 uint32 n, sz; /* Used slots and table size */
793 admin_svcop *active; /* List of active jobs */
794 uint32 free; /* Index of first free slot */
795 admin_jobentry *v; /* And the big array of entries */
799 struct admin *next, *prev; /* Links to next and previous */
800 unsigned f; /* Various useful flags */
801 unsigned ref; /* Reference counter */
803 unsigned seq; /* Sequence number for tracing */
805 oqueue out; /* Output buffer list */
806 oqueue delay; /* Delayed output buffer list */
807 admin_bgop *bg; /* Backgrounded operations */
808 admin_service *svcs; /* Which services I provide */
809 admin_jobtable j; /* Table of outstanding jobs */
810 selbuf b; /* Line buffer for commands */
811 sel_file w; /* Selector for write buffering */
814 #define AF_DEAD 1u /* Destroy this admin block */
815 #define AF_CLOSE 2u /* Client closed connection */
816 #define AF_NOTE 4u /* Catch notifications */
817 #define AF_WARN 8u /* Catch warning messages */
819 # define AF_TRACE 16u /* Catch tracing */
821 #define AF_FOREGROUND 32u /* Quit server when client closes */
824 # define AF_ALLMSGS (AF_NOTE | AF_TRACE | AF_WARN)
826 # define AF_ALLMSGS (AF_NOTE | AF_WARN)
829 /*----- Global variables --------------------------------------------------*/
831 extern sel_state sel; /* Global I/O event state */
832 extern octet buf_i[PKBUFSZ], buf_o[PKBUFSZ], buf_t[PKBUFSZ], buf_u[PKBUFSZ];
833 extern udpsocket udpsock[NADDRFAM]; /* The master UDP sockets */
834 extern kdata *master; /* Default private key */
835 extern char *tag_priv; /* Default private key tag */
838 extern const trace_opt tr_opts[]; /* Trace options array */
839 extern unsigned tr_flags; /* Trace options flags */
842 /*----- Other macros ------------------------------------------------------*/
845 do { rand_quick(RAND_GLOBAL); noise_timer(RAND_GLOBAL); } while (0)
847 /*----- Key management ----------------------------------------------------*/
849 /* --- @km_init@ --- *
851 * Arguments: @const char *privkr@ = private keyring file
852 * @const char *pubkr@ = public keyring file
853 * @const char *ptag@ = default private-key tag
855 * Returns: Zero on success, @-1@ on failure.
857 * Use: Initializes the key-management machinery, loading the
858 * keyrings and so on.
861 extern int km_init(const char */*privkr*/, const char */*pubkr*/,
862 const char */*ptag*/);
864 /* --- @km_reload@ --- *
868 * Returns: Zero if OK, nonzero to force reloading of keys.
870 * Use: Checks the keyrings to see if they need reloading.
873 extern int km_reload(void);
875 /* --- @km_clear@ --- *
881 * Use: Forget the currently loaded keyrings. The @master@ key will
882 * be cleared, but other keys already loaded will continue to
883 * exist until their reference count drops to zero. Call
884 * @km_init@ to make everything work again.
887 extern void km_clear(void);
889 /* --- @km_findpub@, @km_findpriv@ --- *
891 * Arguments: @const char *tag@ = key tag to load
893 * Returns: Pointer to the kdata object if successful, or null on error.
895 * Use: Fetches a public or private key from the keyring.
898 extern kdata *km_findpub(const char */*tag*/);
899 extern kdata *km_findpriv(const char */*tag*/);
901 /* --- @km_findpubbyid@, @km_findprivbyid@ --- *
903 * Arguments: @uint32 id@ = key id to load
905 * Returns: Pointer to the kdata object if successful, or null on error.
907 * Use: Fetches a public or private key from the keyring given its
911 extern kdata *km_findpubbyid(uint32 /*id*/);
912 extern kdata *km_findprivbyid(uint32 /*id*/);
914 /* --- @km_samealgsp@ --- *
916 * Arguments: @const kdata *kdx, *kdy@ = two key data objects
918 * Returns: Nonzero if their two algorithm selections are the same.
920 * Use: Checks sameness of algorithm selections: used to ensure that
921 * peers are using sensible algorithms.
924 extern int km_samealgsp(const kdata */*kdx*/, const kdata */*kdy*/);
926 /* --- @km_ref@ --- *
928 * Arguments: @kdata *kd@ = pointer to the kdata object
932 * Use: Claim a new reference to a kdata object.
935 extern void km_ref(kdata */*kd*/);
937 /* --- @km_unref@ --- *
939 * Arguments: @kdata *kd@ = pointer to the kdata object
943 * Use: Releases a reference to a kdata object.
946 extern void km_unref(kdata */*kd*/);
948 /* --- @km_tag@ --- *
950 * Arguments: @kdata *kd@ - pointer to the kdata object
952 * Returns: A pointer to the short tag by which the kdata was loaded.
955 extern const char *km_tag(kdata */*kd*/);
957 /*----- Key exchange ------------------------------------------------------*/
959 /* --- @kx_start@ --- *
961 * Arguments: @keyexch *kx@ = pointer to key exchange context
962 * @int forcep@ = nonzero to ignore the quiet timer
966 * Use: Stimulates a key exchange. If a key exchage is in progress,
967 * a new challenge is sent (unless the quiet timer forbids
968 * this); if no exchange is in progress, one is commenced.
971 extern void kx_start(keyexch */*kx*/, int /*forcep*/);
973 /* --- @kx_message@ --- *
975 * Arguments: @keyexch *kx@ = pointer to key exchange context
976 * @const addr *a@ = sender's IP address and port
977 * @unsigned msg@ = the message code
978 * @buf *b@ = pointer to buffer containing the packet
980 * Returns: Nonzero if the sender's address was unknown.
982 * Use: Reads a packet containing key exchange messages and handles
986 extern int kx_message(keyexch */*kx*/, const addr */*a*/,
987 unsigned /*msg*/, buf */*b*/);
989 /* --- @kx_free@ --- *
991 * Arguments: @keyexch *kx@ = pointer to key exchange context
995 * Use: Frees everything in a key exchange context.
998 extern void kx_free(keyexch */*kx*/);
1000 /* --- @kx_newkeys@ --- *
1002 * Arguments: @keyexch *kx@ = pointer to key exchange context
1006 * Use: Informs the key exchange module that its keys may have
1007 * changed. If fetching the new keys fails, the peer will be
1008 * destroyed, we log messages and struggle along with the old
1012 extern void kx_newkeys(keyexch */*kx*/);
1014 /* --- @kx_setup@ --- *
1016 * Arguments: @keyexch *kx@ = pointer to key exchange context
1017 * @peer *p@ = pointer to peer context
1018 * @keyset **ks@ = pointer to keyset list
1019 * @unsigned f@ = various useful flags
1021 * Returns: Zero if OK, nonzero if it failed.
1023 * Use: Initializes a key exchange module. The module currently
1024 * contains no keys, and will attempt to initiate a key
1028 extern int kx_setup(keyexch */*kx*/, peer */*p*/,
1029 keyset **/*ks*/, unsigned /*f*/);
1031 /* --- @kx_init@ --- *
1037 * Use: Initializes the key-exchange logic.
1040 extern void kx_init(void);
1042 /*----- Keysets and symmetric cryptography --------------------------------*/
1044 /* --- @ks_drop@ --- *
1046 * Arguments: @keyset *ks@ = pointer to a keyset
1050 * Use: Decrements a keyset's reference counter. If the counter hits
1051 * zero, the keyset is freed.
1054 extern void ks_drop(keyset */*ks*/);
1056 /* --- @ks_gen@ --- *
1058 * Arguments: @deriveargs *a@ = key derivation parameters (modified)
1059 * @peer *p@ = pointer to peer information
1061 * Returns: A pointer to the new keyset.
1063 * Use: Derives a new keyset from the given key material. This will
1064 * set the @what@, @f@, and @hc@ members in @*a@; other members
1065 * must be filled in by the caller.
1067 * The new key is marked so that it won't be selected for output
1068 * by @ksl_encrypt@. You can still encrypt data with it by
1069 * calling @ks_encrypt@ directly.
1072 extern keyset *ks_gen(deriveargs */*a*/, peer */*p*/);
1074 /* --- @ks_activate@ --- *
1076 * Arguments: @keyset *ks@ = pointer to a keyset
1080 * Use: Activates a keyset, so that it can be used for encrypting
1081 * outgoing messages.
1084 extern void ks_activate(keyset */*ks*/);
1086 /* --- @ks_encrypt@ --- *
1088 * Arguments: @keyset *ks@ = pointer to a keyset
1089 * @unsigned ty@ = message type
1090 * @buf *b@ = pointer to input buffer
1091 * @buf *bb@ = pointer to output buffer
1093 * Returns: Zero if successful; @KSERR_REGEN@ if we should negotiate a
1094 * new key; @KSERR_NOKEYS@ if the key is not usable. Also
1095 * returns zero if there was insufficient buffer (but the output
1096 * buffer is broken in this case).
1098 * Use: Encrypts a block of data using the key. Note that the `key
1099 * ought to be replaced' notification is only ever given once
1100 * for each key. Also note that this call forces a keyset to be
1101 * used even if it's marked as not for data output.
1103 * The encryption transform is permitted to corrupt @buf_u@ for
1104 * its own purposes. Neither the source nor destination should
1105 * be within @buf_u@; and callers mustn't expect anything stored
1106 * in @buf_u@ to still
1109 extern int ks_encrypt(keyset */*ks*/, unsigned /*ty*/,
1110 buf */*b*/, buf */*bb*/);
1112 /* --- @ks_decrypt@ --- *
1114 * Arguments: @keyset *ks@ = pointer to a keyset
1115 * @unsigned ty@ = expected type code
1116 * @buf *b@ = pointer to an input buffer
1117 * @buf *bb@ = pointer to an output buffer
1119 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1120 * zero if there was insufficient buffer (but the output buffer
1121 * is broken in this case).
1123 * Use: Attempts to decrypt a message using a given key. Note that
1124 * requesting decryption with a key directly won't clear a
1125 * marking that it's not for encryption.
1127 * The decryption transform is permitted to corrupt @buf_u@ for
1128 * its own purposes. Neither the source nor destination should
1129 * be within @buf_u@; and callers mustn't expect anything stored
1130 * in @buf_u@ to still
1133 extern int ks_decrypt(keyset */*ks*/, unsigned /*ty*/,
1134 buf */*b*/, buf */*bb*/);
1136 /* --- @ksl_free@ --- *
1138 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1142 * Use: Frees (releases references to) all of the keys in a keyset.
1145 extern void ksl_free(keyset **/*ksroot*/);
1147 /* --- @ksl_link@ --- *
1149 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1150 * @keyset *ks@ = pointer to a keyset
1154 * Use: Links a keyset into a list. A keyset can only be on one list
1155 * at a time. Bad things happen otherwise.
1158 extern void ksl_link(keyset **/*ksroot*/, keyset */*ks*/);
1160 /* --- @ksl_prune@ --- *
1162 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1166 * Use: Prunes the keyset list by removing keys which mustn't be used
1170 extern void ksl_prune(keyset **/*ksroot*/);
1172 /* --- @ksl_encrypt@ --- *
1174 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1175 * @unsigned ty@ = message type
1176 * @buf *b@ = pointer to input buffer
1177 * @buf *bb@ = pointer to output buffer
1179 * Returns: Zero if successful; @KSERR_REGEN@ if it's time to negotiate a
1180 * new key; @KSERR_NOKEYS@ if there are no suitable keys
1181 * available. Also returns zero if there was insufficient
1182 * buffer space (but the output buffer is broken in this case).
1184 * Use: Encrypts a packet.
1187 extern int ksl_encrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1188 buf */*b*/, buf */*bb*/);
1190 /* --- @ksl_decrypt@ --- *
1192 * Arguments: @keyset **ksroot@ = pointer to keyset list head
1193 * @unsigned ty@ = expected type code
1194 * @buf *b@ = pointer to input buffer
1195 * @buf *bb@ = pointer to output buffer
1197 * Returns: Zero on success; @KSERR_DECRYPT@ on failure. Also returns
1198 * zero if there was insufficient buffer (but the output buffer
1199 * is broken in this case).
1201 * Use: Decrypts a packet.
1204 extern int ksl_decrypt(keyset **/*ksroot*/, unsigned /*ty*/,
1205 buf */*b*/, buf */*bb*/);
1207 /*----- Challenges --------------------------------------------------------*/
1209 /* --- @c_new@ --- *
1211 * Arguments: @const void *m@ = pointer to associated message, or null
1212 * @size_t msz@ = length of associated message
1213 * @buf *b@ = where to put the challenge
1215 * Returns: Zero if OK, nonzero on error.
1217 * Use: Issues a new challenge.
1220 extern int c_new(const void */*m*/, size_t /*msz*/, buf */*b*/);
1222 /* --- @c_check@ --- *
1224 * Arguments: @const void *m@ = pointer to associated message, or null
1225 * @size_t msz@ = length of associated message
1226 * @buf *b@ = where to find the challenge
1228 * Returns: Zero if OK, nonzero if it didn't work.
1230 * Use: Checks a challenge. On failure, the buffer is broken.
1233 extern int c_check(const void */*m*/, size_t /*msz*/, buf */*b*/);
1235 /*----- Administration interface ------------------------------------------*/
1237 #define A_END ((char *)0)
1239 /* --- @a_vformat@ --- *
1241 * Arguments: @dstr *d@ = where to leave the formatted message
1242 * @const char *fmt@ = pointer to format string
1243 * @va_list *ap@ = arguments in list
1247 * Use: Main message token formatting driver. The arguments are
1248 * interleaved formatting tokens and their parameters, finally
1249 * terminated by an entry @A_END@.
1251 * Tokens recognized:
1253 * * "*..." ... -- pretokenized @dstr_putf@-like string
1255 * * "?ADDR" SOCKADDR -- a socket address, to be converted
1257 * * "?B64" BUFFER SIZE -- binary data to be base64-encoded
1259 * * "?TOKENS" VECTOR -- null-terminated vector of tokens
1261 * * "?PEER" PEER -- peer's name
1263 * * "?ERR" CODE -- system error code
1265 * * "?ERRNO" -- system error code from @errno@
1267 * * "[!]..." ... -- @dstr_putf@-like string as single token
1270 extern void a_vformat(dstr */*d*/, const char */*fmt*/, va_list */*ap*/);
1272 /* --- @a_format@ --- *
1274 * Arguments: @dstr *d@ = where to leave the formatted message
1275 * @const char *fmt@ = pointer to format string
1279 * Use: Writes a tokenized message into a string, for later
1283 extern void EXECL_LIKE(0) a_format(dstr */*d*/, const char */*fmt*/, ...);
1285 /* --- @a_info@ --- *
1287 * Arguments: @admin *a@ = connection
1288 * @const char *fmt@ = format string
1289 * @...@ = other arguments
1293 * Use: Report information to an admin client.
1296 extern void EXECL_LIKE(0) a_info(admin */*a*/, const char */*fmt*/, ...);
1298 /* --- @a_warn@ --- *
1300 * Arguments: @const char *fmt@ = pointer to format string
1301 * @...@ = other arguments
1305 * Use: Informs all admin connections of a warning.
1308 extern void EXECL_LIKE(0) a_warn(const char */*fmt*/, ...);
1310 /* --- @a_notify@ --- *
1312 * Arguments: @const char *fmt@ = pointer to format string
1313 * @...@ = other arguments
1317 * Use: Sends a notification to interested admin connections.
1320 extern void EXECL_LIKE(0) a_notify(const char */*fmt*/, ...);
1322 /* --- @a_create@ --- *
1324 * Arguments: @int fd_in, fd_out@ = file descriptors to use
1325 * @unsigned f@ = initial flags to set
1329 * Use: Creates a new admin connection. It's safe to call this
1330 * before @a_init@ -- and, indeed, this makes sense if you also
1331 * call @a_switcherr@ to report initialization errors through
1332 * the administration machinery.
1335 extern void a_create(int /*fd_in*/, int /*fd_out*/, unsigned /*f*/);
1337 /* --- @a_preselect@ --- *
1343 * Use: Informs the admin module that we're about to select again,
1344 * and that it should do cleanup things it has delayed until a
1348 extern void a_preselect(void);
1350 /* --- @a_daemon@ --- *
1356 * Use: Informs the admin module that it's a daemon.
1359 extern void a_daemon(void);
1361 /* --- @a_listen@ --- *
1363 * Arguments: @const char *name@ = socket name to create
1364 * @uid_t u@ = user to own the socket
1365 * @gid_t g@ = group to own the socket
1366 * @mode_t m@ = permissions to set on the socket
1368 * Returns: Zero on success, @-1@ on failure.
1370 * Use: Creates the admin listening socket.
1373 extern int a_listen(const char */*sock*/,
1374 uid_t /*u*/, gid_t /*g*/, mode_t /*m*/);
1376 /* --- @a_unlisten@ --- *
1382 * Use: Stops listening to the administration socket and removes it.
1385 extern void a_unlisten(void);
1387 /* --- @a_switcherr@ --- *
1393 * Use: Arrange to report warnings, trace messages, etc. to
1394 * administration clients rather than the standard-error stream.
1396 * Obviously this makes no sense unless there is at least one
1397 * client established. Calling @a_listen@ won't help with this,
1398 * because the earliest a new client can connect is during the
1399 * first select-loop iteration, which is too late: some initial
1400 * client must have been added manually using @a_create@.
1403 extern void a_switcherr(void);
1405 /* --- @a_signals@ --- *
1411 * Use: Establishes handlers for the obvious signals.
1414 extern void a_signals(void);
1416 /* --- @a_init@ --- *
1418 * Arguments: @const char *sock@ = socket name to create
1419 * @uid_t u@ = user to own the socket
1420 * @gid_t g@ = group to own the socket
1421 * @mode_t m@ = permissions to set on the socket
1423 * Returns: Zero on success, @-1@ on failure.
1425 * Use: Creates the admin listening socket.
1428 extern int a_init(void);
1430 /*----- Mapping with addresses as keys ------------------------------------*/
1432 /* --- @am_create@ --- *
1434 * Arguments: @addrmap *m@ = pointer to map
1438 * Use: Create an address map, properly set up.
1441 extern void am_create(addrmap */*m*/);
1443 /* --- @am_destroy@ --- *
1445 * Arguments: @addrmap *m@ = pointer to map
1449 * Use: Destroy an address map, throwing away all the entries.
1452 extern void am_destroy(addrmap */*m*/);
1454 /* --- @am_find@ --- *
1456 * Arguments: @addrmap *m@ = pointer to map
1457 * @const addr *a@ = address to look up
1458 * @size_t sz@ = size of block to allocate
1459 * @unsigned *f@ = where to store flags
1461 * Returns: Pointer to found item, or null.
1463 * Use: Finds a record with the given IP address, set @*f@ nonzero
1464 * and returns it. If @sz@ is zero, and no match was found,
1465 * return null; otherwise allocate a new block of @sz@ bytes,
1466 * clear @*f@ to zero and return the block pointer.
1469 extern void *am_find(addrmap */*m*/, const addr */*a*/,
1470 size_t /*sz*/, unsigned */*f*/);
1472 /* --- @am_remove@ --- *
1474 * Arguments: @addrmap *m@ = pointer to map
1475 * @void *i@ = pointer to the item
1479 * Use: Removes an item from the map.
1482 extern void am_remove(addrmap */*m*/, void */*i*/);
1484 /*----- Privilege separation ----------------------------------------------*/
1486 /* --- @ps_trace@ --- *
1488 * Arguments: @unsigned mask@ = trace mask to check
1489 * @const char *fmt@ = message format
1490 * @...@ = values for placeholders
1494 * Use: Writes a trace message.
1497 T( extern void PRINTF_LIKE(2, 3)
1498 ps_trace(unsigned /*mask*/, const char */*fmt*/, ...); )
1500 /* --- @ps_warn@ --- *
1502 * Arguments: @const char *fmt@ = message format
1503 * @...@ = values for placeholders
1507 * Use: Writes a warning message.
1510 extern void PRINTF_LIKE(1, 2) ps_warn(const char */*fmt*/, ...);
1512 /* --- @ps_tunfd@ --- *
1514 * Arguments: @const tunnel_ops *tops@ = pointer to tunnel operations
1515 * @char **ifn@ = where to put the interface name
1517 * Returns: The file descriptor, or @-1@ on error.
1519 * Use: Fetches a file descriptor for a tunnel driver.
1522 extern int ps_tunfd(const tunnel_ops */*tops*/, char **/*ifn*/);
1524 /* --- @ps_split@ --- *
1526 * Arguments: @int detachp@ = whether to detach the child from its terminal
1528 * Returns: Zero on success, @-1@ on failure.
1530 * Use: Separates off the privileged tunnel-opening service from the
1531 * rest of the server.
1534 extern int ps_split(int /*detachp*/);
1536 /* --- @ps_quit@ --- *
1542 * Use: Detaches from the helper process.
1545 extern void ps_quit(void);
1547 /*----- Peer management ---------------------------------------------------*/
1549 /* --- @p_updateaddr@ --- *
1551 * Arguments: @peer *p@ = pointer to peer block
1552 * @const addr *a@ = address to associate with this peer
1554 * Returns: Zero if the address was changed; @+1@ if it was already
1557 * Use: Updates our idea of @p@'s address.
1560 extern int p_updateaddr(peer */*p*/, const addr */*a*/);
1562 /* --- @p_txstart@ --- *
1564 * Arguments: @peer *p@ = pointer to peer block
1565 * @unsigned msg@ = message type code
1567 * Returns: A pointer to a buffer to write to.
1569 * Use: Starts sending to a peer. Only one send can happen at a
1573 extern buf *p_txstart(peer */*p*/, unsigned /*msg*/);
1575 /* --- @p_txaddr@ --- *
1577 * Arguments: @const addr *a@ = recipient address
1578 * @const void *p@ = pointer to packet to send
1579 * @size_t sz@ = length of packet
1581 * Returns: Zero if successful, nonzero on error.
1583 * Use: Sends a packet to an address which (possibly) isn't a current
1587 extern int p_txaddr(const addr */*a*/, const void */*p*/, size_t /*sz*/);
1589 /* --- @p_txend@ --- *
1591 * Arguments: @peer *p@ = pointer to peer block
1592 * @unsigned f@ = flags
1596 * Use: Sends a packet to the peer.
1599 #define TXF_WGT 1u /* Include in who-goes-there table */
1600 extern void p_txend(peer */*p*/, unsigned /*f*/);
1602 /* --- @p_pingsend@ --- *
1604 * Arguments: @peer *p@ = destination peer
1605 * @ping *pg@ = structure to fill in
1606 * @unsigned type@ = message type
1607 * @unsigned long timeout@ = how long to wait before giving up
1608 * @void (*func)(int, void *)@ = callback function
1609 * @void *arg@ = argument for callback
1611 * Returns: Zero if successful, nonzero if it failed.
1613 * Use: Sends a ping to a peer. Call @func@ with a nonzero argument
1614 * if we get an answer within the timeout, or zero if no answer.
1617 extern int p_pingsend(peer */*p*/, ping */*pg*/, unsigned /*type*/,
1618 unsigned long /*timeout*/,
1619 void (*/*func*/)(int, void *), void */*arg*/);
1621 /* --- @p_pingdone@ --- *
1623 * Arguments: @ping *p@ = ping structure
1624 * @int rc@ = return code to pass on
1628 * Use: Disposes of a ping structure, maybe sending a notification.
1631 extern void p_pingdone(ping */*p*/, int /*rc*/);
1633 /* --- @p_greet@ --- *
1635 * Arguments: @peer *p@ = peer to send to
1636 * @const void *c@ = pointer to challenge
1637 * @size_t sz@ = size of challenge
1641 * Use: Sends a greeting packet.
1644 extern void p_greet(peer */*p*/, const void */*c*/, size_t /*sz*/);
1646 /* --- @p_tun@ --- *
1648 * Arguments: @peer *p@ = pointer to peer block
1649 * @buf *b@ = buffer containing incoming packet
1653 * Use: Handles a packet which needs to be sent to a peer.
1656 extern void p_tun(peer */*p*/, buf */*b*/);
1658 /* --- @p_keyreload@ --- *
1664 * Use: Forces a check of the daemon's keyring files.
1667 extern void p_keyreload(void);
1669 /* --- @p_interval@ --- *
1675 * Use: Called periodically to do tidying.
1678 extern void p_interval(void);
1680 /* --- @p_stats@ --- *
1682 * Arguments: @peer *p@ = pointer to a peer block
1684 * Returns: A pointer to the peer's statistics.
1687 extern stats *p_stats(peer */*p*/);
1689 /* --- @p_ifname@ --- *
1691 * Arguments: @peer *p@ = pointer to a peer block
1693 * Returns: A pointer to the peer's interface name.
1696 extern const char *p_ifname(peer */*p*/);
1698 /* --- @p_setifname@ --- *
1700 * Arguments: @peer *p@ = pointer to a peer block
1701 * @const char *name@ = pointer to the new name
1705 * Use: Changes the name held for a peer's interface.
1708 extern void p_setifname(peer */*p*/, const char */*name*/);
1710 /* --- @p_addr@ --- *
1712 * Arguments: @peer *p@ = pointer to a peer block
1714 * Returns: A pointer to the peer's address.
1717 extern const addr *p_addr(peer */*p*/);
1719 /* --- @p_bind@ --- *
1721 * Arguments: @struct addrinfo *ailist@ = addresses to bind to
1723 * Returns: Zero on success, @-1@ on failure.
1725 * Use: Binds to the main UDP sockets.
1728 extern int p_bind(struct addrinfo */*ailist*/);
1730 /* --- @p_unbind@ --- *
1736 * Use: Unbinds the UDP sockets. There must not be any active peers,
1737 * and none can be created until the sockets are rebound.
1740 extern void p_unbind(void);
1742 /* --- @p_init@ --- *
1748 * Use: Initializes the peer system.
1751 extern void p_init(void);
1753 /* --- @p_addtun@ --- *
1755 * Arguments: @const tunnel_ops *tops@ = tunnel ops to add
1757 * Returns: Zero on success, @-1@ on failure.
1759 * Use: Adds a tunnel class to the list of known classes, if it
1760 * initializes properly. If there is no current default tunnel,
1761 * then this one is made the default.
1763 * Does nothing if the tunnel class is already known. So adding
1764 * a bunch of tunnels takes quadratic time, but there will be
1765 * too few to care about.
1768 extern int p_addtun(const tunnel_ops */*tops*/);
1770 /* --- @p_setdflttun@ --- *
1772 * Arguments: @const tunnel_ops *tops@ = tunnel ops to set
1776 * Use: Sets the default tunnel. It must already be registered. The
1777 * old default is forgotten.
1780 extern void p_setdflttun(const tunnel_ops */*tops*/);
1782 /* --- @p_dflttun@ --- *
1786 * Returns: A pointer to the current default tunnel operations, or null
1787 * if no tunnels are defined.
1790 extern const tunnel_ops *p_dflttun(void);
1792 /* --- @p_findtun@ --- *
1794 * Arguments: @const char *name@ = tunnel name
1796 * Returns: Pointer to the tunnel operations, or null.
1798 * Use: Finds the operations for a named tunnel class.
1801 extern const tunnel_ops *p_findtun(const char */*name*/);
1803 /* --- @p_mktuniter@ --- *
1805 * Arguments: @tuniter *i@ = pointer to iterator to initialize
1809 * Use: Initializes a tunnel iterator.
1812 extern void p_mktuniter(tun_iter */*i*/);
1814 /* --- @p_nexttun@ --- *
1816 * Arguments: @tuniter *i@ = pointer to iterator
1818 * Returns: Pointer to the next tunnel's operations, or null.
1821 extern const tunnel_ops *p_nexttun(tun_iter */*i*/);
1823 /* --- @FOREACH_TUN@ --- *
1825 * Arguments: @tops@ = name to bind to each tunnel
1826 * @stuff@ = thing to do for each item
1828 * Use: Does something for each known tunnel class.
1831 #define FOREACH_TUN(tops, stuff) do { \
1833 const tunnel_ops *tops; \
1834 for (p_mktuniter(&i_); (tops = p_nexttun(&i_)) != 0; ) stuff; \
1837 /* --- @p_create@ --- *
1839 * Arguments: @peerspec *spec@ = information about this peer
1841 * Returns: Pointer to the peer block, or null if it failed.
1843 * Use: Creates a new named peer block. No peer is actually attached
1847 extern peer *p_create(peerspec */*spec*/);
1849 /* --- @p_name@ --- *
1851 * Arguments: @peer *p@ = pointer to a peer block
1853 * Returns: A pointer to the peer's name.
1855 * Use: Equivalent to @p_spec(p)->name@.
1858 extern const char *p_name(peer */*p*/);
1860 /* --- @p_tag@ --- *
1862 * Arguments: @peer *p@ = pointer to a peer block
1864 * Returns: A pointer to the peer's public key tag.
1867 extern const char *p_tag(peer */*p*/);
1869 /* --- @p_privtag@ --- *
1871 * Arguments: @peer *p@ = pointer to a peer block
1873 * Returns: A pointer to the peer's private key tag.
1876 extern const char *p_privtag(peer */*p*/);
1878 /* --- @p_spec@ --- *
1880 * Arguments: @peer *p@ = pointer to a peer block
1882 * Returns: Pointer to the peer's specification
1885 extern const peerspec *p_spec(peer */*p*/);
1887 /* --- @p_findbyaddr@ --- *
1889 * Arguments: @const addr *a@ = address to look up
1891 * Returns: Pointer to the peer block, or null if not found.
1893 * Use: Finds a peer by address.
1896 extern peer *p_findbyaddr(const addr */*a*/);
1898 /* --- @p_find@ --- *
1900 * Arguments: @const char *name@ = name to look up
1902 * Returns: Pointer to the peer block, or null if not found.
1904 * Use: Finds a peer by name.
1907 extern peer *p_find(const char */*name*/);
1909 /* --- @p_destroy@ --- *
1911 * Arguments: @peer *p@ = pointer to a peer
1912 * @int bye@ = say goodbye to the peer?
1916 * Use: Destroys a peer.
1919 extern void p_destroy(peer */*p*/, int /*bye*/);
1921 /* --- @p_destroyall@ --- *
1927 * Use: Destroys all of the peers, saying goodbye.
1930 extern void p_destroyall(void);
1932 /* --- @FOREACH_PEER@ --- *
1934 * Arguments: @p@ = name to bind to each peer
1935 * @stuff@ = thing to do for each item
1937 * Use: Does something for each current peer.
1940 #define FOREACH_PEER(p, stuff) do { \
1943 for (p_mkiter(&i_); (p = p_next(&i_)) != 0; ) stuff \
1946 /* --- @p_mkiter@ --- *
1948 * Arguments: @peer_iter *i@ = pointer to an iterator
1952 * Use: Initializes the iterator.
1955 extern void p_mkiter(peer_iter */*i*/);
1957 /* --- @p_next@ --- *
1959 * Arguments: @peer_iter *i@ = pointer to an iterator
1961 * Returns: Next peer, or null if at the end.
1963 * Use: Returns the next peer.
1966 extern peer *p_next(peer_iter */*i*/);
1968 /*----- The interval timer ------------------------------------------------*/
1970 /* --- @iv_addreason@ --- *
1976 * Use: Adds an `interval timer reason'; if there are no others, the
1977 * interval timer is engaged.
1980 extern void iv_addreason(void);
1982 /* --- @iv_rmreason@ --- *
1988 * Use: Removes an interval timer reason; if there are none left, the
1989 * interval timer is disengaged.
1992 extern void iv_rmreason(void);
1994 /*----- The main loop -----------------------------------------------------*/
1996 /* --- @lp_init@ --- *
2002 * Use: Initializes the main loop. Most importantly, this sets up
2003 * the select multiplexor that everything else hooks onto.
2006 extern void lp_init(void);
2008 /* --- @lp_end@ --- *
2014 * Use: Requests an exit from the main loop.
2017 extern void lp_end(void);
2019 /* --- @lp_run@ --- *
2023 * Returns: Zero on successful termination; @-1@ if things went wrong.
2025 * Use: Cranks the main loop until it should be cranked no more.
2028 extern int lp_run(void);
2030 /*----- Tunnel drivers ----------------------------------------------------*/
2033 extern const tunnel_ops tun_linux;
2037 extern const tunnel_ops tun_unet;
2041 extern const tunnel_ops tun_bsd;
2044 extern const tunnel_ops tun_slip;
2046 /*----- Other handy utilities ---------------------------------------------*/
2048 /* --- @timestr@ --- *
2050 * Arguments: @time_t t@ = a time to convert
2052 * Returns: A pointer to a textual representation of the time.
2054 * Use: Converts a time to a textual representation. Corrupts
2058 extern const char *timestr(time_t /*t*/);
2060 /* --- @mystrieq@ --- *
2062 * Arguments: @const char *x, *y@ = two strings
2064 * Returns: True if @x@ and @y are equal, up to case.
2067 extern int mystrieq(const char */*x*/, const char */*y*/);
2071 * Arguments: @int af@ = an address family code
2073 * Returns: The index of the address family's record in @aftab@, or @-1@.
2076 extern int afix(int af);
2078 /* --- @addrsz@ --- *
2080 * Arguments: @const addr *a@ = a network address
2082 * Returns: The size of the address, for passing into the sockets API.
2085 extern socklen_t addrsz(const addr */*a*/);
2087 /* --- @getport@, @setport@ --- *
2089 * Arguments: @addr *a@ = a network address
2090 * @unsigned port@ = port number to set
2094 * Use: Retrieves or sets the port number in an address structure.
2097 extern unsigned getport(addr */*a*/);
2098 extern void setport(addr */*a*/, unsigned /*port*/);
2100 /* --- @seq_reset@ --- *
2102 * Arguments: @seqwin *s@ = sequence-checking window
2106 * Use: Resets a sequence number window.
2109 extern void seq_reset(seqwin */*s*/);
2111 /* --- @seq_check@ --- *
2113 * Arguments: @seqwin *s@ = sequence-checking window
2114 * @uint32 q@ = sequence number to check
2115 * @const char *service@ = service to report message from
2117 * Returns: A @SEQ_@ code.
2119 * Use: Checks a sequence number against the window, updating things
2123 extern int seq_check(seqwin */*s*/, uint32 /*q*/, const char */*service*/);
2125 typedef struct ratelim {
2126 unsigned n, max, persec;
2127 struct timeval when;
2130 /* --- @ratelim_init@ --- *
2132 * Arguments: @ratelim *r@ = rate-limiting state to fill in
2133 * @unsigned persec@ = credit to accumulate per second
2134 * @unsigned max@ = maximum credit to retain
2138 * Use: Initialize a rate-limiting state.
2141 extern void ratelim_init(ratelim */*r*/,
2142 unsigned /*persec*/, unsigned /*max*/);
2144 /* --- @ratelim_withdraw@ --- *
2146 * Arguments: @ratelim *r@ = rate-limiting state
2147 * @unsigned n@ = credit to withdraw
2149 * Returns: Zero if successful; @-1@ if there is unsufficient credit
2151 * Use: Updates the state with any accumulated credit. Then, if
2152 * there there are more than @n@ credits available, withdraw @n@
2153 * and return successfully; otherwise, report failure.
2156 extern int ratelim_withdraw(ratelim */*r*/, unsigned /*n*/);
2158 /* --- @ies_encrypt@ --- *
2160 * Arguments: @kdata *kpub@ = recipient's public key
2161 * @unsigned ty@ = message type octet
2162 * @buf *b@ = input message buffer
2163 * @buf *bb@ = output buffer for the ciphertext
2165 * Returns: On error, returns a @KSERR_...@ code or breaks the buffer;
2166 * on success, returns zero and the buffer is good.
2168 * Use: Encrypts a message for a recipient, given their public key.
2169 * This does not (by itself) provide forward secrecy or sender
2170 * authenticity. The ciphertext is self-delimiting (unlike
2174 extern int ies_encrypt(kdata */*kpub*/, unsigned /*ty*/,
2175 buf */*b*/, buf */*bb*/);
2177 /* --- @ies_decrypt@ --- *
2179 * Arguments: @kdata *kpub@ = private key key
2180 * @unsigned ty@ = message type octet
2181 * @buf *b@ = input ciphertext buffer
2182 * @buf *bb@ = output buffer for the message
2184 * Returns: On error, returns a @KSERR_...@ code; on success, returns
2185 * zero and the buffer is good.
2187 * Use: Decrypts a message encrypted using @ies_encrypt@, given our
2191 extern int ies_decrypt(kdata */*kpriv*/, unsigned /*ty*/,
2192 buf */*b*/, buf */*bb*/);
2194 /*----- That's all, folks -------------------------------------------------*/