|
| 1 | +import { NotStartedError, start, stop } from '@libp2p/interface' |
| 2 | +import { repeatingTask } from '@libp2p/utils/repeating-task' |
| 3 | +import { multiaddr } from '@multiformats/multiaddr' |
| 4 | +import pDefer from 'p-defer' |
| 5 | +import { raceSignal } from 'race-signal' |
| 6 | +import type { NatAPI } from '@achingbrain/nat-port-mapper' |
| 7 | +import type { AbortOptions, ComponentLogger, Logger, Startable } from '@libp2p/interface' |
| 8 | +import type { AddressManager } from '@libp2p/interface-internal' |
| 9 | +import type { RepeatingTask } from '@libp2p/utils/repeating-task' |
| 10 | +import type { DeferredPromise } from 'p-defer' |
| 11 | + |
| 12 | +export interface ExternalAddressCheckerComponents { |
| 13 | + client: NatAPI |
| 14 | + addressManager: AddressManager |
| 15 | + logger: ComponentLogger |
| 16 | +} |
| 17 | + |
| 18 | +export interface ExternalAddressCheckerInit { |
| 19 | + interval?: number |
| 20 | + timeout?: number |
| 21 | + autoConfirmAddress?: boolean |
| 22 | +} |
| 23 | + |
| 24 | +export interface ExternalAddress { |
| 25 | + getPublicIp (options?: AbortOptions): Promise<string> | string |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * Monitors the external network address and notifies when/if it changes |
| 30 | + */ |
| 31 | +class ExternalAddressChecker implements ExternalAddress, Startable { |
| 32 | + private readonly log: Logger |
| 33 | + private readonly client: NatAPI |
| 34 | + private readonly addressManager: AddressManager |
| 35 | + private started: boolean |
| 36 | + private lastPublicIp?: string |
| 37 | + private readonly lastPublicIpPromise: DeferredPromise<string> |
| 38 | + private readonly check: RepeatingTask |
| 39 | + private readonly autoConfirmAddress: boolean |
| 40 | + |
| 41 | + constructor (components: ExternalAddressCheckerComponents, init: ExternalAddressCheckerInit = {}) { |
| 42 | + this.log = components.logger.forComponent('libp2p:upnp-nat:external-address-check') |
| 43 | + this.client = components.client |
| 44 | + this.addressManager = components.addressManager |
| 45 | + this.autoConfirmAddress = init.autoConfirmAddress ?? false |
| 46 | + this.started = false |
| 47 | + |
| 48 | + this.checkExternalAddress = this.checkExternalAddress.bind(this) |
| 49 | + |
| 50 | + this.lastPublicIpPromise = pDefer() |
| 51 | + |
| 52 | + this.check = repeatingTask(this.checkExternalAddress, init.interval ?? 30000, { |
| 53 | + timeout: init.timeout ?? 10000, |
| 54 | + runImmediately: true |
| 55 | + }) |
| 56 | + } |
| 57 | + |
| 58 | + async start (): Promise<void> { |
| 59 | + if (this.started) { |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + await start(this.check) |
| 64 | + |
| 65 | + this.check.start() |
| 66 | + this.started = true |
| 67 | + } |
| 68 | + |
| 69 | + async stop (): Promise<void> { |
| 70 | + await stop(this.check) |
| 71 | + |
| 72 | + this.started = false |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * Return the last public IP address we found, or wait for it to be found |
| 77 | + */ |
| 78 | + async getPublicIp (options?: AbortOptions): Promise<string> { |
| 79 | + if (!this.started) { |
| 80 | + throw new NotStartedError('Not started yet') |
| 81 | + } |
| 82 | + |
| 83 | + return this.lastPublicIp ?? raceSignal(this.lastPublicIpPromise.promise, options?.signal, { |
| 84 | + errorMessage: 'Requesting the public IP from the network gateway timed out - UPnP may not be enabled' |
| 85 | + }) |
| 86 | + } |
| 87 | + |
| 88 | + private async checkExternalAddress (options?: AbortOptions): Promise<void> { |
| 89 | + try { |
| 90 | + const externalAddress = await this.client.externalIp(options) |
| 91 | + |
| 92 | + // check if our public address has changed |
| 93 | + if (this.lastPublicIp != null && externalAddress !== this.lastPublicIp) { |
| 94 | + this.log('external address changed from %s to %s', this.lastPublicIp, externalAddress) |
| 95 | + |
| 96 | + for (const ma of this.addressManager.getAddresses()) { |
| 97 | + const addrString = ma.toString() |
| 98 | + |
| 99 | + if (!addrString.includes(this.lastPublicIp)) { |
| 100 | + continue |
| 101 | + } |
| 102 | + |
| 103 | + // create a new version of the multiaddr with the new public IP |
| 104 | + const newAddress = multiaddr(addrString.replace(this.lastPublicIp, externalAddress)) |
| 105 | + |
| 106 | + // remove the old address and add the new one |
| 107 | + this.addressManager.removeObservedAddr(ma) |
| 108 | + this.addressManager.confirmObservedAddr(newAddress) |
| 109 | + |
| 110 | + if (this.autoConfirmAddress) { |
| 111 | + this.addressManager.confirmObservedAddr(newAddress) |
| 112 | + } else { |
| 113 | + this.addressManager.addObservedAddr(newAddress) |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + this.lastPublicIp = externalAddress |
| 119 | + this.lastPublicIpPromise.resolve(externalAddress) |
| 120 | + } catch (err: any) { |
| 121 | + if (this.lastPublicIp != null) { |
| 122 | + // ignore the error if we've previously run successfully |
| 123 | + return |
| 124 | + } |
| 125 | + |
| 126 | + this.lastPublicIpPromise.reject(err) |
| 127 | + } |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +export function dynamicExternalAddress (components: ExternalAddressCheckerComponents, init: ExternalAddressCheckerInit = {}): ExternalAddress { |
| 132 | + return new ExternalAddressChecker(components, init) |
| 133 | +} |
| 134 | + |
| 135 | +export function staticExternalAddress (address: string): ExternalAddress { |
| 136 | + return { |
| 137 | + getPublicIp: () => address |
| 138 | + } |
| 139 | +} |
0 commit comments