InitializeWithPeers sets up the WireGuard interface with initial configuration and optional full peer snapshot.
(privateKey wgtypes.Key, listenPort int, serverIPs []string, peers []wgtypes.PeerConfig)
| 126 | |
| 127 | // InitializeWithPeers sets up the WireGuard interface with initial configuration and optional full peer snapshot. |
| 128 | func (m *Manager) InitializeWithPeers(privateKey wgtypes.Key, listenPort int, serverIPs []string, peers []wgtypes.PeerConfig) error { |
| 129 | m.mu.Lock() |
| 130 | defer m.mu.Unlock() |
| 131 | |
| 132 | if m.client == nil { |
| 133 | return fmt.Errorf("wgctrl client is not initialized") |
| 134 | } |
| 135 | |
| 136 | nl := m.getNetlinkOps() |
| 137 | configure := m.getConfigureDevice() |
| 138 | |
| 139 | var parsedAddrs []*netlink.Addr |
| 140 | for _, ipStr := range serverIPs { |
| 141 | addr, err := nl.ParseAddr(ipStr) |
| 142 | if err != nil { |
| 143 | return fmt.Errorf("failed to parse address %s: %w", ipStr, err) |
| 144 | } |
| 145 | parsedAddrs = append(parsedAddrs, addr) |
| 146 | } |
| 147 | |
| 148 | // Clean up any existing interface |
| 149 | if err := m.cleanupExistingInterface(); err != nil { |
| 150 | return fmt.Errorf("failed to cleanup existing interface: %w", err) |
| 151 | } |
| 152 | |
| 153 | // Create WireGuard interface |
| 154 | link := &netlink.Wireguard{LinkAttrs: netlink.LinkAttrs{Name: m.iFaceName}} |
| 155 | if err := nl.LinkAdd(link); err != nil { |
| 156 | return fmt.Errorf("failed to add link: %w", wrapPermissionDeniedError("creating wireguard interface", err)) |
| 157 | } |
| 158 | cleanupOnError := true |
| 159 | defer func() { |
| 160 | if cleanupOnError { |
| 161 | _ = m.cleanupExistingInterface() |
| 162 | } |
| 163 | }() |
| 164 | |
| 165 | // Configure WireGuard (single call for base settings + optional peers snapshot). |
| 166 | config := buildInitialWGConfig(privateKey, listenPort, peers) |
| 167 | |
| 168 | if err := configure(m.client, m.iFaceName, config); err != nil { |
| 169 | return fmt.Errorf("failed to configure device: %w", wrapPermissionDeniedError("configuring wireguard device", err)) |
| 170 | } |
| 171 | |
| 172 | link2, err := nl.LinkByName(m.iFaceName) |
| 173 | if err != nil { |
| 174 | return fmt.Errorf("failed to get link: %w", err) |
| 175 | } |
| 176 | |
| 177 | for _, addr := range parsedAddrs { |
| 178 | if err := nl.AddrAdd(link2, addr); err != nil { |
| 179 | return fmt.Errorf( |
| 180 | "failed to add address %s: %w", |
| 181 | addr.IPNet.String(), |
| 182 | wrapPermissionDeniedError("assigning wireguard interface address", err), |
| 183 | ) |
| 184 | } |
| 185 | } |