| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 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 caddycmd |
| 16 | |
| 17 | import ( |
| 18 | "encoding/json" |
| 19 | "fmt" |
| 20 | "io" |
| 21 | "net/http" |
| 22 | "net/url" |
| 23 | "os" |
| 24 | "os/exec" |
| 25 | "path/filepath" |
| 26 | "reflect" |
| 27 | "runtime" |
| 28 | "runtime/debug" |
| 29 | "strings" |
| 30 | |
| 31 | "go.uber.org/zap" |
| 32 | |
| 33 | "github.com/caddyserver/caddy/v2" |
| 34 | ) |
| 35 | |
| 36 | func cmdUpgrade(fl Flags) (int, error) { |
| 37 | _, nonstandard, _, err := getModules() |
| 38 | if err != nil { |
| 39 | return caddy.ExitCodeFailedStartup, fmt.Errorf("unable to enumerate installed plugins: %v", err) |
| 40 | } |
| 41 | pluginPkgs, err := getPluginPackages(nonstandard) |
| 42 | if err != nil { |
| 43 | return caddy.ExitCodeFailedStartup, err |
| 44 | } |
| 45 | |
| 46 | return upgradeBuild(pluginPkgs, fl) |
| 47 | } |
| 48 | |
| 49 | func splitModule(arg string) (module, version string, err error) { |
| 50 | const versionSplit = "@" |
| 51 | |
| 52 | // accommodate module paths that have @ in them, but we can only tolerate that if there's also |
| 53 | // a version, otherwise we don't know if it's a version separator or part of the file path |
| 54 | lastVersionSplit := strings.LastIndex(arg, versionSplit) |
| 55 | if lastVersionSplit < 0 { |
| 56 | module = arg |
| 57 | } else { |
| 58 | module, version = arg[:lastVersionSplit], arg[lastVersionSplit+1:] |
| 59 | } |
| 60 | |
| 61 | if module == "" { |
| 62 | err = fmt.Errorf("module name is required") |
| 63 | } |
| 64 | |
| 65 | return module, version, err |
| 66 | } |
| 67 | |
| 68 | func cmdAddPackage(fl Flags) (int, error) { |
| 69 | if len(fl.Args()) == 0 { |
| 70 | return caddy.ExitCodeFailedStartup, fmt.Errorf("at least one package name must be specified") |
| 71 | } |
| 72 | _, nonstandard, _, err := getModules() |
| 73 | if err != nil { |
| 74 | return caddy.ExitCodeFailedStartup, fmt.Errorf("unable to enumerate installed plugins: %v", err) |
| 75 | } |
| 76 | pluginPkgs, err := getPluginPackages(nonstandard) |
| 77 | if err != nil { |
| 78 | return caddy.ExitCodeFailedStartup, err |
| 79 | } |
| 80 | |
| 81 | for _, arg := range fl.Args() { |
| 82 | module, version, err := splitModule(arg) |
| 83 | if err != nil { |
| 84 | return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid module name: %v", err) |
| 85 | } |
| 86 | // only allow a version to be specified if it's different from the existing version |
| 87 | if _, ok := pluginPkgs[module]; ok && (version == "" || pluginPkgs[module].Version == version) { |
| 88 | return caddy.ExitCodeFailedStartup, fmt.Errorf("package is already added") |
| 89 | } |
| 90 | pluginPkgs[module] = pluginPackage{Version: version, Path: module} |
| 91 | } |
| 92 | |
| 93 | return upgradeBuild(pluginPkgs, fl) |
| 94 | } |
| 95 | |
| 96 | func cmdRemovePackage(fl Flags) (int, error) { |
| 97 | if len(fl.Args()) == 0 { |
| 98 | return caddy.ExitCodeFailedStartup, fmt.Errorf("at least one package name must be specified") |
| 99 | } |
| 100 | _, nonstandard, _, err := getModules() |
| 101 | if err != nil { |
| 102 | return caddy.ExitCodeFailedStartup, fmt.Errorf("unable to enumerate installed plugins: %v", err) |
| 103 | } |
| 104 | pluginPkgs, err := getPluginPackages(nonstandard) |
| 105 | if err != nil { |
| 106 | return caddy.ExitCodeFailedStartup, err |
| 107 | } |
| 108 | |
| 109 | for _, arg := range fl.Args() { |
| 110 | module, _, err := splitModule(arg) |
| 111 | if err != nil { |
| 112 | return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid module name: %v", err) |
| 113 | } |
| 114 | if _, ok := pluginPkgs[module]; !ok { |
| 115 | // package does not exist |
| 116 | return caddy.ExitCodeFailedStartup, fmt.Errorf("package is not added") |
| 117 | } |
| 118 | delete(pluginPkgs, arg) |
| 119 | } |
| 120 | |
| 121 | return upgradeBuild(pluginPkgs, fl) |
| 122 | } |
| 123 | |
| 124 | func upgradeBuild(pluginPkgs map[string]pluginPackage, fl Flags) (int, error) { |
| 125 | l := caddy.Log() |
| 126 | |
| 127 | thisExecPath, err := os.Executable() |
| 128 | if err != nil { |
| 129 | return caddy.ExitCodeFailedStartup, fmt.Errorf("determining current executable path: %v", err) |
| 130 | } |
| 131 | thisExecStat, err := os.Stat(thisExecPath) |
| 132 | if err != nil { |
| 133 | return caddy.ExitCodeFailedStartup, fmt.Errorf("retrieving current executable permission bits: %v", err) |
| 134 | } |
| 135 | if thisExecStat.Mode()&os.ModeSymlink == os.ModeSymlink { |
| 136 | symSource := thisExecPath |
| 137 | // we are a symlink; resolve it |
| 138 | thisExecPath, err = filepath.EvalSymlinks(thisExecPath) |
| 139 | if err != nil { |
| 140 | return caddy.ExitCodeFailedStartup, fmt.Errorf("resolving current executable symlink: %v", err) |
| 141 | } |
| 142 | l.Info("this executable is a symlink", zap.String("source", symSource), zap.String("target", thisExecPath)) |
| 143 | } |
| 144 | l.Info("this executable will be replaced", zap.String("path", thisExecPath)) |
| 145 | |
| 146 | // build the request URL to download this custom build |
| 147 | qs := url.Values{ |
| 148 | "os": {runtime.GOOS}, |
| 149 | "arch": {runtime.GOARCH}, |
| 150 | } |
| 151 | for _, pkgInfo := range pluginPkgs { |
| 152 | qs.Add("p", pkgInfo.String()) |
| 153 | } |
| 154 | |
| 155 | // initiate the build |
| 156 | resp, err := downloadBuild(qs) |
| 157 | if err != nil { |
| 158 | return caddy.ExitCodeFailedStartup, fmt.Errorf("download failed: %v", err) |
| 159 | } |
| 160 | defer resp.Body.Close() |
| 161 | |
| 162 | // back up the current binary, in case something goes wrong we can replace it |
| 163 | backupExecPath := thisExecPath + ".tmp" |
| 164 | l.Info("build acquired; backing up current executable", |
| 165 | zap.String("current_path", thisExecPath), |
| 166 | zap.String("backup_path", backupExecPath)) |
| 167 | err = os.Rename(thisExecPath, backupExecPath) |
| 168 | if err != nil { |
| 169 | return caddy.ExitCodeFailedStartup, fmt.Errorf("backing up current binary: %v", err) |
| 170 | } |
| 171 | defer func() { |
| 172 | if err != nil { |
| 173 | err2 := os.Rename(backupExecPath, thisExecPath) |
| 174 | if err2 != nil { |
| 175 | l.Error("restoring original executable failed; will need to be restored manually", |
| 176 | zap.String("backup_path", backupExecPath), |
| 177 | zap.String("original_path", thisExecPath), |
| 178 | zap.Error(err2)) |
| 179 | } |
| 180 | } |
| 181 | }() |
| 182 | |
| 183 | // download the file; do this in a closure to close reliably before we execute it |
| 184 | err = writeCaddyBinary(thisExecPath, &resp.Body, thisExecStat) |
| 185 | if err != nil { |
| 186 | return caddy.ExitCodeFailedStartup, err |
| 187 | } |
| 188 | |
| 189 | l.Info("download successful; displaying new binary details", zap.String("location", thisExecPath)) |
| 190 | |
| 191 | // use the new binary to print out version and module info |
| 192 | fmt.Print("\nModule versions:\n\n") |
| 193 | if err = listModules(thisExecPath); err != nil { |
| 194 | return caddy.ExitCodeFailedStartup, fmt.Errorf("download succeeded, but unable to execute 'caddy list-modules': %v", err) |
| 195 | } |
| 196 | fmt.Println("\nVersion:") |
| 197 | if err = showVersion(thisExecPath); err != nil { |
| 198 | return caddy.ExitCodeFailedStartup, fmt.Errorf("download succeeded, but unable to execute 'caddy version': %v", err) |
| 199 | } |
| 200 | fmt.Println() |
| 201 | |
| 202 | // clean up the backup file |
| 203 | if !fl.Bool("keep-backup") { |
| 204 | if err = removeCaddyBinary(backupExecPath); err != nil { |
| 205 | return caddy.ExitCodeFailedStartup, fmt.Errorf("download succeeded, but unable to clean up backup binary: %v", err) |
| 206 | } |
| 207 | } else { |
| 208 | l.Info("skipped cleaning up the backup file", zap.String("backup_path", backupExecPath)) |
| 209 | } |
| 210 | |
| 211 | l.Info("upgrade successful; please restart any running Caddy instances", zap.String("executable", thisExecPath)) |
| 212 | |
| 213 | return caddy.ExitCodeSuccess, nil |
| 214 | } |
| 215 | |
| 216 | func getModules() (standard, nonstandard, unknown []moduleInfo, err error) { |
| 217 | bi, ok := debug.ReadBuildInfo() |
| 218 | if !ok { |
| 219 | err = fmt.Errorf("no build info") |
| 220 | return standard, nonstandard, unknown, err |
| 221 | } |
| 222 | |
| 223 | for _, modID := range caddy.Modules() { |
| 224 | modInfo, err := caddy.GetModule(modID) |
| 225 | if err != nil { |
| 226 | // that's weird, shouldn't happen |
| 227 | unknown = append(unknown, moduleInfo{caddyModuleID: modID, err: err}) |
| 228 | continue |
| 229 | } |
| 230 | |
| 231 | // to get the Caddy plugin's version info, we need to know |
| 232 | // the package that the Caddy module's value comes from; we |
| 233 | // can use reflection but we need a non-pointer value (I'm |
| 234 | // not sure why), and since New() should return a pointer |
| 235 | // value, we need to dereference it first |
| 236 | iface := any(modInfo.New()) |
| 237 | if rv := reflect.ValueOf(iface); rv.Kind() == reflect.Pointer { |
| 238 | iface = reflect.New(reflect.TypeOf(iface).Elem()).Elem().Interface() |
| 239 | } |
| 240 | modPkgPath := reflect.TypeOf(iface).PkgPath() |
| 241 | |
| 242 | // now we find the Go module that the Caddy module's package |
| 243 | // belongs to; we assume the Caddy module package path will |
| 244 | // be prefixed by its Go module path, and we will choose the |
| 245 | // longest matching prefix in case there are nested modules |
| 246 | var matched *debug.Module |
| 247 | for _, dep := range bi.Deps { |
| 248 | if strings.HasPrefix(modPkgPath, dep.Path) { |
| 249 | if matched == nil || len(dep.Path) > len(matched.Path) { |
| 250 | matched = dep |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | caddyModGoMod := moduleInfo{caddyModuleID: modID, goModule: matched} |
| 256 | |
| 257 | if strings.HasPrefix(modPkgPath, caddy.ImportPath) { |
| 258 | standard = append(standard, caddyModGoMod) |
| 259 | } else { |
| 260 | nonstandard = append(nonstandard, caddyModGoMod) |
| 261 | } |
| 262 | } |
| 263 | return standard, nonstandard, unknown, err |
| 264 | } |
| 265 | |
| 266 | func listModules(path string) error { |
| 267 | cmd := exec.Command(path, "list-modules", "--versions", "--skip-standard") |
| 268 | cmd.Stdout = os.Stdout |
| 269 | cmd.Stderr = os.Stderr |
| 270 | return cmd.Run() |
| 271 | } |
| 272 | |
| 273 | func showVersion(path string) error { |
| 274 | cmd := exec.Command(path, "version") |
| 275 | cmd.Stdout = os.Stdout |
| 276 | cmd.Stderr = os.Stderr |
| 277 | return cmd.Run() |
| 278 | } |
| 279 | |
| 280 | func downloadBuild(qs url.Values) (*http.Response, error) { |
| 281 | l := caddy.Log() |
| 282 | l.Info("requesting build", |
| 283 | zap.String("os", qs.Get("os")), |
| 284 | zap.String("arch", qs.Get("arch")), |
| 285 | zap.Strings("packages", qs["p"])) |
| 286 | resp, err := http.Get(fmt.Sprintf("%s?%s", downloadPath, qs.Encode())) |
| 287 | if err != nil { |
| 288 | return nil, fmt.Errorf("secure request failed: %v", err) |
| 289 | } |
| 290 | if resp.StatusCode >= 400 { |
| 291 | var details struct { |
| 292 | StatusCode int `json:"status_code"` |
| 293 | Error struct { |
| 294 | Message string `json:"message"` |
| 295 | ID string `json:"id"` |
| 296 | } `json:"error"` |
| 297 | } |
| 298 | err2 := json.NewDecoder(resp.Body).Decode(&details) |
| 299 | if err2 != nil { |
| 300 | return nil, fmt.Errorf("download and error decoding failed: HTTP %d: %v", resp.StatusCode, err2) |
| 301 | } |
| 302 | return nil, fmt.Errorf("download failed: HTTP %d: %s (id=%s)", resp.StatusCode, details.Error.Message, details.Error.ID) |
| 303 | } |
| 304 | return resp, nil |
| 305 | } |
| 306 | |
| 307 | func getPluginPackages(modules []moduleInfo) (map[string]pluginPackage, error) { |
| 308 | pluginPkgs := make(map[string]pluginPackage) |
| 309 | for _, mod := range modules { |
| 310 | if mod.goModule.Replace != nil { |
| 311 | return nil, fmt.Errorf("cannot auto-upgrade when Go module has been replaced: %s => %s", |
| 312 | mod.goModule.Path, mod.goModule.Replace.Path) |
| 313 | } |
| 314 | pluginPkgs[mod.goModule.Path] = pluginPackage{Version: mod.goModule.Version, Path: mod.goModule.Path} |
| 315 | } |
| 316 | return pluginPkgs, nil |
| 317 | } |
| 318 | |
| 319 | func writeCaddyBinary(path string, body *io.ReadCloser, fileInfo os.FileInfo) error { |
| 320 | l := caddy.Log() |
| 321 | destFile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileInfo.Mode()) |
| 322 | if err != nil { |
| 323 | return fmt.Errorf("unable to open destination file: %v", err) |
| 324 | } |
| 325 | defer destFile.Close() |
| 326 | |
| 327 | l.Info("downloading binary", zap.String("destination", path)) |
| 328 | |
| 329 | _, err = io.Copy(destFile, *body) |
| 330 | if err != nil { |
| 331 | return fmt.Errorf("unable to download file: %v", err) |
| 332 | } |
| 333 | |
| 334 | err = destFile.Sync() |
| 335 | if err != nil { |
| 336 | return fmt.Errorf("syncing downloaded file to device: %v", err) |
| 337 | } |
| 338 | |
| 339 | return nil |
| 340 | } |
| 341 | |
| 342 | const downloadPath = "https://caddyserver.com/api/download" |
| 343 | |
| 344 | type pluginPackage struct { |
| 345 | Version string |
| 346 | Path string |
| 347 | } |
| 348 | |
| 349 | func (p pluginPackage) String() string { |
| 350 | if p.Version == "" { |
| 351 | return p.Path |
| 352 | } |
| 353 | return p.Path + "@" + p.Version |
| 354 | } |