0b5a6c22c56a8bd2a53503e2188555b5b34ed436
[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, 0);
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, 0);
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 * @unsigned f@ = flags
537 *
538 * Returns: ---
539 *
540 * Use: Sends a packet to the peer.
541 */
542
543 static void p_setkatimer(peer *);
544
545 static int p_dotxend(peer *p)
546 {
547 socklen_t sasz = addrsz(&p->spec.sa);
548
549 if (!BOK(&p->b)) {
550 a_warn("PEER", "?PEER", p, "packet-build-failed", A_END);
551 return (0);
552 }
553 IF_TRACING(T_PEER, trace_block(T_PACKET, "peer: sending packet",
554 BBASE(&p->b), BLEN(&p->b)); )
555 if (sendto(udpsock[p->afix].sf.fd, BBASE(&p->b), BLEN(&p->b),
556 0, &p->spec.sa.sa, sasz) < 0) {
557 a_warn("PEER", "?PEER", p, "socket-write-error", "?ERRNO", A_END);
558 return (0);
559 } else {
560 p->st.n_out++;
561 p->st.sz_out += BLEN(&p->b);
562 return (1);
563 }
564 }
565
566 void p_txend(peer *p, unsigned f)
567 {
568 if (p_dotxend(p)) {
569 if (p->spec.t_ka) {
570 sel_rmtimer(&p->tka);
571 p_setkatimer(p);
572 }
573 }
574 }
575
576 /* --- @p_pingwrite@ --- *
577 *
578 * Arguments: @ping *p@ = ping structure
579 * @buf *b@ = buffer to write in
580 *
581 * Returns: ---
582 *
583 * Use: Fills in a ping structure and writes the packet payload.
584 */
585
586 static void p_pingwrite(ping *p, buf *b)
587 {
588 static uint32 seq = 0;
589
590 p->id = U32(seq++);
591 GR_FILL(&rand_global, p->magic, sizeof(p->magic));
592 buf_putu32(b, p->id);
593 buf_put(b, p->magic, sizeof(p->magic));
594 }
595
596 /* --- @p_pingdone@ --- *
597 *
598 * Arguments: @ping *p@ = ping structure
599 * @int rc@ = return code to pass on
600 *
601 * Returns: ---
602 *
603 * Use: Disposes of a ping structure, maybe sending a notification.
604 */
605
606 void p_pingdone(ping *p, int rc)
607 {
608 if (p->prev) p->prev->next = p->next;
609 else p->p->pings = p->next;
610 if (p->next) p->next->prev = p->prev;
611 if (rc != PING_TIMEOUT) sel_rmtimer(&p->t);
612 T( trace(T_PEER, "peer: ping 0x%08lx done (rc = %d)",
613 (unsigned long)p->id, rc); )
614 if (rc >= 0) p->func(rc, p->arg);
615 }
616
617 /* --- @p_pingtimeout@ --- *
618 *
619 * Arguments: @struct timeval *now@ = the time now
620 * @void *pv@ = pointer to ping block
621 *
622 * Returns: ---
623 *
624 * Use: Called when a ping times out.
625 */
626
627 static void p_pingtimeout(struct timeval *now, void *pv)
628 {
629 ping *p = pv;
630
631 T( trace(T_PEER, "peer: ping 0x%08lx timed out", (unsigned long)p->id); )
632 p_pingdone(p, PING_TIMEOUT);
633 }
634
635 /* --- @p_pingsend@ --- *
636 *
637 * Arguments: @peer *p@ = destination peer
638 * @ping *pg@ = structure to fill in
639 * @unsigned type@ = message type
640 * @unsigned long timeout@ = how long to wait before giving up
641 * @void (*func)(int, void *)@ = callback function
642 * @void *arg@ = argument for callback
643 *
644 * Returns: Zero if successful, nonzero if it failed.
645 *
646 * Use: Sends a ping to a peer. Call @func@ with a nonzero argument
647 * if we get an answer within the timeout, or zero if no answer.
648 */
649
650 int p_pingsend(peer *p, ping *pg, unsigned type,
651 unsigned long timeout,
652 void (*func)(int, void *), void *arg)
653 {
654 buf *b, bb;
655 struct timeval tv;
656
657 switch (type) {
658 case MISC_PING:
659 pg->msg = MISC_PONG;
660 b = p_txstart(p, MSG_MISC | MISC_PING);
661 p_pingwrite(pg, b);
662 p_txend(p, 0);
663 break;
664 case MISC_EPING:
665 pg->msg = MISC_EPONG;
666 b = p_txstart(p, MSG_MISC | MISC_EPING);
667 buf_init(&bb, buf_t, sizeof(buf_t));
668 p_pingwrite(pg, &bb);
669 buf_flip(&bb);
670 p_encrypt(p, MSG_MISC | MISC_EPING, &bb, b);
671 if (!BOK(b))
672 return (-1);
673 p_txend(p, 0);
674 break;
675 default:
676 abort();
677 break;
678 }
679
680 pg->next = p->pings;
681 pg->prev = 0;
682 pg->p = p;
683 pg->func = func;
684 pg->arg = arg;
685 if (p->pings) p->pings->prev = pg;
686 p->pings = pg;
687 gettimeofday(&tv, 0);
688 tv.tv_sec += timeout;
689 sel_addtimer(&sel, &pg->t, &tv, p_pingtimeout, pg);
690 T( trace(T_PEER, "peer: send %s 0x%08lx to %s",
691 p_pingtype(type), (unsigned long)pg->id, p->spec.name); )
692 return (0);
693 }
694
695 /* --- @p_greet@ --- *
696 *
697 * Arguments: @peer *p@ = peer to send to
698 * @const void *c@ = pointer to challenge
699 * @size_t sz@ = size of challenge
700 *
701 * Returns: ---
702 *
703 * Use: Sends a greeting packet.
704 */
705
706 void p_greet(peer *p, const void *c, size_t sz)
707 {
708 buf *b = p_txstart(p, MSG_MISC | MISC_GREET);
709 buf_put(b, c, sz);
710 p_txend(p, 0);
711 }
712
713 /* --- @p_tun@ --- *
714 *
715 * Arguments: @peer *p@ = pointer to peer block
716 * @buf *b@ = buffer containing incoming packet
717 *
718 * Returns: ---
719 *
720 * Use: Handles a packet which needs to be sent to a peer.
721 */
722
723 void p_tun(peer *p, buf *b)
724 {
725 buf *bb = p_txstart(p, MSG_PACKET);
726
727 QUICKRAND;
728 p_encrypt(p, MSG_PACKET, b, bb);
729 if (BOK(bb) && BLEN(bb)) {
730 p->st.n_ipout++;
731 p->st.sz_ipout += BLEN(bb);
732 p_txend(p, 0);
733 }
734 }
735
736 /* --- @p_keyreload@ --- *
737 *
738 * Arguments: ---
739 *
740 * Returns: ---
741 *
742 * Use: Forces a check of the daemon's keyring files.
743 */
744
745 void p_keyreload(void)
746 {
747 if (km_reload())
748 FOREACH_PEER(p, { kx_newkeys(&p->kx); });
749 }
750
751 /* --- @p_interval@ --- *
752 *
753 * Arguments: ---
754 *
755 * Returns: ---
756 *
757 * Use: Called periodically to do tidying.
758 */
759
760 void p_interval(void)
761 {
762 p_keyreload();
763 FOREACH_PEER(p, { ksl_prune(&p->ks); });
764 }
765
766 /* --- @p_stats@ --- *
767 *
768 * Arguments: @peer *p@ = pointer to a peer block
769 *
770 * Returns: A pointer to the peer's statistics.
771 */
772
773 stats *p_stats(peer *p) { return (&p->st); }
774
775 /* --- @p_ifname@ --- *
776 *
777 * Arguments: @peer *p@ = pointer to a peer block
778 *
779 * Returns: A pointer to the peer's interface name.
780 */
781
782 const char *p_ifname(peer *p) { return (p->ifname); }
783
784 /* --- @p_setifname@ --- *
785 *
786 * Arguments: @peer *p@ = pointer to a peer block
787 * @const char *name@ = pointer to the new name
788 *
789 * Returns: ---
790 *
791 * Use: Changes the name held for a peer's interface.
792 */
793
794 void p_setifname(peer *p, const char *name)
795 {
796 xfree(p->ifname);
797 p->ifname = xstrdup(name);
798 if (p->spec.tops->setifname)
799 p->spec.tops->setifname(p->t, name);
800 }
801
802 /* --- @p_addr@ --- *
803 *
804 * Arguments: @peer *p@ = pointer to a peer block
805 *
806 * Returns: A pointer to the peer's address.
807 */
808
809 const addr *p_addr(peer *p) { return (&p->spec.sa); }
810
811 /* --- @p_bind@ --- *
812 *
813 * Arguments: @struct addrinfo *ailist@ = addresses to bind to
814 *
815 * Returns: Zero on success, @-1@ on failure.
816 *
817 * Use: Binds to the main UDP sockets.
818 */
819
820 int p_bind(struct addrinfo *ailist)
821 {
822 int fd = -1;
823 int len = PKBUFSZ;
824 int yes = 1;
825 int i;
826 struct addrinfo *ai;
827 unsigned port, lastport = 0;
828 addr a;
829 socklen_t sz;
830
831 for (i = 0; i < NADDRFAM; i++) udpsock[i].sf.fd = -1;
832
833 for (ai = ailist; ai; ai = ai->ai_next) {
834 if ((i = afix(ai->ai_family)) < 0) continue;
835 if (udpsock[i].sf.fd != -1) continue;
836
837 /* --- Note on socket buffer sizes --- *
838 *
839 * For some bizarre reason, Linux 2.2 (at least) doubles the socket
840 * buffer sizes I pass to @setsockopt@. I'm not putting special-case
841 * code here for Linux: BSD (at least TCPv2) does what I tell it rather
842 * than second-guessing me.
843 */
844
845 if ((fd = socket(ai->ai_family, SOCK_DGRAM, 0)) < 0) {
846 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
847 "create-failed", "?ERRNO", A_END);
848 goto fail;
849 }
850 if (i == AFIX_INET6 &&
851 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes))) {
852 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
853 "set-v6only-failed", "?ERRNO", A_END);
854 goto fail;
855 }
856 assert(ai->ai_addrlen <= sizeof(a));
857 memcpy(&a, ai->ai_addr, ai->ai_addrlen);
858 if ((port = getport(&a)) == 0 && lastport) setport(&a, lastport);
859 if (bind(fd, &a.sa, addrsz(&a))) {
860 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
861 "bind-failed", "?ERRNO", A_END);
862 goto fail;
863 }
864 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)) ||
865 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &len, sizeof(len))) {
866 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
867 "set-buffers-failed", "?ERRNO", A_END);
868 goto fail;
869 }
870 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
871 if (port)
872 udpsock[i].port = port;
873 else {
874 sz = sizeof(a);
875 if (getsockname(fd, &a.sa, &sz)) {
876 a_warn("PEER", "-", "udp-socket", "%s", aftab[i].name,
877 "read-local-address-failed", "?ERRNO", A_END);
878 goto fail;
879 }
880 udpsock[i].port = lastport = getport(&a);
881 }
882 T( trace(T_PEER, "peer: created %s socket", aftab[i].name); )
883 sel_initfile(&sel, &udpsock[i].sf, fd, SEL_READ, p_read, 0);
884 sel_addfile(&udpsock[i].sf);
885 fd = -1;
886 }
887
888 return (0);
889
890 fail:
891 if (fd != -1) close(fd);
892 p_unbind();
893 return (-1);
894 }
895
896 /* --- @p_unbind@ --- *
897 *
898 * Arguments: ---
899 *
900 * Returns: ---
901 *
902 * Use: Unbinds the UDP sockets. There must not be any active peers,
903 * and none can be created until the sockets are rebound.
904 */
905
906 void p_unbind(void)
907 {
908 int i;
909
910 #ifndef NDEBUG
911 { peer_iter it; p_mkiter(&it); assert(!p_next(&it)); }
912 #endif
913
914 for (i = 0; i < NADDRFAM; i++) {
915 if (udpsock[i].sf.fd == -1) continue;
916 sel_rmfile(&udpsock[i].sf);
917 close(udpsock[i].sf.fd);
918 udpsock[i].sf.fd = -1;
919 }
920 }
921
922 /* --- @p_init@ --- *
923 *
924 * Arguments: ---
925 *
926 * Returns: ---
927 *
928 * Use: Initializes the peer system.
929 */
930
931 void p_init(void)
932 {
933 sym_create(&byname);
934 am_create(&byaddr);
935 }
936
937 /* --- @p_addtun@ --- *
938 *
939 * Arguments: @const tunnel_ops *tops@ = tunnel ops to add
940 *
941 * Returns: Zero on success, @-1@ on failure.
942 *
943 * Use: Adds a tunnel class to the list of known classes, if it
944 * initializes properly. If there is no current default tunnel,
945 * then this one is made the default.
946 *
947 * Does nothing if the tunnel class is already known. So adding
948 * a bunch of tunnels takes quadratic time, but there will be
949 * too few to care about.
950 */
951
952 int p_addtun(const tunnel_ops *tops)
953 {
954 struct tunnel_node *tn;
955
956 for (tn = tunnels; tn; tn = tn->next)
957 if (tn->tops == tops) return (0);
958 if (tops->init()) return (-1);
959 tn = CREATE(struct tunnel_node);
960 tn->next = 0; tn->tops = tops;
961 *tunnels_tail = tn; tunnels_tail = &tn->next;
962 if (!dflttun) dflttun = tops;
963 return (0);
964 }
965
966 /* --- @p_setdflttun@ --- *
967 *
968 * Arguments: @const tunnel_ops *tops@ = tunnel ops to set
969 *
970 * Returns: ---
971 *
972 * Use: Sets the default tunnel. It must already be registered. The
973 * old default is forgotten.
974 */
975
976 void p_setdflttun(const tunnel_ops *tops)
977 { dflttun = tops; }
978
979 /* --- @p_dflttun@ --- *
980 *
981 * Arguments: ---
982 *
983 * Returns: A pointer to the current default tunnel operations, or null
984 * if no tunnels are defined.
985 */
986
987 const tunnel_ops *p_dflttun(void) { return (dflttun); }
988
989 /* --- @p_findtun@ --- *
990 *
991 * Arguments: @const char *name@ = tunnel name
992 *
993 * Returns: Pointer to the tunnel operations, or null.
994 *
995 * Use: Finds the operations for a named tunnel class.
996 */
997
998 const tunnel_ops *p_findtun(const char *name)
999 {
1000 const struct tunnel_node *tn;
1001
1002 for (tn = tunnels; tn; tn = tn->next)
1003 if (mystrieq(tn->tops->name, name) == 0) return (tn->tops);
1004 return (0);
1005 }
1006
1007 /* --- @p_mktuniter@ --- *
1008 *
1009 * Arguments: @tuniter *i@ = pointer to iterator to initialize
1010 *
1011 * Returns: ---
1012 *
1013 * Use: Initializes a tunnel iterator.
1014 */
1015
1016 void p_mktuniter(tun_iter *i) { i->next = tunnels; }
1017
1018 /* --- @p_nexttun@ --- *
1019 *
1020 * Arguments: @tuniter *i@ = pointer to iterator
1021 *
1022 * Returns: Pointer to the next tunnel's operations, or null.
1023 */
1024
1025 const tunnel_ops *p_nexttun(tun_iter *i)
1026 {
1027 const struct tunnel_node *tn = i->next;
1028
1029 if (!tn) return (0);
1030 else { i->next = tn->next; return (tn->tops); }
1031 }
1032
1033 /* --- @p_keepalive@ --- *
1034 *
1035 * Arguments: @struct timeval *now@ = the current time
1036 * @void *pv@ = peer to wake up
1037 *
1038 * Returns: ---
1039 *
1040 * Use: Sends a keepalive ping message to its peer.
1041 */
1042
1043 static void p_keepalive(struct timeval *now, void *pv)
1044 {
1045 peer *p = pv;
1046
1047 p_txstart(p, MSG_MISC | MISC_NOP); p_dotxend(p);
1048 T( trace(T_PEER, "peer: sent keepalive to %s", p->spec.name); )
1049 p_setkatimer(p);
1050 }
1051
1052 /* --- @p_setkatimer@ --- *
1053 *
1054 * Arguments: @peer *p@ = peer to set
1055 *
1056 * Returns: ---
1057 *
1058 * Use: Resets the keepalive timer thing.
1059 */
1060
1061 static void p_setkatimer(peer *p)
1062 {
1063 struct timeval tv;
1064
1065 if (!p->spec.t_ka)
1066 return;
1067 gettimeofday(&tv, 0);
1068 tv.tv_sec += p->spec.t_ka;
1069 sel_addtimer(&sel, &p->tka, &tv, p_keepalive, p);
1070 }
1071
1072 /* --- @p_create@ --- *
1073 *
1074 * Arguments: @peerspec *spec@ = information about this peer
1075 *
1076 * Returns: Pointer to the peer block, or null if it failed.
1077 *
1078 * Use: Creates a new named peer block. No peer is actually attached
1079 * by this point.
1080 */
1081
1082 peer *p_create(peerspec *spec)
1083 {
1084 peer *p = CREATE(peer);
1085 const tunnel_ops *tops = spec->tops;
1086 int fd;
1087 unsigned f;
1088
1089 p->byname = sym_find(&byname, spec->name, -1, sizeof(peer_byname), &f);
1090 if (f) goto tidy_0;
1091 p->byaddr = am_find(&byaddr, &spec->sa, sizeof(peer_byaddr), &f);
1092 if (f) goto tidy_1;
1093 p->byname->p = p->byaddr->p = p;
1094
1095 T( trace(T_PEER, "peer: creating new peer `%s'", spec->name); )
1096 p->spec = *spec;
1097 p->spec.name = (/*unconst*/ char *)SYM_NAME(p->byname);
1098 if (spec->tag) p->spec.tag = xstrdup(spec->tag);
1099 if (spec->privtag) p->spec.privtag = xstrdup(spec->privtag);
1100 if (spec->knock) p->spec.knock = xstrdup(spec->knock);
1101 p->ks = 0;
1102 p->pings = 0;
1103 p->ifname = 0;
1104 p->afix = afix(p->spec.sa.sa.sa_family); assert(p->afix >= 0);
1105 memset(&p->st, 0, sizeof(stats));
1106 p->st.t_start = time(0);
1107 if (!(tops->flags & TUNF_PRIVOPEN))
1108 fd = -1;
1109 else if ((fd = ps_tunfd(tops, &p->ifname)) < 0)
1110 goto tidy_2;
1111 if ((p->t = tops->create(p, fd, &p->ifname)) == 0)
1112 goto tidy_3;
1113 T( trace(T_TUNNEL, "peer: attached interface %s to peer `%s'",
1114 p->ifname, p_name(p)); )
1115 p_setkatimer(p);
1116 iv_addreason();
1117 if (kx_setup(&p->kx, p, &p->ks, p->spec.f & PSF_KXMASK))
1118 goto tidy_4;
1119 a_notify("ADD",
1120 "?PEER", p,
1121 "%s", p->ifname,
1122 "?ADDR", &p->spec.sa,
1123 A_END);
1124 if (!(p->spec.f & KXF_CORK)) {
1125 a_notify("KXSTART", "?PEER", p, A_END);
1126 /* Couldn't tell anyone before */
1127 }
1128 if (p->spec.f & PSF_MOBILE) nmobile++;
1129 return (p);
1130
1131 tidy_4:
1132 if (spec->t_ka) sel_rmtimer(&p->tka);
1133 xfree(p->ifname);
1134 p->t->ops->destroy(p->t);
1135 iv_rmreason();
1136 tidy_3:
1137 if (fd >= 0) close(fd);
1138 tidy_2:
1139 am_remove(&byaddr, p->byaddr);
1140 if (p->spec.tag) xfree(p->spec.tag);
1141 if (p->spec.privtag) xfree(p->spec.privtag);
1142 tidy_1:
1143 sym_remove(&byname, p->byname);
1144 tidy_0:
1145 DESTROY(p);
1146 return (0);
1147 }
1148
1149 /* --- @p_name@ --- *
1150 *
1151 * Arguments: @peer *p@ = pointer to a peer block
1152 *
1153 * Returns: A pointer to the peer's name.
1154 */
1155
1156 const char *p_name(peer *p)
1157 { if (p) return (p->spec.name); else return ("-"); }
1158
1159 /* --- @p_tag@ --- *
1160 *
1161 * Arguments: @peer *p@ = pointer to a peer block
1162 *
1163 * Returns: A pointer to the peer's public key tag.
1164 */
1165
1166 const char *p_tag(peer *p)
1167 { return (p->spec.tag ? p->spec.tag : p->spec.name); }
1168
1169 /* --- @p_privtag@ --- *
1170 *
1171 * Arguments: @peer *p@ = pointer to a peer block
1172 *
1173 * Returns: A pointer to the peer's private key tag.
1174 */
1175
1176 const char *p_privtag(peer *p)
1177 { return (p->spec.privtag ? p->spec.privtag : tag_priv); }
1178
1179 /* --- @p_spec@ --- *
1180 *
1181 * Arguments: @peer *p@ = pointer to a peer block
1182 *
1183 * Returns: Pointer to the peer's specification
1184 */
1185
1186 const peerspec *p_spec(peer *p) { return (&p->spec); }
1187
1188 /* --- @p_findbyaddr@ --- *
1189 *
1190 * Arguments: @const addr *a@ = address to look up
1191 *
1192 * Returns: Pointer to the peer block, or null if not found.
1193 *
1194 * Use: Finds a peer by address.
1195 */
1196
1197 peer *p_findbyaddr(const addr *a)
1198 {
1199 peer_byaddr *pa;
1200
1201 if ((pa = am_find(&byaddr, a, 0, 0)) != 0) {
1202 assert(pa->p);
1203 return (pa->p);
1204 }
1205 return (0);
1206 }
1207
1208 /* --- @p_find@ --- *
1209 *
1210 * Arguments: @const char *name@ = name to look up
1211 *
1212 * Returns: Pointer to the peer block, or null if not found.
1213 *
1214 * Use: Finds a peer by name.
1215 */
1216
1217 peer *p_find(const char *name)
1218 {
1219 peer_byname *pn;
1220
1221 if ((pn = sym_find(&byname, name, -1, 0, 0)) != 0)
1222 return (pn->p);
1223 return (0);
1224 }
1225
1226 /* --- @p_destroy@ --- *
1227 *
1228 * Arguments: @peer *p@ = pointer to a peer
1229 * @int bye@ = say goodbye to the peer?
1230 *
1231 * Returns: ---
1232 *
1233 * Use: Destroys a peer.
1234 */
1235
1236 void p_destroy(peer *p, int bye)
1237 {
1238 ping *pg, *ppg;
1239 buf *b, bb;
1240
1241 T( trace(T_PEER, "peer: destroying peer `%s'", p->spec.name); )
1242
1243 if (bye) {
1244 b = p_txstart(p, MSG_MISC | MISC_BYE);
1245 buf_init(&bb, buf_t, sizeof(buf_t));
1246 assert(BOK(&bb)); buf_flip(&bb);
1247 p_encrypt(p, MSG_MISC | MISC_BYE, &bb, b);
1248 p_txend(p, 0);
1249 }
1250
1251 a_notify("KILL", "%s", p->spec.name, A_END);
1252 ksl_free(&p->ks);
1253 kx_free(&p->kx);
1254 if (p->spec.f & PSF_MOBILE) nmobile--;
1255 if (p->ifname) xfree(p->ifname);
1256 if (p->spec.tag) xfree(p->spec.tag);
1257 if (p->spec.privtag) xfree(p->spec.privtag);
1258 if (p->spec.knock) xfree(p->spec.knock);
1259 p->t->ops->destroy(p->t);
1260 if (p->spec.t_ka) sel_rmtimer(&p->tka);
1261 for (pg = p->pings; pg; pg = ppg) {
1262 ppg = pg->next;
1263 p_pingdone(pg, PING_PEERDIED);
1264 }
1265 sym_remove(&byname, p->byname);
1266 am_remove(&byaddr, p->byaddr);
1267 iv_rmreason();
1268 DESTROY(p);
1269 }
1270
1271 /* --- @p_destroyall@ --- *
1272 *
1273 * Arguments: ---
1274 *
1275 * Returns: ---
1276 *
1277 * Use: Destroys all of the peers, saying goodbye.
1278 */
1279
1280 void p_destroyall(void) { FOREACH_PEER(p, { p_destroy(p, 1); }); }
1281
1282 /* --- @p_mkiter@ --- *
1283 *
1284 * Arguments: @peer_iter *i@ = pointer to an iterator
1285 *
1286 * Returns: ---
1287 *
1288 * Use: Initializes the iterator.
1289 */
1290
1291 void p_mkiter(peer_iter *i) { sym_mkiter(&i->i, &byname); }
1292
1293 /* --- @p_next@ --- *
1294 *
1295 * Arguments: @peer_iter *i@ = pointer to an iterator
1296 *
1297 * Returns: Next peer, or null if at the end.
1298 *
1299 * Use: Returns the next peer.
1300 */
1301
1302 peer *p_next(peer_iter *i)
1303 {
1304 peer_byname *pn;
1305
1306 if ((pn = sym_next(&i->i)) == 0)
1307 return (0);
1308 return (pn->p);
1309 }
1310
1311 /*----- That's all, folks -------------------------------------------------*/