server/: Build a proper interface for handling tunnel classes.
[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 udpsocket udpsock[NADDRFAM];
33
34 /*----- Static variables --------------------------------------------------*/
35
36 static sym_table byname;
37 static addrmap byaddr;
38 static unsigned nmobile;
39 static struct tunnel_node {
40 struct tunnel_node *next;
41 const tunnel_ops *tops;
42 } *tunnels, **tunnels_tail = &tunnels;
43 const tunnel_ops *dflttun;
44
45 /*----- Main code ---------------------------------------------------------*/
46
47 /* --- @p_pingtype@ --- *
48 *
49 * Arguments: @unsigned msg@ = message type
50 *
51 * Returns: String to describe the message.
52 */
53
54 static const char *p_pingtype(unsigned msg)
55 {
56 switch (msg & MSG_TYPEMASK) {
57 case MISC_PING:
58 case MISC_PONG:
59 return "transport-ping";
60 case MISC_EPING:
61 case MISC_EPONG:
62 return "encrypted-ping";
63 default:
64 abort();
65 }
66 }
67
68 /* --- @p_ponged@ --- *
69 *
70 * Arguments: @peer *p@ = peer packet arrived from
71 * @unsigned msg@ = message type
72 * @buf *b@ = buffer containing payload
73 *
74 * Returns: ---
75 *
76 * Use: Processes a ping response.
77 */
78
79 static void p_ponged(peer *p, unsigned msg, buf *b)
80 {
81 uint32 id;
82 const octet *magic;
83 ping *pg;
84
85 IF_TRACING(T_PEER, {
86 trace(T_PEER, "peer: received %s reply from %s",
87 p_pingtype(msg), p->spec.name);
88 trace_block(T_PACKET, "peer: ping contents", BBASE(b), BSZ(b));
89 })
90
91 if (buf_getu32(b, &id) ||
92 (magic = buf_get(b, sizeof(pg->magic))) == 0 ||
93 BLEFT(b)) {
94 a_warn("PEER", "?PEER", p, "malformed-%s", p_pingtype(msg), A_END);
95 return;
96 }
97
98 for (pg = p->pings; pg; pg = pg->next) {
99 if (pg->id == id)
100 goto found;
101 }
102 a_warn("PEER",
103 "?PEER", p,
104 "unexpected-%s", p_pingtype(msg),
105 "0x%08lx", (unsigned long)id,
106 A_END);
107 return;
108
109 found:
110 if (memcmp(magic, pg->magic, sizeof(pg->magic)) != 0) {
111 a_warn("PEER", "?PEER", p, "corrupt-%s", p_pingtype(msg), A_END);
112 return;
113 }
114 p_pingdone(pg, PING_OK);
115 }
116
117 /* --- @p_rxupdstats@ --- *
118 *
119 * Arguments: @peer *p@ = peer to update
120 * @size_t n@ = size of incoming packet
121 *
122 * Returns: ---
123 *
124 * Use: Updates the peer's incoming packet statistics.
125 */
126
127 static void p_rxupdstats(peer *p, size_t n)
128 {
129 p->st.t_last = time(0);
130 p->st.n_in++;
131 p->st.sz_in += n;
132 }
133
134 /* --- @p_encrypt@ --- *
135 *
136 * Arguments: @peer *p@ = peer to encrypt message to
137 * @int ty@ message type to send
138 * @buf *bin, *bout@ = input and output buffers
139 *
140 * Returns: ---
141 *
142 * Use: Convenience function for packet encryption. Forces
143 * renegotiation when necessary. Check for the output buffer
144 * being broken to find out whether the encryption was
145 * successful.
146 */
147
148 static int p_encrypt(peer *p, int ty, buf *bin, buf *bout)
149 {
150 int err = ksl_encrypt(&p->ks, ty, bin, bout);
151
152 if (err == KSERR_REGEN) {
153 kx_start(&p->kx, 1);
154 err = 0;
155 }
156 if (!BOK(bout))
157 err = -1;
158 return (err);
159 }
160
161 /* --- @p_updateaddr@ --- *
162 *
163 * Arguments: @peer *p@ = pointer to peer block
164 * @const addr *a@ = address to associate with this peer
165 *
166 * Returns: Zero if the address was changed; @+1@ if it was already
167 * right.
168 *
169 * Use: Updates our idea of @p@'s address.
170 */
171
172 int p_updateaddr(peer *p, const addr *a)
173 {
174 peer *q;
175 peer_byaddr *pa, *qa;
176 int ix;
177 unsigned f;
178
179 /* --- Figure out how to proceed --- *
180 *
181 * If this address already belongs to a different peer, then swap the
182 * addresses over. This doesn't leave the displaced peer in an especially
183 * good state, but it ought to get sorted out soon enough.
184 */
185
186 pa = am_find(&byaddr, a, sizeof(peer_byaddr), &f);
187 if (f && pa->p == p)
188 return (+1);
189 else if (!f) {
190 T( trace(T_PEER, "peer: updating address for `%s'", p_name(p)); )
191 am_remove(&byaddr, p->byaddr);
192 p->byaddr = pa; p->spec.sa = *a; pa->p = p;
193 p->afix = afix(p->spec.sa.sa.sa_family); assert(p->afix >= 0);
194 a_notify("NEWADDR", "?PEER", p, "?ADDR", a, A_END);
195 return (0);
196 } else {
197 q = pa->p; qa = p->byaddr;
198 T( trace(T_PEER, "peer: swapping addresses for `%s' and `%s'",
199 p_name(p), p_name(q)); )
200 q->byaddr = qa; qa->p = q; q->spec.sa = p->spec.sa;
201 p->byaddr = pa; pa->p = p; p->spec.sa = *a;
202 ix = p->afix; p->afix = q->afix; q->afix = ix;
203 a_notify("NEWADDR", "?PEER", p, "?ADDR", a, A_END);
204 a_notify("NEWADDR", "?PEER", q, "?ADDR", &q->spec.sa, A_END);
205 return (0);
206 }
207 }
208
209 /* --- @p_decrypt@ --- *
210 *
211 * Arguments: @peer **pp@ = pointer to peer to decrypt message from
212 * @addr *a@ = address the packet arrived on
213 * @size_t n@ = size of original incoming packet
214 * @int ty@ = message type to expect
215 * @buf *bin, *bout@ = input and output buffers
216 *
217 * Returns: Zero on success; nonzero on error.
218 *
219 * Use: Convenience function for packet decryption. Reports errors
220 * and updates statistics appropriately.
221 *
222 * If @*pp@ is null on entry and there are mobile peers then we
223 * see if any of them can decrypt the packet. If so, we record
224 * @*a@ as the peer's new address and send a notification.
225 */
226
227 static int p_decrypt(peer **pp, addr *a, size_t n,
228 int ty, buf *bin, buf *bout)
229 {
230 peer *p, *q;
231 int err = KSERR_DECRYPT;
232
233 /* --- If we have a match on the source address then try that first --- */
234
235 q = *pp;
236 if (q) {
237 T( trace(T_PEER, "peer: decrypting packet from known peer `%s'",
238 p_name(q)); )
239 if ((err = ksl_decrypt(&q->ks, ty, bin, bout)) != KSERR_DECRYPT ||
240 !(q->spec.f & PSF_MOBILE) || nmobile == 1) {
241 p = q;
242 goto match;
243 }
244 T( trace(T_PEER, "peer: failed to decrypt: try other mobile peers..."); )
245 } else if (nmobile)
246 T( trace(T_PEER, "peer: unknown source: trying mobile peers...") );
247 else {
248 p = 0;
249 goto searched;
250 }
251
252 /* --- See whether any mobile peer is interested --- */
253
254 p = 0;
255 FOREACH_PEER(qq, {
256 if (qq == q || !(qq->spec.f & PSF_MOBILE)) continue;
257 if ((err = ksl_decrypt(&qq->ks, ty, bin, bout)) == KSERR_DECRYPT) {
258 T( trace(T_PEER, "peer: peer `%s' failed to decrypt",
259 p_name(qq)); )
260 continue;
261 } else {
262 p = qq;
263 IF_TRACING(T_PEER, {
264 if (!err)
265 trace(T_PEER, "peer: peer `%s' reports success", p_name(qq));
266 else {
267 trace(T_PEER, "peer: peer `%s' reports decryption error %d",
268 p_name(qq), err);
269 }
270 })
271 break;
272 }
273 });
274
275 /* --- We've searched the mobile peers --- */
276
277 searched:
278 if (!p) {
279 if (!q)
280 a_warn("PEER", "-", "unexpected-source", "?ADDR", a, A_END);
281 else {
282 a_warn("PEER", "?PEER", p, "decrypt-failed",
283 "error-code", "%d", err, A_END);
284 p_rxupdstats(q, n);
285 }
286 return (-1);
287 }
288
289 /* --- We found one that accepted, so update the peer's address --- */
290
291 if (!err) {
292 *pp = p;
293 p_updateaddr(p, a);
294 }
295
296 match:
297 p_rxupdstats(p, n);
298 if (err) {
299 if (p) p->st.n_reject++;
300 a_warn("PEER", "?PEER", p, "decrypt-failed",
301 "error-code", "%d", err, A_END);
302 return (-1);
303 }
304 if (!BOK(bout))
305 return (-1);
306 return (0);
307 }
308
309 /* --- @p_read@ --- *
310 *
311 * Arguments: @int fd@ = file descriptor to read from
312 * @unsigned mode@ = what happened
313 * @void *v@ = an uninteresting pointer
314 *
315 * Returns: ---
316 *
317 * Use: Reads a packet from somewhere.
318 */
319
320 static void p_read(int fd, unsigned mode, void *v)
321 {
322 peer *p = 0;
323 addr a;
324 socklen_t sz;
325 ssize_t n;
326 int ch;
327 buf b, bb;
328 #ifndef NTRACE
329 int ix = -1;
330 char name[NI_MAXHOST], svc[NI_MAXSERV];
331 #endif
332
333 /* --- Read the data --- */
334
335 QUICKRAND;
336 sz = sizeof(addr);
337 n = recvfrom(fd, buf_i, sizeof(buf_i), 0, &a.sa, &sz);
338 if (n < 0) {
339 a_warn("PEER", "-", "socket-read-error", "?ERRNO", A_END);
340 return;
341 }
342 IF_TRACING(T_PEER, {
343 ix = afix(a.sa.sa_family);
344 getnameinfo(&a.sa, sz, name, sizeof(name), svc, sizeof(svc),
345 NI_NUMERICHOST | NI_NUMERICSERV);
346 })
347
348 /* --- If the packet is a greeting, don't check peers --- */
349
350 if (n && buf_i[0] == (MSG_MISC | MISC_GREET)) {
351 IF_TRACING(T_PEER, {
352 trace(T_PEER, "peer: greeting received from %s %s %s",
353 aftab[ix].name, name, svc);
354 trace_block(T_PACKET, "peer: greeting contents", buf_i, n);
355 })
356 buf_init(&b, buf_i, n);
357 buf_getbyte(&b);
358 if (c_check(0, 0, &b) || BLEFT(&b)) {
359 a_warn("PEER", "-", "invalid-greeting", A_END);
360 return;
361 }
362 a_notify("GREET",
363 "?B64", buf_i + 1, (size_t)(n - 1),
364 "?ADDR", &a,
365 A_END);
366 return;
367 }
368
369 /* --- Find the appropriate peer --- *
370 *
371 * At this stage, don't worry too much about whether we actually found it.
372 */
373
374 p = p_findbyaddr(&a);
375
376 IF_TRACING(T_PEER, {
377 if (p) {
378 trace(T_PEER,
379 "peer: packet received from `%s' from address %s %s %s",
380 p_name(p), aftab[ix].name, name, svc);
381 } else {
382 trace(T_PEER, "peer: packet received from unknown address %s %s %s",
383 aftab[ix].name, name, svc);
384 }
385 trace_block(T_PACKET, "peer: packet contents", buf_i, n);
386 })
387
388 /* --- Pick the packet apart --- */
389
390 buf_init(&b, buf_i, n);
391 if ((ch = buf_getbyte(&b)) < 0) {
392 a_warn("PEER", "?PEER", p, "bad-packet", "no-type", A_END);
393 return;
394 }
395 switch (ch & MSG_CATMASK) {
396 case MSG_PACKET:
397 if (ch & MSG_TYPEMASK) {
398 a_warn("PEER",
399 "?PEER", p,
400 "bad-packet",
401 "unknown-type", "0x%02x", ch,
402 A_END);
403 if (p) p->st.n_reject++;
404 return;
405 }
406 buf_init(&bb, buf_o, sizeof(buf_o));
407 if (p_decrypt(&p, &a, n, MSG_PACKET, &b, &bb))
408 return;
409 if (BOK(&bb)) {
410 p->st.n_ipin++;
411 p->st.sz_ipin += BSZ(&b);
412 p->t->ops->inject(p->t, &bb);
413 } else {
414 p->st.n_reject++;
415 a_warn("PEER", "?PEER", p, "packet-build-failed", A_END);
416 }
417 break;
418 case MSG_KEYEXCH:
419 if (p) p_rxupdstats(p, n);
420 if (kx_message(p ? &p->kx : 0, &a, ch & MSG_TYPEMASK, &b)) goto unexp;
421 break;
422 case MSG_MISC:
423 switch (ch & MSG_TYPEMASK) {
424 case MISC_NOP:
425 if (!p) goto unexp;
426 p_rxupdstats(p, n);
427 T( trace(T_PEER, "peer: received NOP packet"); )
428 break;
429 case MISC_PING:
430 if (!p) goto unexp;
431 p_rxupdstats(p, n);
432 buf_put(p_txstart(p, MSG_MISC | MISC_PONG), BCUR(&b), BLEFT(&b));
433 p_txend(p);
434 break;
435 case MISC_PONG:
436 if (!p) goto unexp;
437 p_rxupdstats(p, n);
438 p_ponged(p, MISC_PONG, &b);
439 break;
440 case MISC_EPING:
441 buf_init(&bb, buf_t, sizeof(buf_t));
442 if (p_decrypt(&p, &a, n, ch, &b, &bb))
443 return;
444 if (BOK(&bb)) {
445 buf_flip(&bb);
446 p_encrypt(p, MSG_MISC | MISC_EPONG, &bb,
447 p_txstart(p, MSG_MISC | MISC_EPONG));
448 p_txend(p);
449 }
450 break;
451 case MISC_EPONG:
452 buf_init(&bb, buf_t, sizeof(buf_t));
453 if (p_decrypt(&p, &a, n, ch, &b, &bb))
454 return;
455 if (BOK(&bb)) {
456 buf_flip(&bb);
457 p_ponged(p, MISC_EPONG, &bb);
458 }
459 break;
460 case MISC_BYE:
461 buf_init(&bb, buf_t, sizeof(buf_t));
462 if (p_decrypt(&p, &a, n, ch, &b, &bb)) return;
463 if (!(p->spec.f&PSF_EPHEM)) return;
464 if (BOK(&bb)) {
465 buf_flip(&bb);
466 if (BSZ(&bb)) return;
467 p_destroy(p, 0);
468 }
469 break;
470 }
471 break;
472 default:
473 if (p) p->st.n_reject++;
474 a_warn("PEER",
475 "?PEER", p,
476 "bad-packet",
477 "unknown-category", "0x%02x", ch,
478 A_END);
479 break;
480 unexp:
481 a_warn("PEER", "-", "unexpected-source", "?ADDR", &a, A_END);
482 break;
483 }
484 }
485
486 /* --- @p_txstart@ --- *
487 *
488 * Arguments: @peer *p@ = pointer to peer block
489 * @unsigned msg@ = message type code
490 *
491 * Returns: A pointer to a buffer to write to.
492 *
493 * Use: Starts sending to a peer. Only one send can happen at a
494 * time.
495 */
496
497 buf *p_txstart(peer *p, unsigned msg)
498 {
499 buf_init(&p->b, buf_o, sizeof(buf_o));
500 buf_putbyte(&p->b, msg);
501 return (&p->b);
502 }
503
504 /* --- @p_txaddr@ --- *
505 *
506 * Arguments: @const addr *a@ = recipient address
507 * @const void *p@ = pointer to packet to send
508 * @size_t sz@ = length of packet
509 *
510 * Returns: Zero if successful, nonzero on error.
511 *
512 * Use: Sends a packet to an address which (possibly) isn't a current
513 * peer.
514 */
515
516 int p_txaddr(const addr *a, const void *p, size_t sz)
517 {
518 socklen_t sasz = addrsz(a);
519 int i;
520
521 if ((i = afix(a->sa.sa_family)) < 0) {
522 a_warn("PEER", "?ADDR", a, "disabled-address-family", A_END);
523 return (-1);
524 }
525 IF_TRACING(T_PEER, trace_block(T_PACKET, "peer: sending packet", p, sz); )
526 if (sendto(udpsock[i].sf.fd, p, sz, 0, &a->sa, sasz) < 0) {
527 a_warn("PEER", "?ADDR", a, "socket-write-error", "?ERRNO", A_END);
528 return (-1);
529 }
530 return (0);
531 }
532
533 /* --- @p_txend@ --- *
534 *
535 * Arguments: @peer *p@ = pointer to peer block
536 *
537 * Returns: ---
538 *
539 * Use: Sends a packet to the peer.
540 */
541
542 static void p_setkatimer(peer *);
543
544 static int p_dotxend(peer *p)
545 {
546 socklen_t sasz = addrsz(&p->spec.sa);
547
548 if (!BOK(&p->b)) {
549 a_warn("PEER", "?PEER", p, "packet-build-failed", A_END);
550 return (0);
551 }
552 IF_TRACING(T_PEER, trace_block(T_PACKET, "peer: sending packet",
553 BBASE(&p->b), BLEN(&p->b)); )
554 if (sendto(udpsock[p->afix].sf.fd, BBASE(&p->b), BLEN(&p->b),
555 0, &p->spec.sa.sa, sasz) < 0) {
556 a_warn("PEER", "?PEER", p, "socket-write-error", "?ERRNO", A_END);
557 return (0);
558 } else {
559 p->st.n_out++;
560 p->st.sz_out += BLEN(&p->b);
561 return (1);
562 }
563 }
564
565 void p_txend(peer *p)
566 {
567 if (p_dotxend(p) && p->spec.t_ka) {
568 sel_rmtimer(&p->tka);
569 p_setkatimer(p);
570 }
571 }
572
573 /* --- @p_pingwrite@ --- *
574 *
575 * Arguments: @ping *p@ = ping structure
576 * @buf *b@ = buffer to write in
577 *
578 * Returns: ---
579 *
580 * Use: Fills in a ping structure and writes the packet payload.
581 */
582
583 static void p_pingwrite(ping *p, buf *b)
584 {
585 static uint32 seq = 0;
586
587 p->id = U32(seq++);
588 GR_FILL(&rand_global, p->magic, sizeof(p->magic));
589 buf_putu32(b, p->id);
590 buf_put(b, p->magic, sizeof(p->magic));
591 }
592
593 /* --- @p_pingdone@ --- *
594 *
595 * Arguments: @ping *p@ = ping structure
596 * @int rc@ = return code to pass on
597 *
598 * Returns: ---
599 *
600 * Use: Disposes of a ping structure, maybe sending a notification.
601 */
602
603 void p_pingdone(ping *p, int rc)
604 {
605 if (p->prev) p->prev->next = p->next;
606 else p->p->pings = p->next;
607 if (p->next) p->next->prev = p->prev;
608 if (rc != PING_TIMEOUT) sel_rmtimer(&p->t);
609 T( trace(T_PEER, "peer: ping 0x%08lx done (rc = %d)",
610 (unsigned long)p->id, rc); )
611 if (rc >= 0) p->func(rc, p->arg);
612 }
613
614 /* --- @p_pingtimeout@ --- *
615 *
616 * Arguments: @struct timeval *now@ = the time now
617 * @void *pv@ = pointer to ping block
618 *
619 * Returns: ---
620 *
621 * Use: Called when a ping times out.
622 */
623
624 static void p_pingtimeout(struct timeval *now, void *pv)
625 {
626 ping *p = pv;
627
628 T( trace(T_PEER, "peer: ping 0x%08lx timed out", (unsigned long)p->id); )
629 p_pingdone(p, PING_TIMEOUT);
630 }
631
632 /* --- @p_pingsend@ --- *
633 *
634 * Arguments: @peer *p@ = destination peer
635 * @ping *pg@ = structure to fill in
636 * @unsigned type@ = message type
637 * @unsigned long timeout@ = how long to wait before giving up
638 * @void (*func)(int, void *)@ = callback function
639 * @void *arg@ = argument for callback
640 *
641 * Returns: Zero if successful, nonzero if it failed.
642 *
643 * Use: Sends a ping to a peer. Call @func@ with a nonzero argument
644 * if we get an answer within the timeout, or zero if no answer.
645 */
646
647 int p_pingsend(peer *p, ping *pg, unsigned type,
648 unsigned long timeout,
649 void (*func)(int, void *), void *arg)
650 {
651 buf *b, bb;
652 struct timeval tv;
653
654 switch (type) {
655 case MISC_PING:
656 pg->msg = MISC_PONG;
657 b = p_txstart(p, MSG_MISC | MISC_PING);
658 p_pingwrite(pg, b);
659 p_txend(p);
660 break;
661 case MISC_EPING:
662 pg->msg = MISC_EPONG;
663 b = p_txstart(p, MSG_MISC | MISC_EPING);
664 buf_init(&bb, buf_t, sizeof(buf_t));
665 p_pingwrite(pg, &bb);
666 buf_flip(&bb);
667 p_encrypt(p, MSG_MISC | MISC_EPING, &bb, b);
668 if (!BOK(b))
669 return (-1);
670 p_txend(p);
671 break;
672 default:
673 abort();
674 break;
675 }
676
677 pg->next = p->pings;
678 pg->prev = 0;
679 pg->p = p;
680 pg->func = func;
681 pg->arg = arg;
682 if (p->pings) p->pings->prev = pg;
683 p->pings = pg;
684 gettimeofday(&tv, 0);
685 tv.tv_sec += timeout;
686 sel_addtimer(&sel, &pg->t, &tv, p_pingtimeout, pg);
687 T( trace(T_PEER, "peer: send %s 0x%08lx to %s",
688 p_pingtype(type), (unsigned long)pg->id, p->spec.name); )
689 return (0);
690 }
691
692 /* --- @p_greet@ --- *
693 *
694 * Arguments: @peer *p@ = peer to send to
695 * @const void *c@ = pointer to challenge
696 * @size_t sz@ = size of challenge
697 *
698 * Returns: ---
699 *
700 * Use: Sends a greeting packet.
701 */
702
703 void p_greet(peer *p, const void *c, size_t sz)
704 {
705 buf *b = p_txstart(p, MSG_MISC | MISC_GREET);
706 buf_put(b, c, sz);
707 p_txend(p);
708 }
709
710 /* --- @p_tun@ --- *
711 *
712 * Arguments: @peer *p@ = pointer to peer block
713 * @buf *b@ = buffer containing incoming packet
714 *
715 * Returns: ---
716 *
717 * Use: Handles a packet which needs to be sent to a peer.
718 */
719
720 void p_tun(peer *p, buf *b)
721 {
722 buf *bb = p_txstart(p, MSG_PACKET);
723
724 QUICKRAND;
725 p_encrypt(p, MSG_PACKET, b, bb);
726 if (BOK(bb) && BLEN(bb)) {
727 p->st.n_ipout++;
728 p->st.sz_ipout += BLEN(bb);
729 p_txend(p);
730 }
731 }
732
733 /* --- @p_keyreload@ --- *
734 *
735 * Arguments: ---
736 *
737 * Returns: ---
738 *
739 * Use: Forces a check of the daemon's keyring files.
740 */
741
742 void p_keyreload(void)
743 {
744 if (km_reload())
745 FOREACH_PEER(p, { kx_newkeys(&p->kx); });
746 }
747
748 /* --- @p_interval@ --- *
749 *
750 * Arguments: ---
751 *
752 * Returns: ---
753 *
754 * Use: Called periodically to do tidying.
755 */
756
757 void p_interval(void)
758 {
759 p_keyreload();
760 FOREACH_PEER(p, { ksl_prune(&p->ks); });
761 }
762
763 /* --- @p_stats@ --- *
764 *
765 * Arguments: @peer *p@ = pointer to a peer block
766 *
767 * Returns: A pointer to the peer's statistics.
768 */
769
770 stats *p_stats(peer *p) { return (&p->st); }
771
772 /* --- @p_ifname@ --- *
773 *
774 * Arguments: @peer *p@ = pointer to a peer block
775 *
776 * Returns: A pointer to the peer's interface name.
777 */
778
779 const char *p_ifname(peer *p) { return (p->ifname); }
780
781 /* --- @p_setifname@ --- *
782 *
783 * Arguments: @peer *p@ = pointer to a peer block
784 * @const char *name@ = pointer to the new name
785 *
786 * Returns: ---
787 *
788 * Use: Changes the name held for a peer's interface.
789 */
790
791 void p_setifname(peer *p, const char *name)
792 {
793 xfree(p->ifname);
794 p->ifname = xstrdup(name);
795 if (p->spec.tops->setifname)
796 p->spec.tops->setifname(p->t, name);
797 }
798
799 /* --- @p_addr@ --- *
800 *
801 * Arguments: @peer *p@ = pointer to a peer block
802 *
803 * Returns: A pointer to the peer's address.
804 */
805
806 const addr *p_addr(peer *p) { return (&p->spec.sa); }
807
808 /* --- @p_bind@ --- *
809 *
810 * Arguments: @struct addrinfo *ailist@ = addresses to bind to
811 *
812 * Returns: ---
813 *
814 * Use: Initializes the peer system; creates the socket.
815 */
816
817 void p_bind(struct addrinfo *ailist)
818 {
819 int fd;
820 int len = PKBUFSZ;
821 int yes = 1;
822 int i;
823 struct addrinfo *ai;
824 unsigned port, lastport = 0;
825 addr a;
826 socklen_t sz;
827
828 for (i = 0; i < NADDRFAM; i++) udpsock[i].sf.fd = -1;
829
830 for (ai = ailist; ai; ai = ai->ai_next) {
831 if ((i = afix(ai->ai_family)) < 0) continue;
832 if (udpsock[i].sf.fd != -1) continue;
833
834 /* --- Note on socket buffer sizes --- *
835 *
836 * For some bizarre reason, Linux 2.2 (at least) doubles the socket
837 * buffer sizes I pass to @setsockopt@. I'm not putting special-case
838 * code here for Linux: BSD (at least TCPv2) does what I tell it rather
839 * than second-guessing me.
840 */
841
842 if ((fd = socket(ai->ai_family, SOCK_DGRAM, 0)) < 0) {
843 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
844 "create-failed", "?ERRNO", A_END);
845 exit(EXIT_FAILURE);
846 }
847 if (i == AFIX_INET6 &&
848 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes))) {
849 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
850 "set-v6only-failed", "?ERRNO", A_END);
851 exit(EXIT_FAILURE);
852 }
853 assert(ai->ai_addrlen <= sizeof(a));
854 memcpy(&a, ai->ai_addr, ai->ai_addrlen);
855 if ((port = getport(&a)) == 0 && lastport) setport(&a, lastport);
856 if (bind(fd, &a.sa, addrsz(&a))) {
857 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
858 "bind-failed", "?ERRNO", A_END);
859 exit(EXIT_FAILURE);
860 }
861 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)) ||
862 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &len, sizeof(len))) {
863 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
864 "set-buffers-failed", "?ERRNO", A_END);
865 exit(EXIT_FAILURE);
866 }
867 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
868 if (port)
869 udpsock[i].port = port;
870 else {
871 sz = sizeof(a);
872 if (getsockname(fd, &a.sa, &sz)) {
873 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
874 "read-local-address-failed", "?ERRNO", A_END);
875 exit(EXIT_FAILURE);
876 }
877 udpsock[i].port = lastport = getport(&a);
878 }
879 T( trace(T_PEER, "peer: created %s socket", aftab[i].name); )
880 sel_initfile(&sel, &udpsock[i].sf, fd, SEL_READ, p_read, 0);
881 sel_addfile(&udpsock[i].sf);
882 }
883
884 }
885
886 /* --- @p_unbind@ --- *
887 *
888 * Arguments: ---
889 *
890 * Returns: ---
891 *
892 * Use: Unbinds the UDP sockets. There must not be any active peers,
893 * and none can be created until the sockets are rebound.
894 */
895
896 void p_unbind(void)
897 {
898 int i;
899
900 #ifndef NDEBUG
901 { peer_iter it; p_mkiter(&it); assert(!p_next(&it)); }
902 #endif
903
904 for (i = 0; i < NADDRFAM; i++) {
905 if (udpsock[i].sf.fd == -1) continue;
906 sel_rmfile(&udpsock[i].sf);
907 close(udpsock[i].sf.fd);
908 udpsock[i].sf.fd = -1;
909 }
910 }
911
912 /* --- @p_init@ --- *
913 *
914 * Arguments: ---
915 *
916 * Returns: ---
917 *
918 * Use: Initializes the peer system.
919 */
920
921 void p_init(void)
922 {
923 sym_create(&byname);
924 am_create(&byaddr);
925 }
926
927 /* --- @p_addtun@ --- *
928 *
929 * Arguments: @const tunnel_ops *tops@ = tunnel ops to add
930 *
931 * Returns: ---
932 *
933 * Use: Adds a tunnel class to the list of known classes. If there
934 * is no current default tunnel, then this one is made the
935 * default.
936 *
937 * Does nothing if the tunnel class is already known. So adding
938 * a bunch of tunnels takes quadratic time, but there will be
939 * too few to care about.
940 */
941
942 void p_addtun(const tunnel_ops *tops)
943 {
944 struct tunnel_node *tn;
945
946 for (tn = tunnels; tn; tn = tn->next)
947 if (tn->tops == tops) return;
948 tops->init();
949 tn = CREATE(struct tunnel_node);
950 tn->next = 0; tn->tops = tops;
951 *tunnels_tail = tn; tunnels_tail = &tn->next;
952 if (!dflttun) dflttun = tops;
953 }
954
955 /* --- @p_setdflttun@ --- *
956 *
957 * Arguments: @const tunnel_ops *tops@ = tunnel ops to set
958 *
959 * Returns: ---
960 *
961 * Use: Sets the default tunnel. It must already be registered. The
962 * old default is forgotten.
963 */
964
965 void p_setdflttun(const tunnel_ops *tops)
966 { dflttun = tops; }
967
968 /* --- @p_dflttun@ --- *
969 *
970 * Arguments: ---
971 *
972 * Returns: A pointer to the current default tunnel operations, or null
973 * if no tunnels are defined.
974 */
975
976 const tunnel_ops *p_dflttun(void) { return (dflttun); }
977
978 /* --- @p_findtun@ --- *
979 *
980 * Arguments: @const char *name@ = tunnel name
981 *
982 * Returns: Pointer to the tunnel operations, or null.
983 *
984 * Use: Finds the operations for a named tunnel class.
985 */
986
987 const tunnel_ops *p_findtun(const char *name)
988 {
989 const struct tunnel_node *tn;
990
991 for (tn = tunnels; tn; tn = tn->next)
992 if (mystrieq(tn->tops->name, name) == 0) return (tn->tops);
993 return (0);
994 }
995
996 /* --- @p_mktuniter@ --- *
997 *
998 * Arguments: @tuniter *i@ = pointer to iterator to initialize
999 *
1000 * Returns: ---
1001 *
1002 * Use: Initializes a tunnel iterator.
1003 */
1004
1005 void p_mktuniter(tun_iter *i) { i->next = tunnels; }
1006
1007 /* --- @p_nexttun@ --- *
1008 *
1009 * Arguments: @tuniter *i@ = pointer to iterator
1010 *
1011 * Returns: Pointer to the next tunnel's operations, or null.
1012 */
1013
1014 const tunnel_ops *p_nexttun(tun_iter *i)
1015 {
1016 const struct tunnel_node *tn = i->next;
1017
1018 if (!tn) return (0);
1019 else { i->next = tn->next; return (tn->tops); }
1020 }
1021
1022 /* --- @p_keepalive@ --- *
1023 *
1024 * Arguments: @struct timeval *now@ = the current time
1025 * @void *pv@ = peer to wake up
1026 *
1027 * Returns: ---
1028 *
1029 * Use: Sends a keepalive ping message to its peer.
1030 */
1031
1032 static void p_keepalive(struct timeval *now, void *pv)
1033 {
1034 peer *p = pv;
1035
1036 p_txstart(p, MSG_MISC | MISC_NOP); p_dotxend(p);
1037 T( trace(T_PEER, "peer: sent keepalive to %s", p->spec.name); )
1038 p_setkatimer(p);
1039 }
1040
1041 /* --- @p_setkatimer@ --- *
1042 *
1043 * Arguments: @peer *p@ = peer to set
1044 *
1045 * Returns: ---
1046 *
1047 * Use: Resets the keepalive timer thing.
1048 */
1049
1050 static void p_setkatimer(peer *p)
1051 {
1052 struct timeval tv;
1053
1054 if (!p->spec.t_ka)
1055 return;
1056 gettimeofday(&tv, 0);
1057 tv.tv_sec += p->spec.t_ka;
1058 sel_addtimer(&sel, &p->tka, &tv, p_keepalive, p);
1059 }
1060
1061 /* --- @p_create@ --- *
1062 *
1063 * Arguments: @peerspec *spec@ = information about this peer
1064 *
1065 * Returns: Pointer to the peer block, or null if it failed.
1066 *
1067 * Use: Creates a new named peer block. No peer is actually attached
1068 * by this point.
1069 */
1070
1071 peer *p_create(peerspec *spec)
1072 {
1073 peer *p = CREATE(peer);
1074 const tunnel_ops *tops = spec->tops;
1075 int fd;
1076 unsigned f;
1077
1078 p->byname = sym_find(&byname, spec->name, -1, sizeof(peer_byname), &f);
1079 if (f) goto tidy_0;
1080 p->byaddr = am_find(&byaddr, &spec->sa, sizeof(peer_byaddr), &f);
1081 if (f) goto tidy_1;
1082 p->byname->p = p->byaddr->p = p;
1083
1084 T( trace(T_PEER, "peer: creating new peer `%s'", spec->name); )
1085 p->spec = *spec;
1086 p->spec.name = (/*unconst*/ char *)SYM_NAME(p->byname);
1087 if (spec->tag) p->spec.tag = xstrdup(spec->tag);
1088 if (spec->privtag) p->spec.privtag = xstrdup(spec->privtag);
1089 if (spec->knock) p->spec.knock = xstrdup(spec->knock);
1090 p->ks = 0;
1091 p->pings = 0;
1092 p->ifname = 0;
1093 p->afix = afix(p->spec.sa.sa.sa_family); assert(p->afix >= 0);
1094 memset(&p->st, 0, sizeof(stats));
1095 p->st.t_start = time(0);
1096 if (!(tops->flags & TUNF_PRIVOPEN))
1097 fd = -1;
1098 else if ((fd = ps_tunfd(tops, &p->ifname)) < 0)
1099 goto tidy_2;
1100 if ((p->t = tops->create(p, fd, &p->ifname)) == 0)
1101 goto tidy_3;
1102 T( trace(T_TUNNEL, "peer: attached interface %s to peer `%s'",
1103 p->ifname, p_name(p)); )
1104 p_setkatimer(p);
1105 iv_addreason();
1106 if (kx_setup(&p->kx, p, &p->ks, p->spec.f & PSF_KXMASK))
1107 goto tidy_4;
1108 a_notify("ADD",
1109 "?PEER", p,
1110 "%s", p->ifname,
1111 "?ADDR", &p->spec.sa,
1112 A_END);
1113 if (!(p->spec.f & KXF_CORK)) {
1114 a_notify("KXSTART", "?PEER", p, A_END);
1115 /* Couldn't tell anyone before */
1116 }
1117 if (p->spec.f & PSF_MOBILE) nmobile++;
1118 return (p);
1119
1120 tidy_4:
1121 if (spec->t_ka) sel_rmtimer(&p->tka);
1122 xfree(p->ifname);
1123 p->t->ops->destroy(p->t);
1124 iv_rmreason();
1125 tidy_3:
1126 if (fd >= 0) close(fd);
1127 tidy_2:
1128 am_remove(&byaddr, p->byaddr);
1129 if (p->spec.tag) xfree(p->spec.tag);
1130 if (p->spec.privtag) xfree(p->spec.privtag);
1131 tidy_1:
1132 sym_remove(&byname, p->byname);
1133 tidy_0:
1134 DESTROY(p);
1135 return (0);
1136 }
1137
1138 /* --- @p_name@ --- *
1139 *
1140 * Arguments: @peer *p@ = pointer to a peer block
1141 *
1142 * Returns: A pointer to the peer's name.
1143 */
1144
1145 const char *p_name(peer *p)
1146 { if (p) return (p->spec.name); else return ("-"); }
1147
1148 /* --- @p_tag@ --- *
1149 *
1150 * Arguments: @peer *p@ = pointer to a peer block
1151 *
1152 * Returns: A pointer to the peer's public key tag.
1153 */
1154
1155 const char *p_tag(peer *p)
1156 { return (p->spec.tag ? p->spec.tag : p->spec.name); }
1157
1158 /* --- @p_privtag@ --- *
1159 *
1160 * Arguments: @peer *p@ = pointer to a peer block
1161 *
1162 * Returns: A pointer to the peer's private key tag.
1163 */
1164
1165 const char *p_privtag(peer *p)
1166 { return (p->spec.privtag ? p->spec.privtag : tag_priv); }
1167
1168 /* --- @p_spec@ --- *
1169 *
1170 * Arguments: @peer *p@ = pointer to a peer block
1171 *
1172 * Returns: Pointer to the peer's specification
1173 */
1174
1175 const peerspec *p_spec(peer *p) { return (&p->spec); }
1176
1177 /* --- @p_findbyaddr@ --- *
1178 *
1179 * Arguments: @const addr *a@ = address to look up
1180 *
1181 * Returns: Pointer to the peer block, or null if not found.
1182 *
1183 * Use: Finds a peer by address.
1184 */
1185
1186 peer *p_findbyaddr(const addr *a)
1187 {
1188 peer_byaddr *pa;
1189
1190 if ((pa = am_find(&byaddr, a, 0, 0)) != 0) {
1191 assert(pa->p);
1192 return (pa->p);
1193 }
1194 return (0);
1195 }
1196
1197 /* --- @p_find@ --- *
1198 *
1199 * Arguments: @const char *name@ = name to look up
1200 *
1201 * Returns: Pointer to the peer block, or null if not found.
1202 *
1203 * Use: Finds a peer by name.
1204 */
1205
1206 peer *p_find(const char *name)
1207 {
1208 peer_byname *pn;
1209
1210 if ((pn = sym_find(&byname, name, -1, 0, 0)) != 0)
1211 return (pn->p);
1212 return (0);
1213 }
1214
1215 /* --- @p_destroy@ --- *
1216 *
1217 * Arguments: @peer *p@ = pointer to a peer
1218 * @int bye@ = say goodbye to the peer?
1219 *
1220 * Returns: ---
1221 *
1222 * Use: Destroys a peer.
1223 */
1224
1225 void p_destroy(peer *p, int bye)
1226 {
1227 ping *pg, *ppg;
1228 buf *b, bb;
1229
1230 T( trace(T_PEER, "peer: destroying peer `%s'", p->spec.name); )
1231
1232 if (bye && (p->spec.f&PSF_EPHEM)) {
1233 b = p_txstart(p, MSG_MISC | MISC_BYE);
1234 buf_init(&bb, buf_t, sizeof(buf_t));
1235 assert(BOK(&bb)); buf_flip(&bb);
1236 p_encrypt(p, MSG_MISC | MISC_BYE, &bb, b);
1237 p_txend(p);
1238 }
1239
1240 a_notify("KILL", "%s", p->spec.name, A_END);
1241 ksl_free(&p->ks);
1242 kx_free(&p->kx);
1243 if (p->spec.f & PSF_MOBILE) nmobile--;
1244 if (p->ifname) xfree(p->ifname);
1245 if (p->spec.tag) xfree(p->spec.tag);
1246 if (p->spec.privtag) xfree(p->spec.privtag);
1247 if (p->spec.knock) xfree(p->spec.knock);
1248 p->t->ops->destroy(p->t);
1249 if (p->spec.t_ka) sel_rmtimer(&p->tka);
1250 for (pg = p->pings; pg; pg = ppg) {
1251 ppg = pg->next;
1252 p_pingdone(pg, PING_PEERDIED);
1253 }
1254 sym_remove(&byname, p->byname);
1255 am_remove(&byaddr, p->byaddr);
1256 iv_rmreason();
1257 DESTROY(p);
1258 }
1259
1260 /* --- @p_destroyall@ --- *
1261 *
1262 * Arguments: ---
1263 *
1264 * Returns: ---
1265 *
1266 * Use: Destroys all of the peers, saying goodbye.
1267 */
1268
1269 void p_destroyall(void) { FOREACH_PEER(p, { p_destroy(p, 1); }); }
1270
1271 /* --- @p_mkiter@ --- *
1272 *
1273 * Arguments: @peer_iter *i@ = pointer to an iterator
1274 *
1275 * Returns: ---
1276 *
1277 * Use: Initializes the iterator.
1278 */
1279
1280 void p_mkiter(peer_iter *i) { sym_mkiter(&i->i, &byname); }
1281
1282 /* --- @p_next@ --- *
1283 *
1284 * Arguments: @peer_iter *i@ = pointer to an iterator
1285 *
1286 * Returns: Next peer, or null if at the end.
1287 *
1288 * Use: Returns the next peer.
1289 */
1290
1291 peer *p_next(peer_iter *i)
1292 {
1293 peer_byname *pn;
1294
1295 if ((pn = sym_next(&i->i)) == 0)
1296 return (0);
1297 return (pn->p);
1298 }
1299
1300 /*----- That's all, folks -------------------------------------------------*/