]> Sergey Matveev's repositories - tofuproxy.git/blob - netrc.go
Statically linked *zstd
[tofuproxy.git] / netrc.go
1 // Nearly all code is taken from src/cmd/go/internal/auth/netrc.go
2
3 package tofuproxy
4
5 import (
6         "io/ioutil"
7         "log"
8         "os"
9         "path/filepath"
10         "strings"
11 )
12
13 func findInNetrc(host string) (string, string) {
14         netrcPath, ok := os.LookupEnv("NETRC")
15         if !ok {
16                 homeDir, err := os.UserHomeDir()
17                 if err != nil {
18                         log.Fatalln(err)
19                 }
20                 netrcPath = filepath.Join(homeDir, ".netrc")
21         }
22         data, err := ioutil.ReadFile(netrcPath)
23         if err != nil {
24                 if os.IsNotExist(err) {
25                         return "", ""
26                 }
27                 log.Fatalln(err)
28         }
29         inMacro := false
30         var machine, login, password string
31         for _, line := range strings.Split(string(data), "\n") {
32                 if inMacro {
33                         if line == "" {
34                                 inMacro = false
35                         }
36                         continue
37                 }
38                 fields := strings.Fields(line)
39                 i := 0
40                 for ; i < len(fields)-1; i += 2 {
41                         switch fields[i] {
42                         case "machine":
43                                 machine = fields[i+1]
44                                 login = ""
45                                 password = ""
46                         case "default":
47                                 break
48                         case "login":
49                                 login = fields[i+1]
50                         case "password":
51                                 password = fields[i+1]
52                         case "macdef":
53                                 inMacro = true
54                         }
55                         if machine != "" && login != "" && password != "" {
56                                 if machine == host {
57                                         return login, password
58                                 }
59                                 machine, login, password = "", "", ""
60                         }
61                 }
62                 if i < len(fields) && fields[i] == "default" {
63                         break
64                 }
65         }
66         return "", ""
67 }