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