| 1 | package ipfsfetcher |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net/url" |
| 9 | "os" |
| 10 | gopath "path" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | |
| 14 | "github.com/ipfs/boxo/files" |
| 15 | "github.com/ipfs/boxo/path" |
| 16 | "github.com/ipfs/kubo/config" |
| 17 | "github.com/ipfs/kubo/core" |
| 18 | "github.com/ipfs/kubo/core/coreapi" |
| 19 | iface "github.com/ipfs/kubo/core/coreiface" |
| 20 | "github.com/ipfs/kubo/core/coreiface/options" |
| 21 | "github.com/ipfs/kubo/core/node/libp2p" |
| 22 | "github.com/ipfs/kubo/repo/fsrepo" |
| 23 | "github.com/ipfs/kubo/repo/fsrepo/migrations" |
| 24 | peer "github.com/libp2p/go-libp2p/core/peer" |
| 25 | ) |
| 26 | |
| 27 | const ( |
| 28 | // Default maximum download size. |
| 29 | defaultFetchLimit = 1024 * 1024 * 512 |
| 30 | |
| 31 | tempNodeTCPAddr = "/ip4/127.0.0.1/tcp/0" |
| 32 | ) |
| 33 | |
| 34 | type IpfsFetcher struct { |
| 35 | distPath string |
| 36 | limit int64 |
| 37 | repoRoot *string |
| 38 | userConfigFile string |
| 39 | |
| 40 | openOnce sync.Once |
| 41 | openErr error |
| 42 | closeOnce sync.Once |
| 43 | closeErr error |
| 44 | |
| 45 | ipfs iface.CoreAPI |
| 46 | ipfsTmpDir string |
| 47 | ipfsStopFunc func() |
| 48 | |
| 49 | fetched []path.Path |
| 50 | mutex sync.Mutex |
| 51 | |
| 52 | addrInfo peer.AddrInfo |
| 53 | } |
| 54 | |
| 55 | var _ migrations.Fetcher = (*IpfsFetcher)(nil) |
| 56 | |
| 57 | // NewIpfsFetcher creates a new IpfsFetcher |
| 58 | // |
| 59 | // Specifying "" for distPath sets the default IPNS path. |
| 60 | // Specifying 0 for fetchLimit sets the default, -1 means no limit. |
| 61 | // |
| 62 | // Bootstrap and peer information in read from the IPFS config file in |
| 63 | // repoRoot, unless repoRoot is nil. If repoRoot is empty (""), then read the |
| 64 | // config from the default IPFS directory. |
| 65 | func NewIpfsFetcher(distPath string, fetchLimit int64, repoRoot *string, userConfigFile string) *IpfsFetcher { |
| 66 | f := &IpfsFetcher{ |
| 67 | limit: defaultFetchLimit, |
| 68 | distPath: migrations.LatestIpfsDist, |
| 69 | repoRoot: repoRoot, |
| 70 | userConfigFile: userConfigFile, |
| 71 | } |
| 72 | |
| 73 | if distPath != "" { |
| 74 | if !strings.HasPrefix(distPath, "/") { |
| 75 | distPath = "/" + distPath |
| 76 | } |
| 77 | f.distPath = distPath |
| 78 | } |
| 79 | |
| 80 | if fetchLimit != 0 { |
| 81 | if fetchLimit < 0 { |
| 82 | fetchLimit = 0 |
| 83 | } |
| 84 | f.limit = fetchLimit |
| 85 | } |
| 86 | |
| 87 | return f |
| 88 | } |
| 89 | |
| 90 | // Fetch attempts to fetch the file at the given path, from the distribution |
| 91 | // site configured for this HttpFetcher. |
| 92 | func (f *IpfsFetcher) Fetch(ctx context.Context, filePath string) ([]byte, error) { |
| 93 | // Initialize and start IPFS node on first call to Fetch, since the fetcher |
| 94 | // may be created by not used. |
| 95 | f.openOnce.Do(func() { |
| 96 | bootstrap, peers := readIpfsConfig(f.repoRoot, f.userConfigFile) |
| 97 | f.ipfsTmpDir, f.openErr = initTempNode(ctx, bootstrap, peers) |
| 98 | if f.openErr != nil { |
| 99 | return |
| 100 | } |
| 101 | |
| 102 | f.openErr = f.startTempNode(ctx) |
| 103 | }) |
| 104 | |
| 105 | fmt.Printf("Fetching with IPFS: %q\n", filePath) |
| 106 | |
| 107 | if f.openErr != nil { |
| 108 | return nil, f.openErr |
| 109 | } |
| 110 | |
| 111 | iPath, err := parsePath(gopath.Join(f.distPath, filePath)) |
| 112 | if err != nil { |
| 113 | return nil, err |
| 114 | } |
| 115 | |
| 116 | nd, err := f.ipfs.Unixfs().Get(ctx, iPath) |
| 117 | if err != nil { |
| 118 | return nil, err |
| 119 | } |
| 120 | |
| 121 | f.recordFetched(iPath) |
| 122 | |
| 123 | fileNode, ok := nd.(files.File) |
| 124 | if !ok { |
| 125 | return nil, fmt.Errorf("%q is not a file", filePath) |
| 126 | } |
| 127 | |
| 128 | var rc io.ReadCloser |
| 129 | if f.limit != 0 { |
| 130 | rc = migrations.NewLimitReadCloser(fileNode, f.limit) |
| 131 | } else { |
| 132 | rc = fileNode |
| 133 | } |
| 134 | defer rc.Close() |
| 135 | |
| 136 | return io.ReadAll(rc) |
| 137 | } |
| 138 | |
| 139 | func (f *IpfsFetcher) Close() error { |
| 140 | f.closeOnce.Do(func() { |
| 141 | if f.ipfsStopFunc != nil { |
| 142 | // Tell ipfs node to stop and wait for it to stop |
| 143 | f.ipfsStopFunc() |
| 144 | } |
| 145 | |
| 146 | if f.ipfsTmpDir != "" { |
| 147 | // Remove the temp ipfs dir |
| 148 | f.closeErr = os.RemoveAll(f.ipfsTmpDir) |
| 149 | } |
| 150 | }) |
| 151 | return f.closeErr |
| 152 | } |
| 153 | |
| 154 | func (f *IpfsFetcher) AddrInfo() peer.AddrInfo { |
| 155 | return f.addrInfo |
| 156 | } |
| 157 | |
| 158 | // FetchedPaths returns the IPFS paths of all items fetched by this fetcher. |
| 159 | func (f *IpfsFetcher) FetchedPaths() []path.Path { |
| 160 | f.mutex.Lock() |
| 161 | defer f.mutex.Unlock() |
| 162 | return f.fetched |
| 163 | } |
| 164 | |
| 165 | func (f *IpfsFetcher) recordFetched(fetchedPath path.Path) { |
| 166 | // Mutex protects against update by concurrent calls to Fetch |
| 167 | f.mutex.Lock() |
| 168 | defer f.mutex.Unlock() |
| 169 | f.fetched = append(f.fetched, fetchedPath) |
| 170 | } |
| 171 | |
| 172 | func initTempNode(ctx context.Context, bootstrap []string, peers []peer.AddrInfo) (string, error) { |
| 173 | identity, err := config.CreateIdentity(io.Discard, []options.KeyGenerateOption{ |
| 174 | options.Key.Type(options.Ed25519Key), |
| 175 | }) |
| 176 | if err != nil { |
| 177 | return "", err |
| 178 | } |
| 179 | cfg, err := config.InitWithIdentity(identity) |
| 180 | if err != nil { |
| 181 | return "", err |
| 182 | } |
| 183 | |
| 184 | // create temporary ipfs directory |
| 185 | dir, err := os.MkdirTemp("", "ipfs-temp") |
| 186 | if err != nil { |
| 187 | return "", fmt.Errorf("failed to get temp dir: %s", err) |
| 188 | } |
| 189 | |
| 190 | // configure the temporary node |
| 191 | cfg.Routing.Type = config.NewOptionalString("dhtclient") |
| 192 | |
| 193 | // Disable listening for inbound connections |
| 194 | cfg.Addresses.Gateway = []string{} |
| 195 | cfg.Addresses.API = []string{} |
| 196 | cfg.Addresses.Swarm = []string{tempNodeTCPAddr} |
| 197 | |
| 198 | if len(bootstrap) != 0 { |
| 199 | cfg.Bootstrap = bootstrap |
| 200 | } |
| 201 | |
| 202 | if len(peers) != 0 { |
| 203 | cfg.Peering.Peers = peers |
| 204 | } |
| 205 | |
| 206 | // Assumes that repo plugins are already loaded |
| 207 | err = fsrepo.Init(dir, cfg) |
| 208 | if err != nil { |
| 209 | os.RemoveAll(dir) |
| 210 | return "", fmt.Errorf("failed to initialize ephemeral node: %s", err) |
| 211 | } |
| 212 | |
| 213 | return dir, nil |
| 214 | } |
| 215 | |
| 216 | func (f *IpfsFetcher) startTempNode(ctx context.Context) error { |
| 217 | // Open the repo |
| 218 | r, err := fsrepo.Open(f.ipfsTmpDir) |
| 219 | if err != nil { |
| 220 | return err |
| 221 | } |
| 222 | |
| 223 | // Create a new lifetime context that is used to stop the temp ipfs node |
| 224 | ctxIpfsLife, cancel := context.WithCancel(context.Background()) |
| 225 | |
| 226 | // Construct the node |
| 227 | node, err := core.NewNode(ctxIpfsLife, &core.BuildCfg{ |
| 228 | Online: true, |
| 229 | Routing: libp2p.DHTClientOption, |
| 230 | Repo: r, |
| 231 | }) |
| 232 | if err != nil { |
| 233 | cancel() |
| 234 | r.Close() |
| 235 | return err |
| 236 | } |
| 237 | |
| 238 | ipfs, err := coreapi.NewCoreAPI(node) |
| 239 | if err != nil { |
| 240 | cancel() |
| 241 | return err |
| 242 | } |
| 243 | |
| 244 | stopFunc := func() { |
| 245 | // Tell ipfs to stop |
| 246 | cancel() |
| 247 | // Wait until ipfs is stopped |
| 248 | <-node.Context().Done() |
| 249 | } |
| 250 | |
| 251 | addrs, err := ipfs.Swarm().LocalAddrs(ctx) |
| 252 | if err != nil { |
| 253 | // Failure to get the local swarm address only means that the |
| 254 | // downloaded migrations cannot be fetched through the temporary node. |
| 255 | // So, print the error message and keep going. |
| 256 | fmt.Fprintln(os.Stderr, "cannot get local swarm address:", err) |
| 257 | } |
| 258 | |
| 259 | f.addrInfo = peer.AddrInfo{ |
| 260 | ID: node.Identity, |
| 261 | Addrs: addrs, |
| 262 | } |
| 263 | |
| 264 | f.ipfs = ipfs |
| 265 | f.ipfsStopFunc = stopFunc |
| 266 | |
| 267 | return nil |
| 268 | } |
| 269 | |
| 270 | func parsePath(fetchPath string) (path.Path, error) { |
| 271 | if ipfsPath, err := path.NewPath(fetchPath); err == nil { |
| 272 | return ipfsPath, nil |
| 273 | } |
| 274 | |
| 275 | u, err := url.Parse(fetchPath) |
| 276 | if err != nil { |
| 277 | return nil, fmt.Errorf("%q could not be parsed: %s", fetchPath, err) |
| 278 | } |
| 279 | |
| 280 | switch proto := u.Scheme; proto { |
| 281 | case "ipfs", "ipld", "ipns": |
| 282 | return path.NewPath(gopath.Join("/", proto, u.Host, u.Path)) |
| 283 | default: |
| 284 | return nil, fmt.Errorf("%q is not an IPFS path", fetchPath) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | func readIpfsConfig(repoRoot *string, userConfigFile string) (bootstrap []string, peers []peer.AddrInfo) { |
| 289 | if repoRoot == nil { |
| 290 | return |
| 291 | } |
| 292 | |
| 293 | cfgPath, err := config.Filename(*repoRoot, userConfigFile) |
| 294 | if err != nil { |
| 295 | fmt.Fprintln(os.Stderr, err) |
| 296 | return |
| 297 | } |
| 298 | |
| 299 | cfgFile, err := os.Open(cfgPath) |
| 300 | if err != nil { |
| 301 | fmt.Fprintln(os.Stderr, err) |
| 302 | return |
| 303 | } |
| 304 | defer cfgFile.Close() |
| 305 | |
| 306 | // Attempt to read bootstrap addresses |
| 307 | var bootstrapCfg struct { |
| 308 | Bootstrap []string |
| 309 | } |
| 310 | err = json.NewDecoder(cfgFile).Decode(&bootstrapCfg) |
| 311 | if err != nil { |
| 312 | fmt.Fprintln(os.Stderr, "cannot read bootstrap peers from config") |
| 313 | } else { |
| 314 | bootstrap = bootstrapCfg.Bootstrap |
| 315 | } |
| 316 | |
| 317 | if _, err = cfgFile.Seek(0, 0); err != nil { |
| 318 | // If Seek fails, only log the error and continue on to try to read the |
| 319 | // peering config anyway as it might still be readable |
| 320 | fmt.Fprintln(os.Stderr, err) |
| 321 | } |
| 322 | |
| 323 | // Attempt to read peers |
| 324 | var peeringCfg struct { |
| 325 | Peering config.Peering |
| 326 | } |
| 327 | err = json.NewDecoder(cfgFile).Decode(&peeringCfg) |
| 328 | if err != nil { |
| 329 | fmt.Fprintln(os.Stderr, "cannot read peering from config") |
| 330 | } else { |
| 331 | peers = peeringCfg.Peering.Peers |
| 332 | } |
| 333 | |
| 334 | return |
| 335 | } |