1#!/bin/bash
2# Copyright 2021 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16source "$(dirname "${BASH_SOURCE[0]}")"/ncsid_lib.sh
17
18NCSI_IF="$1"
19
20old_rtr=
21old_mac=
22
23set_rtr() {
24  [ -n "$rtr" -a -n "$lifetime" ] || return
25  [ "$rtr" != "$old_rtr" -a "$mac" != "$old_mac" ] || return
26  # Only valid default routers can be considered, 0 lifetime implies
27  # a non-default router
28  (( lifetime > 0 )) || return
29
30  echo "Setting default router: $rtr at $mac" >&2
31  local svc=xyz.openbmc_project.Network
32  SetStatic "$svc" "$NCSI_IF" || return
33  UpdateGateway "$svc" "$NCSI_IF" "$rtr" || return
34  UpdateNeighbor "$svc" "$NCSI_IF" "$rtr" "$mac" || return
35
36  retries=-1
37  old_mac="$mac"
38  old_rtr="$rtr"
39}
40
41retries=1
42w=60
43while true; do
44  start=$SECONDS
45  args=(-m "$NCSI_IF" -w $(( w * 1000 )))
46  if (( retries > 0 )); then
47    args+=(-r "$retries")
48  else
49    args+=(-d)
50  fi
51  while read line; do
52    if [ -z "$line" ]; then
53      lifetime=
54      mac=
55    elif [[ "$line" =~ ^Router' 'lifetime' '*:' '*([0-9]*) ]]; then
56      lifetime="${BASH_REMATCH[1]}"
57    elif [[ "$line" =~ ^Source' 'link-layer' 'address' '*:' '*([a-fA-F0-9:]*)$ ]]; then
58      mac="${BASH_REMATCH[1]}"
59    elif [[ "$line" =~ ^from' '(.*)$ ]]; then
60      rtr="${BASH_REMATCH[1]}"
61      set_rtr || true
62      lifetime=
63      mac=
64      rtr=
65    fi
66  done < <(exec rdisc6 "${args[@]}" 2>/dev/null)
67  # If rdisc6 exits early we still want to wait the full `w` time before
68  # starting again.
69  (( timeout = start + w - SECONDS ))
70  sleep $(( timeout < 0 ? 0 : timeout ))
71done
72