1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (C) 2022 Felix Fietkau <nbd@nbd.name>
7 static const struct wg_ops
*wg_get_ops(struct network
*net
)
12 if (wg_user_ops
.check(net
))
22 int wg_init_network(struct network
*net
)
24 net
->wg
.ops
= wg_get_ops(net
);
29 return net
->wg
.ops
->init(net
);
32 void wg_cleanup_network(struct network
*net
)
35 net
->wg
.ops
->cleanup(net
);
39 wg_peer_set_connected(struct network
*net
, struct network_peer
*peer
, bool val
)
41 if (peer
->state
.connected
== val
)
44 peer
->state
.connected
= val
;
45 network_services_peer_update(net
, peer
);
48 struct network_peer
*wg_peer_update_start(struct network
*net
, const uint8_t *key
)
50 struct network_peer
*peer
;
52 peer
= vlist_find(&net
->peers
, key
, peer
, node
);
56 peer
->state
.handshake
= false;
58 if (peer
->state
.idle
>= 2 * net
->net_config
.keepalive
)
59 wg_peer_set_connected(net
, peer
, false);
60 if (peer
->state
.idle
> net
->net_config
.keepalive
)
61 network_pex_event(net
, peer
, PEX_EV_PING
);
66 void wg_peer_update_done(struct network
*net
, struct network_peer
*peer
)
68 if (peer
->state
.handshake
)
69 network_pex_event(net
, peer
, PEX_EV_HANDSHAKE
);
72 void wg_peer_set_last_handshake(struct network
*net
, struct network_peer
*peer
,
73 uint64_t now
, uint64_t sec
)
75 if (sec
== peer
->state
.last_handshake
)
78 peer
->state
.handshake
= true;
79 peer
->state
.last_handshake
= sec
;
81 if (sec
<= net
->net_config
.keepalive
) {
82 if (peer
->state
.idle
> sec
)
83 peer
->state
.idle
= sec
;
84 wg_peer_set_connected(net
, peer
, true);
88 void wg_peer_set_rx_bytes(struct network
*net
, struct network_peer
*peer
,
91 int64_t diff
= bytes
- peer
->state
.rx_bytes
;
93 peer
->state
.rx_bytes
= bytes
;
96 wg_peer_set_connected(net
, peer
, true);
100 void wg_peer_set_endpoint(struct network
*net
, struct network_peer
*peer
,
101 void *data
, size_t len
)
103 if (len
> sizeof(peer
->state
.endpoint
))
106 if (!memcmp(&peer
->state
.endpoint
, data
, len
))
109 memset(&peer
->state
.endpoint
, 0, sizeof(peer
->state
.endpoint
));
110 memcpy(&peer
->state
.endpoint
, data
, len
);
111 network_pex_event(net
, peer
, PEX_EV_ENDPOINT_CHANGE
);