Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#pragma once
8
9#include <AK/IPv4Address.h>
10#include <Kernel/Library/NonnullLockRefPtr.h>
11#include <Kernel/Locking/MutexProtected.h>
12#include <Kernel/Net/NetworkAdapter.h>
13#include <Kernel/Thread.h>
14
15namespace Kernel {
16
17struct Route final : public AtomicRefCounted<Route> {
18 Route(IPv4Address const& destination, IPv4Address const& gateway, IPv4Address const& netmask, u16 flags, NonnullLockRefPtr<NetworkAdapter> adapter)
19 : destination(destination)
20 , gateway(gateway)
21 , netmask(netmask)
22 , flags(flags)
23 , adapter(adapter)
24 {
25 }
26
27 bool operator==(Route const& other) const
28 {
29 return destination == other.destination && netmask == other.netmask && flags == other.flags && adapter.ptr() == other.adapter.ptr();
30 }
31
32 bool matches(Route const& other) const
33 {
34 return destination == other.destination && (gateway == other.gateway || other.gateway.is_zero()) && netmask == other.netmask && flags == other.flags && adapter.ptr() == other.adapter.ptr();
35 }
36
37 const IPv4Address destination;
38 const IPv4Address gateway;
39 const IPv4Address netmask;
40 const u16 flags;
41 NonnullLockRefPtr<NetworkAdapter> adapter;
42
43 IntrusiveListNode<Route, LockRefPtr<Route>> route_list_node {};
44 using RouteList = IntrusiveList<&Route::route_list_node>;
45};
46
47struct RoutingDecision {
48 LockRefPtr<NetworkAdapter> adapter;
49 MACAddress next_hop;
50
51 bool is_zero() const;
52};
53
54enum class UpdateTable {
55 Set,
56 Delete,
57};
58
59void update_arp_table(IPv4Address const&, MACAddress const&, UpdateTable update);
60ErrorOr<void> update_routing_table(IPv4Address const& destination, IPv4Address const& gateway, IPv4Address const& netmask, u16 flags, LockRefPtr<NetworkAdapter> const adapter, UpdateTable update);
61
62enum class AllowUsingGateway {
63 Yes,
64 No,
65};
66
67RoutingDecision route_to(IPv4Address const& target, IPv4Address const& source, LockRefPtr<NetworkAdapter> const through = nullptr, AllowUsingGateway = AllowUsingGateway::Yes);
68
69SpinlockProtected<HashMap<IPv4Address, MACAddress>, LockRank::None>& arp_table();
70SpinlockProtected<Route::RouteList, LockRank::None>& routing_table();
71
72}