| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package legacy |
| 16 |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "fmt" |
| 20 | "os" |
| 21 | "path/filepath" |
| 22 | ) |
| 23 |
| 24 | func ParseClientConfig(filePath string) ( |
| 25 | cfg ClientCommonConf, |
| 26 | proxyCfgs map[string]ProxyConf, |
| 27 | visitorCfgs map[string]VisitorConf, |
| 28 | err error, |
| 29 | ) { |
| 30 | var content []byte |
| 31 | content, err = GetRenderedConfFromFile(filePath) |
| 32 | if err != nil { |
| 33 | return |
| 34 | } |
| 35 | configBuffer := bytes.NewBuffer(nil) |
| 36 | configBuffer.Write(content) |
| 37 |
| 38 | // Parse common section. |
| 39 | cfg, err = UnmarshalClientConfFromIni(content) |
| 40 | if err != nil { |
| 41 | return |
| 42 | } |
| 43 | if err = cfg.Validate(); err != nil { |
| 44 | err = fmt.Errorf("parse config error: %v", err) |
| 45 | return |
| 46 | } |
| 47 |
| 48 | // Aggregate proxy configs from include files. |
| 49 | var buf []byte |
| 50 | buf, err = getIncludeContents(cfg.IncludeConfigFiles) |
| 51 | if err != nil { |
| 52 | err = fmt.Errorf("getIncludeContents error: %v", err) |
| 53 | return |
| 54 | } |
| 55 | configBuffer.WriteString("\n") |
| 56 | configBuffer.Write(buf) |
| 57 |
| 58 | // Parse all proxy and visitor configs. |
| 59 | proxyCfgs, visitorCfgs, err = LoadAllProxyConfsFromIni(cfg.User, configBuffer.Bytes(), cfg.Start) |
| 60 | if err != nil { |
| 61 | return |
| 62 | } |
| 63 | return |
| 64 | } |
| 65 |
| 66 | // getIncludeContents renders all configs from paths. |
| 67 | // files format can be a single file path or directory or regex path. |
| 68 | func getIncludeContents(paths []string) ([]byte, error) { |
| 69 | out := bytes.NewBuffer(nil) |
| 70 | for _, path := range paths { |
| 71 | absDir, err := filepath.Abs(filepath.Dir(path)) |
| 72 | if err != nil { |
| 73 | return nil, err |
| 74 | } |
| 75 | if _, err := os.Stat(absDir); os.IsNotExist(err) { |
| 76 | return nil, err |
| 77 | } |
| 78 | files, err := os.ReadDir(absDir) |
| 79 | if err != nil { |
| 80 | return nil, err |
| 81 | } |
| 82 | for _, fi := range files { |
| 83 | if fi.IsDir() { |
| 84 | continue |
| 85 | } |
| 86 | absFile := filepath.Join(absDir, fi.Name()) |
| 87 | if matched, _ := filepath.Match(filepath.Join(absDir, filepath.Base(path)), absFile); matched { |
| 88 | tmpContent, err := GetRenderedConfFromFile(absFile) |
| 89 | if err != nil { |
| 90 | return nil, fmt.Errorf("render extra config %s error: %v", absFile, err) |
| 91 | } |
| 92 | out.Write(tmpContent) |
| 93 | out.WriteString("\n") |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | return out.Bytes(), nil |
| 98 | } |