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