chiark / gitweb /
server/admin.h: Consolidate address construction during resolution.
[tripe] / server / peer.c
1 /* -*-c-*-
2  *
3  * Communication with the peer
4  *
5  * (c) 2001 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Trivial IP Encryption (TrIPE).
11  *
12  * TrIPE is free software: you can redistribute it and/or modify it under
13  * the terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your
15  * option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20  * for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE.  If not, see <https://www.gnu.org/licenses/>.
24  */
25
26 /*----- Header files ------------------------------------------------------*/
27
28 #include "tripe.h"
29
30 /*----- Global state ------------------------------------------------------*/
31
32 sel_file udpsock[NADDRFAM];
33
34 /*----- Static variables --------------------------------------------------*/
35
36 static sym_table byname;
37 static addrmap byaddr;
38 static unsigned nmobile;
39
40 /*----- Tunnel table ------------------------------------------------------*/
41
42 const tunnel_ops *tunnels[] = {
43 #ifdef TUN_LINUX
44   &tun_linux,
45 #endif
46 #ifdef TUN_BSD
47   &tun_bsd,
48 #endif
49 #ifdef TUN_UNET
50   &tun_unet,
51 #endif
52   &tun_slip,
53   0
54 }, *tun_default;
55
56 /*----- Main code ---------------------------------------------------------*/
57
58 /* --- @p_pingtype@ --- *
59  *
60  * Arguments:   @unsigned msg@ = message type
61  *
62  * Returns:     String to describe the message.
63  */
64
65 static const char *p_pingtype(unsigned msg)
66 {
67   switch (msg & MSG_TYPEMASK) {
68     case MISC_PING:
69     case MISC_PONG:
70       return "transport-ping";
71     case MISC_EPING:
72     case MISC_EPONG:
73       return "encrypted-ping";
74     default:
75       abort();
76   }
77 }
78
79 /* --- @p_ponged@ --- *
80  *
81  * Arguments:   @peer *p@ = peer packet arrived from
82  *              @unsigned msg@ = message type
83  *              @buf *b@ = buffer containing payload
84  *
85  * Returns:     ---
86  *
87  * Use:         Processes a ping response.
88  */
89
90 static void p_ponged(peer *p, unsigned msg, buf *b)
91 {
92   uint32 id;
93   const octet *magic;
94   ping *pg;
95
96   IF_TRACING(T_PEER, {
97     trace(T_PEER, "peer: received %s reply from %s",
98           p_pingtype(msg), p->spec.name);
99     trace_block(T_PACKET, "peer: ping contents", BBASE(b), BSZ(b));
100   })
101
102   if (buf_getu32(b, &id) ||
103       (magic = buf_get(b, sizeof(pg->magic))) == 0 ||
104       BLEFT(b)) {
105     a_warn("PEER", "?PEER", p, "malformed-%s", p_pingtype(msg), A_END);
106     return;
107   }
108
109   for (pg = p->pings; pg; pg = pg->next) {
110     if (pg->id == id)
111       goto found;
112   }
113   a_warn("PEER",
114          "?PEER", p,
115          "unexpected-%s", p_pingtype(msg),
116          "0x%08lx", (unsigned long)id,
117          A_END);
118   return;
119
120 found:
121   if (memcmp(magic, pg->magic, sizeof(pg->magic)) != 0) {
122     a_warn("PEER", "?PEER", p, "corrupt-%s", p_pingtype(msg), A_END);
123     return;
124   }
125   p_pingdone(pg, PING_OK);
126 }
127
128 /* --- @p_rxupdstats@ --- *
129  *
130  * Arguments:   @peer *p@ = peer to update
131  *              @size_t n@ = size of incoming packet
132  *
133  * Returns:     ---
134  *
135  * Use:         Updates the peer's incoming packet statistics.
136  */
137
138 static void p_rxupdstats(peer *p, size_t n)
139 {
140   p->st.t_last = time(0);
141   p->st.n_in++;
142   p->st.sz_in += n;
143 }
144
145 /* --- @p_encrypt@ --- *
146  *
147  * Arguments:   @peer *p@ = peer to encrypt message to
148  *              @int ty@ message type to send
149  *              @buf *bin, *bout@ = input and output buffers
150  *
151  * Returns:     ---
152  *
153  * Use:         Convenience function for packet encryption.  Forces
154  *              renegotiation when necessary.  Check for the output buffer
155  *              being broken to find out whether the encryption was
156  *              successful.
157  */
158
159 static int p_encrypt(peer *p, int ty, buf *bin, buf *bout)
160 {
161   int err = ksl_encrypt(&p->ks, ty, bin, bout);
162
163   if (err == KSERR_REGEN) {
164     kx_start(&p->kx, 1);
165     err = 0;
166   }
167   if (!BOK(bout))
168     err = -1;
169   return (err);
170 }
171
172 /* --- @p_updateaddr@ --- *
173  *
174  * Arguments:   @peer *p@ = pointer to peer block
175  *              @const addr *a@ = address to associate with this peer
176  *
177  * Returns:     Zero if the address was changed; @+1@ if it was already
178  *              right.
179  *
180  * Use:         Updates our idea of @p@'s address.
181  */
182
183 int p_updateaddr(peer *p, const addr *a)
184 {
185   peer *q;
186   peer_byaddr *pa, *qa;
187   int ix;
188   unsigned f;
189
190   /* --- Figure out how to proceed --- *
191    *
192    * If this address already belongs to a different peer, then swap the
193    * addresses over.  This doesn't leave the displaced peer in an especially
194    * good state, but it ought to get sorted out soon enough.
195    */
196
197   pa = am_find(&byaddr, a, sizeof(peer_byaddr), &f);
198   if (f && pa->p == p)
199     return (+1);
200   else if (!f) {
201     T( trace(T_PEER, "peer: updating address for `%s'", p_name(p)); )
202     am_remove(&byaddr, p->byaddr);
203     p->byaddr = pa; p->spec.sa = *a; pa->p = p;
204     p->afix = afix(p->spec.sa.sa.sa_family); assert(p->afix >= 0);
205     a_notify("NEWADDR", "?PEER", p, "?ADDR", a, A_END);
206     return (0);
207   } else {
208     q = pa->p; qa = p->byaddr;
209     T( trace(T_PEER, "peer: swapping addresses for `%s' and `%s'",
210              p_name(p), p_name(q)); )
211     q->byaddr = qa; qa->p = q; q->spec.sa = p->spec.sa;
212     p->byaddr = pa; pa->p = p; p->spec.sa = *a;
213     ix = p->afix; p->afix = q->afix; q->afix = ix;
214     a_notify("NEWADDR", "?PEER", p, "?ADDR", a, A_END);
215     a_notify("NEWADDR", "?PEER", q, "?ADDR", &q->spec.sa, A_END);
216     return (0);
217   }
218 }
219
220 /* --- @p_decrypt@ --- *
221  *
222  * Arguments:   @peer **pp@ = pointer to peer to decrypt message from
223  *              @addr *a@ = address the packet arrived on
224  *              @size_t n@ = size of original incoming packet
225  *              @int ty@ = message type to expect
226  *              @buf *bin, *bout@ = input and output buffers
227  *
228  * Returns:     Zero on success; nonzero on error.
229  *
230  * Use:         Convenience function for packet decryption.  Reports errors
231  *              and updates statistics appropriately.
232  *
233  *              If @*pp@ is null on entry and there are mobile peers then we
234  *              see if any of them can decrypt the packet.  If so, we record
235  *              @*a@ as the peer's new address and send a notification.
236  */
237
238 static int p_decrypt(peer **pp, addr *a, size_t n,
239                      int ty, buf *bin, buf *bout)
240 {
241   peer *p, *q;
242   int err = KSERR_DECRYPT;
243
244   /* --- If we have a match on the source address then try that first --- */
245
246   q = *pp;
247   if (q) {
248     T( trace(T_PEER, "peer: decrypting packet from known peer `%s'",
249              p_name(q)); )
250     if ((err = ksl_decrypt(&q->ks, ty, bin, bout)) != KSERR_DECRYPT ||
251         !(q->spec.f & PSF_MOBILE) || nmobile == 1) {
252       p = q;
253       goto match;
254     }
255     T( trace(T_PEER, "peer: failed to decrypt: try other mobile peers..."); )
256   } else if (nmobile)
257     T( trace(T_PEER, "peer: unknown source: trying mobile peers...") );
258   else {
259     p = 0;
260     goto searched;
261   }
262
263   /* --- See whether any mobile peer is interested --- */
264
265   p = 0;
266   FOREACH_PEER(qq, {
267     if (qq == q || !(qq->spec.f & PSF_MOBILE)) continue;
268     if ((err = ksl_decrypt(&qq->ks, ty, bin, bout)) == KSERR_DECRYPT) {
269       T( trace(T_PEER, "peer: peer `%s' failed to decrypt",
270                p_name(qq)); )
271         continue;
272     } else {
273       p = qq;
274       IF_TRACING(T_PEER, {
275         if (!err)
276           trace(T_PEER, "peer: peer `%s' reports success", p_name(qq));
277         else {
278           trace(T_PEER, "peer: peer `%s' reports decryption error %d",
279                 p_name(qq), err);
280         }
281       })
282       break;
283     }
284   });
285
286   /* --- We've searched the mobile peers --- */
287
288 searched:
289   if (!p) {
290     if (!q)
291       a_warn("PEER", "-", "unexpected-source", "?ADDR", a, A_END);
292     else {
293       a_warn("PEER", "?PEER", p, "decrypt-failed",
294              "error-code", "%d", err, A_END);
295       p_rxupdstats(q, n);
296     }
297     return (-1);
298   }
299
300   /* --- We found one that accepted, so update the peer's address --- */
301
302   if (!err) {
303     *pp = p;
304     p_updateaddr(p, a);
305   }
306
307 match:
308   p_rxupdstats(p, n);
309   if (err) {
310     if (p) p->st.n_reject++;
311     a_warn("PEER", "?PEER", p, "decrypt-failed",
312            "error-code", "%d", err, A_END);
313     return (-1);
314   }
315   if (!BOK(bout))
316     return (-1);
317   return (0);
318 }
319
320 /* --- @p_read@ --- *
321  *
322  * Arguments:   @int fd@ = file descriptor to read from
323  *              @unsigned mode@ = what happened
324  *              @void *v@ = an uninteresting pointer
325  *
326  * Returns:     ---
327  *
328  * Use:         Reads a packet from somewhere.
329  */
330
331 static void p_read(int fd, unsigned mode, void *v)
332 {
333   peer *p = 0;
334   addr a;
335   socklen_t sz;
336   ssize_t n;
337   int ch;
338   buf b, bb;
339
340   /* --- Read the data --- */
341
342   QUICKRAND;
343   sz = sizeof(addr);
344   n = recvfrom(fd, buf_i, sizeof(buf_i), 0, &a.sa, &sz);
345   if (n < 0) {
346     a_warn("PEER", "-", "socket-read-error", "?ERRNO", A_END);
347     return;
348   }
349
350   /* --- If the packet is a greeting, don't check peers --- */
351
352   if (n && buf_i[0] == (MSG_MISC | MISC_GREET)) {
353     IF_TRACING(T_PEER, {
354       trace(T_PEER, "peer: greeting received from INET %s %u",
355             inet_ntoa(a.sin.sin_addr),
356             (unsigned)ntohs(a.sin.sin_port));
357       trace_block(T_PACKET, "peer: greeting contents", buf_i, n);
358     })
359     buf_init(&b, buf_i, n);
360     buf_getbyte(&b);
361     if (c_check(&b) || BLEFT(&b)) {
362       a_warn("PEER", "-", "invalid-greeting", A_END);
363       return;
364     }
365     a_notify("GREET",
366              "?B64", buf_i + 1, (size_t)(n - 1),
367              "?ADDR", &a,
368              A_END);
369     return;
370   }
371
372   /* --- Find the appropriate peer --- *
373    *
374    * At this stage, don't worry too much about whether we actually found it.
375    */
376
377   p = p_findbyaddr(&a);
378
379   IF_TRACING(T_PEER, {
380     if (p) {
381       trace(T_PEER,
382             "peer: packet received from `%s' from address INET %s %d",
383             p_name(p), inet_ntoa(a.sin.sin_addr), ntohs(a.sin.sin_port));
384     } else {
385       trace(T_PEER, "peer: packet received from unknown address INET %s %d",
386             inet_ntoa(a.sin.sin_addr), ntohs(a.sin.sin_port));
387     }
388     trace_block(T_PACKET, "peer: packet contents", buf_i, n);
389   })
390
391   /* --- Pick the packet apart --- */
392
393   buf_init(&b, buf_i, n);
394   if ((ch = buf_getbyte(&b)) < 0) {
395     a_warn("PEER", "?PEER", p, "bad-packet", "no-type", A_END);
396     return;
397   }
398   switch (ch & MSG_CATMASK) {
399     case MSG_PACKET:
400       if (ch & MSG_TYPEMASK) {
401         a_warn("PEER",
402                "?PEER", p,
403                "bad-packet",
404                "unknown-type", "0x%02x", ch,
405                A_END);
406         if (p) p->st.n_reject++;
407         return;
408       }
409       buf_init(&bb, buf_o, sizeof(buf_o));
410       if (p_decrypt(&p, &a, n, MSG_PACKET, &b, &bb))
411         return;
412       if (BOK(&bb)) {
413         p->st.n_ipin++;
414         p->st.sz_ipin += BSZ(&b);
415         p->t->ops->inject(p->t, &bb);
416       } else {
417         p->st.n_reject++;
418         a_warn("PEER", "?PEER", p, "packet-build-failed", A_END);
419       }
420       break;
421     case MSG_KEYEXCH:
422       if (!p) goto unexp;
423       p_rxupdstats(p, n);
424       kx_message(&p->kx, ch & MSG_TYPEMASK, &b);
425       break;
426     case MSG_MISC:
427       switch (ch & MSG_TYPEMASK) {
428         case MISC_NOP:
429           if (!p) goto unexp;
430           p_rxupdstats(p, n);
431           T( trace(T_PEER, "peer: received NOP packet"); )
432           break;
433         case MISC_PING:
434           if (!p) goto unexp;
435           p_rxupdstats(p, n);
436           buf_put(p_txstart(p, MSG_MISC | MISC_PONG), BCUR(&b), BLEFT(&b));
437           p_txend(p);
438           break;
439         case MISC_PONG:
440           if (!p) goto unexp;
441           p_rxupdstats(p, n);
442           p_ponged(p, MISC_PONG, &b);
443           break;
444         case MISC_EPING:
445           buf_init(&bb, buf_t, sizeof(buf_t));
446           if (p_decrypt(&p, &a, n, ch, &b, &bb))
447             return;
448           if (BOK(&bb)) {
449             buf_flip(&bb);
450             p_encrypt(p, MSG_MISC | MISC_EPONG, &bb,
451                       p_txstart(p, MSG_MISC | MISC_EPONG));
452             p_txend(p);
453           }
454           break;
455         case MISC_EPONG:
456           buf_init(&bb, buf_t, sizeof(buf_t));
457           if (p_decrypt(&p, &a, n, ch, &b, &bb))
458             return;
459           if (BOK(&bb)) {
460             buf_flip(&bb);
461             p_ponged(p, MISC_EPONG, &bb);
462           }
463           break;
464       }
465       break;
466     default:
467       if (p) p->st.n_reject++;
468       a_warn("PEER",
469              "?PEER", p,
470              "bad-packet",
471              "unknown-category", "0x%02x", ch,
472              A_END);
473       break;
474     unexp:
475       a_warn("PEER", "-", "unexpected-source", "?ADDR", &a, A_END);
476       break;
477   }
478 }
479
480 /* --- @p_txstart@ --- *
481  *
482  * Arguments:   @peer *p@ = pointer to peer block
483  *              @unsigned msg@ = message type code
484  *
485  * Returns:     A pointer to a buffer to write to.
486  *
487  * Use:         Starts sending to a peer.  Only one send can happen at a
488  *              time.
489  */
490
491 buf *p_txstart(peer *p, unsigned msg)
492 {
493   buf_init(&p->b, buf_o, sizeof(buf_o));
494   buf_putbyte(&p->b, msg);
495   return (&p->b);
496 }
497
498 /* --- @p_txend@ --- *
499  *
500  * Arguments:   @peer *p@ = pointer to peer block
501  *
502  * Returns:     ---
503  *
504  * Use:         Sends a packet to the peer.
505  */
506
507 static void p_setkatimer(peer *);
508
509 static int p_dotxend(peer *p)
510 {
511   socklen_t sasz = addrsz(&p->spec.sa);
512
513   if (!BOK(&p->b)) {
514     a_warn("PEER", "?PEER", p, "packet-build-failed", A_END);
515     return (0);
516   }
517   IF_TRACING(T_PEER, trace_block(T_PACKET, "peer: sending packet",
518                                  BBASE(&p->b), BLEN(&p->b)); )
519   if (sendto(udpsock[p->afix].fd, BBASE(&p->b), BLEN(&p->b),
520              0, &p->spec.sa.sa, sasz) < 0) {
521     a_warn("PEER", "?PEER", p, "socket-write-error", "?ERRNO", A_END);
522     return (0);
523   } else {
524     p->st.n_out++;
525     p->st.sz_out += BLEN(&p->b);
526     return (1);
527   }
528 }
529
530 void p_txend(peer *p)
531 {
532   if (p_dotxend(p) && p->spec.t_ka) {
533     sel_rmtimer(&p->tka);
534     p_setkatimer(p);
535   }
536 }
537
538 /* --- @p_pingwrite@ --- *
539  *
540  * Arguments:   @ping *p@ = ping structure
541  *              @buf *b@ = buffer to write in
542  *
543  * Returns:     ---
544  *
545  * Use:         Fills in a ping structure and writes the packet payload.
546  */
547
548 static void p_pingwrite(ping *p, buf *b)
549 {
550   static uint32 seq = 0;
551
552   p->id = U32(seq++);
553   GR_FILL(&rand_global, p->magic, sizeof(p->magic));
554   buf_putu32(b, p->id);
555   buf_put(b, p->magic, sizeof(p->magic));
556 }
557
558 /* --- @p_pingdone@ --- *
559  *
560  * Arguments:   @ping *p@ = ping structure
561  *              @int rc@ = return code to pass on
562  *
563  * Returns:     ---
564  *
565  * Use:         Disposes of a ping structure, maybe sending a notification.
566  */
567
568 void p_pingdone(ping *p, int rc)
569 {
570   if (p->prev) p->prev->next = p->next;
571   else p->p->pings = p->next;
572   if (p->next) p->next->prev = p->prev;
573   if (rc != PING_TIMEOUT) sel_rmtimer(&p->t);
574   T( trace(T_PEER, "peer: ping 0x%08lx done (rc = %d)",
575            (unsigned long)p->id, rc); )
576   if (rc >= 0) p->func(rc, p->arg);
577 }
578
579 /* --- @p_pingtimeout@ --- *
580  *
581  * Arguments:   @struct timeval *now@ = the time now
582  *              @void *pv@ = pointer to ping block
583  *
584  * Returns:     ---
585  *
586  * Use:         Called when a ping times out.
587  */
588
589 static void p_pingtimeout(struct timeval *now, void *pv)
590 {
591   ping *p = pv;
592
593   T( trace(T_PEER, "peer: ping 0x%08lx timed out", (unsigned long)p->id); )
594   p_pingdone(p, PING_TIMEOUT);
595 }
596
597 /* --- @p_pingsend@ --- *
598  *
599  * Arguments:   @peer *p@ = destination peer
600  *              @ping *pg@ = structure to fill in
601  *              @unsigned type@ = message type
602  *              @unsigned long timeout@ = how long to wait before giving up
603  *              @void (*func)(int, void *)@ = callback function
604  *              @void *arg@ = argument for callback
605  *
606  * Returns:     Zero if successful, nonzero if it failed.
607  *
608  * Use:         Sends a ping to a peer.  Call @func@ with a nonzero argument
609  *              if we get an answer within the timeout, or zero if no answer.
610  */
611
612 int p_pingsend(peer *p, ping *pg, unsigned type,
613                unsigned long timeout,
614                void (*func)(int, void *), void *arg)
615 {
616   buf *b, bb;
617   struct timeval tv;
618
619   switch (type) {
620     case MISC_PING:
621       pg->msg = MISC_PONG;
622       b = p_txstart(p, MSG_MISC | MISC_PING);
623       p_pingwrite(pg, b);
624       p_txend(p);
625       break;
626     case MISC_EPING:
627       pg->msg = MISC_EPONG;
628       b = p_txstart(p, MSG_MISC | MISC_EPING);
629       buf_init(&bb, buf_t, sizeof(buf_t));
630       p_pingwrite(pg, &bb);
631       buf_flip(&bb);
632       p_encrypt(p, MSG_MISC | MISC_EPING, &bb, b);
633       if (!BOK(b))
634         return (-1);
635       p_txend(p);
636       break;
637     default:
638       abort();
639       break;
640   }
641
642   pg->next = p->pings;
643   pg->prev = 0;
644   pg->p = p;
645   pg->func = func;
646   pg->arg = arg;
647   if (p->pings) p->pings->prev = pg;
648   p->pings = pg;
649   gettimeofday(&tv, 0);
650   tv.tv_sec += timeout;
651   sel_addtimer(&sel, &pg->t, &tv, p_pingtimeout, pg);
652   T( trace(T_PEER, "peer: send %s 0x%08lx to %s",
653            p_pingtype(type), (unsigned long)pg->id, p->spec.name); )
654   return (0);
655 }
656
657 /* --- @p_greet@ --- *
658  *
659  * Arguments:   @peer *p@ = peer to send to
660  *              @const void *c@ = pointer to challenge
661  *              @size_t sz@ = size of challenge
662  *
663  * Returns:     ---
664  *
665  * Use:         Sends a greeting packet.
666  */
667
668 void p_greet(peer *p, const void *c, size_t sz)
669 {
670   buf *b = p_txstart(p, MSG_MISC | MISC_GREET);
671   buf_put(b, c, sz);
672   p_txend(p);
673 }
674
675 /* --- @p_tun@ --- *
676  *
677  * Arguments:   @peer *p@ = pointer to peer block
678  *              @buf *b@ = buffer containing incoming packet
679  *
680  * Returns:     ---
681  *
682  * Use:         Handles a packet which needs to be sent to a peer.
683  */
684
685 void p_tun(peer *p, buf *b)
686 {
687   buf *bb = p_txstart(p, MSG_PACKET);
688
689   QUICKRAND;
690   p_encrypt(p, MSG_PACKET, b, bb);
691   if (BOK(bb) && BLEN(bb)) {
692     p->st.n_ipout++;
693     p->st.sz_ipout += BLEN(bb);
694     p_txend(p);
695   }
696 }
697
698 /* --- @p_keyreload@ --- *
699  *
700  * Arguments:   ---
701  *
702  * Returns:     ---
703  *
704  * Use:         Forces a check of the daemon's keyring files.
705  */
706
707 void p_keyreload(void)
708 {
709   if (km_reload())
710     FOREACH_PEER(p, { kx_newkeys(&p->kx); });
711 }
712
713 /* --- @p_interval@ --- *
714  *
715  * Arguments:   ---
716  *
717  * Returns:     ---
718  *
719  * Use:         Called periodically to do tidying.
720  */
721
722 void p_interval(void)
723 {
724   p_keyreload();
725   FOREACH_PEER(p, { ksl_prune(&p->ks); });
726 }
727
728 /* --- @p_stats@ --- *
729  *
730  * Arguments:   @peer *p@ = pointer to a peer block
731  *
732  * Returns:     A pointer to the peer's statistics.
733  */
734
735 stats *p_stats(peer *p) { return (&p->st); }
736
737 /* --- @p_ifname@ --- *
738  *
739  * Arguments:   @peer *p@ = pointer to a peer block
740  *
741  * Returns:     A pointer to the peer's interface name.
742  */
743
744 const char *p_ifname(peer *p) { return (p->ifname); }
745
746 /* --- @p_setifname@ --- *
747  *
748  * Arguments:   @peer *p@ = pointer to a peer block
749  *              @const char *name@ = pointer to the new name
750  *
751  * Returns:     ---
752  *
753  * Use:         Changes the name held for a peer's interface.
754  */
755
756 void p_setifname(peer *p, const char *name)
757 {
758   xfree(p->ifname);
759   p->ifname = xstrdup(name);
760   if (p->spec.tops->setifname)
761     p->spec.tops->setifname(p->t, name);
762 }
763
764 /* --- @p_addr@ --- *
765  *
766  * Arguments:   @peer *p@ = pointer to a peer block
767  *
768  * Returns:     A pointer to the peer's address.
769  */
770
771 const addr *p_addr(peer *p) { return (&p->spec.sa); }
772
773 /* --- @p_init@ --- *
774  *
775  * Arguments:   @struct in_addr addr@ = address to bind to
776  *              @unsigned port@ = port number to listen to
777  *
778  * Returns:     ---
779  *
780  * Use:         Initializes the peer system; creates the socket.
781  */
782
783 void p_init(struct in_addr addr, unsigned port)
784 {
785   int fd;
786   struct sockaddr_in sin;
787   int len = PKBUFSZ;
788
789   /* --- Note on socket buffer sizes --- *
790    *
791    * For some bizarre reason, Linux 2.2 (at least) doubles the socket buffer
792    * sizes I pass to @setsockopt@.  I'm not putting special-case code here
793    * for Linux: BSD (at least TCPv2) does what I tell it rather than second-
794    * guessing me.
795    */
796
797   if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
798     die(EXIT_FAILURE, "socket creation failed: %s", strerror(errno));
799   BURN(sin);
800   sin.sin_family = AF_INET;
801   sin.sin_addr = addr;
802   sin.sin_port = htons(port);
803   if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)))
804     die(EXIT_FAILURE, "bind failed: %s", strerror(errno));
805   if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)) ||
806       setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &len, sizeof(len))) {
807     die(EXIT_FAILURE, "failed to set socket buffer sizes: %s",
808         strerror(errno));
809   }
810   fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
811   sel_initfile(&sel, &udpsock[AFIX_INET], fd, SEL_READ, p_read, 0);
812   sel_addfile(&udpsock[AFIX_INET]);
813   T( trace(T_PEER, "peer: created socket"); )
814
815   sym_create(&byname);
816   am_create(&byaddr);
817 }
818
819 /* --- @p_port@ --- *
820  *
821  * Arguments:   @int i@ = address family index to retrieve
822  *
823  * Returns:     Port number used for socket.
824  */
825
826 unsigned p_port(int i)
827 {
828   addr a;
829   socklen_t sz = sizeof(addr);
830
831   if (getsockname(udpsock[i].fd, &a.sa, &sz))
832     die(EXIT_FAILURE, "couldn't read port number: %s", strerror(errno));
833   assert(a.sa.sa_family == AF_INET);
834   return (ntohs(a.sin.sin_port));
835 }
836
837 /* --- @p_keepalive@ --- *
838  *
839  * Arguments:   @struct timeval *now@ = the current time
840  *              @void *pv@ = peer to wake up
841  *
842  * Returns:     ---
843  *
844  * Use:         Sends a keepalive ping message to its peer.
845  */
846
847 static void p_keepalive(struct timeval *now, void *pv)
848 {
849   peer *p = pv;
850
851   p_txstart(p, MSG_MISC | MISC_NOP); p_dotxend(p);
852   T( trace(T_PEER, "peer: sent keepalive to %s", p->spec.name); )
853   p_setkatimer(p);
854 }
855
856 /* --- @p_setkatimer@ --- *
857  *
858  * Arguments:   @peer *p@ = peer to set
859  *
860  * Returns:     ---
861  *
862  * Use:         Resets the keepalive timer thing.
863  */
864
865 static void p_setkatimer(peer *p)
866 {
867   struct timeval tv;
868
869   if (!p->spec.t_ka)
870     return;
871   gettimeofday(&tv, 0);
872   tv.tv_sec += p->spec.t_ka;
873   sel_addtimer(&sel, &p->tka, &tv, p_keepalive, p);
874 }
875
876 /* --- @p_create@ --- *
877  *
878  * Arguments:   @peerspec *spec@ = information about this peer
879  *
880  * Returns:     Pointer to the peer block, or null if it failed.
881  *
882  * Use:         Creates a new named peer block.  No peer is actually attached
883  *              by this point.
884  */
885
886 peer *p_create(peerspec *spec)
887 {
888   peer *p = CREATE(peer);
889   const tunnel_ops *tops = spec->tops;
890   int fd;
891   unsigned f;
892
893   p->byname = sym_find(&byname, spec->name, -1, sizeof(peer_byname), &f);
894   if (f) goto tidy_0;
895   p->byaddr = am_find(&byaddr, &spec->sa, sizeof(peer_byaddr), &f);
896   if (f) goto tidy_1;
897   p->byname->p = p->byaddr->p = p;
898
899   T( trace(T_PEER, "peer: creating new peer `%s'", spec->name); )
900   p->spec = *spec;
901   p->spec.name = (/*unconst*/ char *)SYM_NAME(p->byname);
902   if (spec->tag) p->spec.tag = xstrdup(spec->tag);
903   if (spec->privtag) p->spec.privtag = xstrdup(spec->privtag);
904   p->ks = 0;
905   p->pings = 0;
906   p->ifname = 0;
907   p->afix = afix(p->spec.sa.sa.sa_family); assert(p->afix >= 0);
908   memset(&p->st, 0, sizeof(stats));
909   p->st.t_start = time(0);
910   if (!(tops->flags & TUNF_PRIVOPEN))
911     fd = -1;
912   else if ((fd = ps_tunfd(tops, &p->ifname)) < 0)
913     goto tidy_2;
914   if ((p->t = tops->create(p, fd, &p->ifname)) == 0)
915     goto tidy_3;
916   T( trace(T_TUNNEL, "peer: attached interface %s to peer `%s'",
917            p->ifname, p_name(p)); )
918   p_setkatimer(p);
919   if (kx_init(&p->kx, p, &p->ks, p->spec.f & PSF_KXMASK))
920     goto tidy_4;
921   a_notify("ADD",
922            "?PEER", p,
923            "%s", p->ifname,
924            "?ADDR", &p->spec.sa,
925            A_END);
926   if (!(p->spec.f & KXF_CORK)) {
927     a_notify("KXSTART", "?PEER", p, A_END);
928     /* Couldn't tell anyone before */
929   }
930   if (p->spec.f & PSF_MOBILE) nmobile++;
931   return (p);
932
933 tidy_4:
934   if (spec->t_ka) sel_rmtimer(&p->tka);
935   xfree(p->ifname);
936   p->t->ops->destroy(p->t);
937 tidy_3:
938   if (fd >= 0) close(fd);
939 tidy_2:
940   am_remove(&byaddr, p->byaddr);
941   if (p->spec.tag) xfree(p->spec.tag);
942   if (p->spec.privtag) xfree(p->spec.privtag);
943 tidy_1:
944   sym_remove(&byname, p->byname);
945 tidy_0:
946   DESTROY(p);
947   return (0);
948 }
949
950 /* --- @p_name@ --- *
951  *
952  * Arguments:   @peer *p@ = pointer to a peer block
953  *
954  * Returns:     A pointer to the peer's name.
955  */
956
957 const char *p_name(peer *p)
958   { if (p) return (p->spec.name); else return ("-"); }
959
960 /* --- @p_tag@ --- *
961  *
962  * Arguments:   @peer *p@ = pointer to a peer block
963  *
964  * Returns:     A pointer to the peer's public key tag.
965  */
966
967 const char *p_tag(peer *p)
968   { return (p->spec.tag ? p->spec.tag : p->spec.name); }
969
970 /* --- @p_privtag@ --- *
971  *
972  * Arguments:   @peer *p@ = pointer to a peer block
973  *
974  * Returns:     A pointer to the peer's private key tag.
975  */
976
977 const char *p_privtag(peer *p)
978   { return (p->spec.privtag ? p->spec.privtag : tag_priv); }
979
980 /* --- @p_spec@ --- *
981  *
982  * Arguments:   @peer *p@ = pointer to a peer block
983  *
984  * Returns:     Pointer to the peer's specification
985  */
986
987 const peerspec *p_spec(peer *p) { return (&p->spec); }
988
989 /* --- @p_findbyaddr@ --- *
990  *
991  * Arguments:   @const addr *a@ = address to look up
992  *
993  * Returns:     Pointer to the peer block, or null if not found.
994  *
995  * Use:         Finds a peer by address.
996  */
997
998 peer *p_findbyaddr(const addr *a)
999 {
1000   peer_byaddr *pa;
1001
1002   if ((pa = am_find(&byaddr, a, 0, 0)) != 0) {
1003     assert(pa->p);
1004     return (pa->p);
1005   }
1006   return (0);
1007 }
1008
1009 /* --- @p_find@ --- *
1010  *
1011  * Arguments:   @const char *name@ = name to look up
1012  *
1013  * Returns:     Pointer to the peer block, or null if not found.
1014  *
1015  * Use:         Finds a peer by name.
1016  */
1017
1018 peer *p_find(const char *name)
1019 {
1020   peer_byname *pn;
1021
1022   if ((pn = sym_find(&byname, name, -1, 0, 0)) != 0)
1023     return (pn->p);
1024   return (0);
1025 }
1026
1027 /* --- @p_destroy@ --- *
1028  *
1029  * Arguments:   @peer *p@ = pointer to a peer
1030  *
1031  * Returns:     ---
1032  *
1033  * Use:         Destroys a peer.
1034  */
1035
1036 void p_destroy(peer *p)
1037 {
1038   ping *pg, *ppg;
1039
1040   T( trace(T_PEER, "peer: destroying peer `%s'", p->spec.name); )
1041   a_notify("KILL", "%s", p->spec.name, A_END);
1042   ksl_free(&p->ks);
1043   kx_free(&p->kx);
1044   if (p->spec.f & PSF_MOBILE) nmobile--;
1045   if (p->ifname) xfree(p->ifname);
1046   if (p->spec.tag) xfree(p->spec.tag);
1047   if (p->spec.privtag) xfree(p->spec.privtag);
1048   p->t->ops->destroy(p->t);
1049   if (p->spec.t_ka) sel_rmtimer(&p->tka);
1050   for (pg = p->pings; pg; pg = ppg) {
1051     ppg = pg->next;
1052     p_pingdone(pg, PING_PEERDIED);
1053   }
1054   sym_remove(&byname, p->byname);
1055   am_remove(&byaddr, p->byaddr);
1056   DESTROY(p);
1057 }
1058
1059 /* --- @p_mkiter@ --- *
1060  *
1061  * Arguments:   @peer_iter *i@ = pointer to an iterator
1062  *
1063  * Returns:     ---
1064  *
1065  * Use:         Initializes the iterator.
1066  */
1067
1068 void p_mkiter(peer_iter *i) { sym_mkiter(&i->i, &byname); }
1069
1070 /* --- @p_next@ --- *
1071  *
1072  * Arguments:   @peer_iter *i@ = pointer to an iterator
1073  *
1074  * Returns:     Next peer, or null if at the end.
1075  *
1076  * Use:         Returns the next peer.
1077  */
1078
1079 peer *p_next(peer_iter *i)
1080 {
1081   peer_byname *pn;
1082
1083   if ((pn = sym_next(&i->i)) == 0)
1084     return (0);
1085   return (pn->p);
1086 }
1087
1088 /*----- That's all, folks -------------------------------------------------*/