├── .gitignore ├── internal └── internal.go ├── caddyplug_unix.go ├── caddyplug.go ├── caddyplug ├── plugin.go ├── fetch.go ├── deps.go ├── main.go └── command.go ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | caddy -------------------------------------------------------------------------------- /internal/internal.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | ) 7 | 8 | // PluginsDir is the directory for built plugins. 9 | func PluginsDir() string { 10 | return filepath.Join(LibDir(), "plugins") 11 | } 12 | 13 | // LibDir is the directory for caddy plugin loader resources. 14 | func LibDir() string { 15 | return filepath.Join(os.Getenv("HOME"), "lib", "caddy") 16 | } 17 | -------------------------------------------------------------------------------- /caddyplug_unix.go: -------------------------------------------------------------------------------- 1 | // +build linux darwin 2 | 3 | package caddyplug 4 | 5 | import ( 6 | "fmt" 7 | "log" 8 | "os" 9 | "path/filepath" 10 | "plugin" 11 | "strings" 12 | 13 | "github.com/abiosoft/caddyplug/internal" 14 | ) 15 | 16 | func init() { 17 | loadPlugins("http") 18 | loadPlugins("dns") 19 | } 20 | 21 | func loadPlugins(pluginType string) { 22 | log.Println("loading....", pluginType) 23 | dir, err := os.Open(filepath.Join(internal.PluginsDir(), pluginType)) 24 | if err != nil { 25 | return 26 | } 27 | plugins, err := dir.Readdirnames(-1) 28 | if err != nil { 29 | fmt.Println(err) 30 | return 31 | } 32 | for _, pluginLib := range plugins { 33 | if !strings.HasSuffix(pluginLib, ".so") { 34 | continue 35 | } 36 | pluginName := strings.TrimSuffix(pluginLib, ".so") 37 | pluginFile := filepath.Join(dir.Name(), pluginLib) 38 | _, err := plugin.Open(pluginFile) 39 | if err != nil { 40 | fmt.Println("error loading "+pluginName+": ", err) 41 | loadError = true 42 | continue 43 | } 44 | loadedPlugins[pluginType] = append(loadedPlugins[pluginType], pluginName) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /caddyplug.go: -------------------------------------------------------------------------------- 1 | package caddyplug 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "runtime" 7 | "strings" 8 | 9 | "github.com/caddyserver/caddy" 10 | ) 11 | 12 | const ( 13 | errNoPlugin = "no plugins found, use caddyplug to add plugins" 14 | errRebuildPlugin = "error occured while loading some plugins, try reinstalling them" 15 | ) 16 | 17 | func init() { 18 | caddy.RegisterEventHook("pluginloader", hook) 19 | } 20 | 21 | var hook caddy.EventHook = func(event caddy.EventName, info interface{}) error { 22 | switch event { 23 | case caddy.StartupEvent: 24 | if runtime.GOOS != "linux" { 25 | log.Println("pluginloader is only supported on Linux") 26 | return nil 27 | } 28 | count := 0 29 | if httpPlugins := loadedPlugins["http"]; len(httpPlugins) > 0 { 30 | fmt.Println("http plugins loaded:", strings.Join(httpPlugins, ", ")) 31 | count += len(httpPlugins) 32 | } 33 | if dnsPlugins := loadedPlugins["dns"]; len(dnsPlugins) > 0 { 34 | fmt.Println("dns plugins loaded:", strings.Join(dnsPlugins, ", ")) 35 | count += len(dnsPlugins) 36 | } 37 | if loadError { 38 | fmt.Println(errRebuildPlugin) 39 | } else if count == 0 { 40 | fmt.Println(errNoPlugin) 41 | } 42 | } 43 | return nil 44 | } 45 | 46 | var ( 47 | loadedPlugins = map[string][]string{ 48 | "http": []string{}, 49 | "dns": []string{}, 50 | } 51 | loadError bool 52 | ) 53 | -------------------------------------------------------------------------------- /caddyplug/plugin.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path/filepath" 7 | "strings" 8 | ) 9 | 10 | var plugins = map[string]Plugin{} 11 | 12 | // Plugin is a caddy plugin. 13 | type Plugin struct { 14 | Name string 15 | Package string 16 | Type string 17 | } 18 | 19 | // Build builds the plugin. 20 | func (p Plugin) Build() error { 21 | if err := install(p.Package); err != nil { 22 | return err 23 | } 24 | file, err := generate(pluginPath(p.Type), p) 25 | if err != nil { 26 | return err 27 | } 28 | defer os.Remove(file) 29 | return build(file, filepath.Join(filepath.Dir(file), p.Name+".so")) 30 | } 31 | 32 | // Remove uninstalls the plugin. 33 | func (p Plugin) Remove() error { 34 | if !p.Installed() { 35 | return nil 36 | } 37 | return os.Remove(p.PluginFile()) 38 | } 39 | 40 | // Installed checks if the plugin is installed. 41 | func (p Plugin) Installed() bool { 42 | stat, err := os.Stat(p.PluginFile()) 43 | // TODO not all stat errors indicate file not present. 44 | return err == nil && !stat.IsDir() 45 | } 46 | 47 | // PluginFile returns the file path to the plugin .so file. 48 | func (p Plugin) PluginFile() string { 49 | return filepath.Join(pluginPath(p.Type), p.Name+".so") 50 | } 51 | 52 | func initPlugins() error { 53 | if err := fetchDependencies(); err != nil { 54 | return err 55 | } 56 | for _, fetcher := range fetchers { 57 | p, err := fetcher.FetchPlugins() 58 | if err != nil { 59 | return err 60 | } 61 | for _, plugin := range p { 62 | plugins[plugin.Name] = plugin 63 | } 64 | } 65 | return nil 66 | } 67 | 68 | func generate(dir string, p Plugin) (string, error) { 69 | file := filepath.Join(dir, p.Name+".go") 70 | content := strings.Replace(pluginSrc, "{package}", p.Package, -1) 71 | return file, ioutil.WriteFile(file, []byte(content), 0666) 72 | } 73 | 74 | func build(src string, output string) error { 75 | return shellCmd{}.run("go", "build", "-buildmode=plugin", "-o", output, src) 76 | } 77 | 78 | func install(packageName string) error { 79 | return shellCmd{}.run("go", "get", "-v", packageName) 80 | } 81 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # caddyplug 2 | 3 | caddyplug is an experimental [Caddy](https://caddyserver.com) plugin manager using Go plugins. 4 | 5 | [Demonstration Video](https://youtu.be/uKSgHhh6-rA) 6 | 7 | ## Requirements 8 | 9 | - Go 1.8 10 | - Linux/macOS 11 | - Caddy with hook.pluginloader plugin. Installable with `caddyplug install-caddy`. 12 | 13 | ## Install 14 | 15 | ``` 16 | go get github.com/abiosoft/caddyplug/caddyplug 17 | ``` 18 | 19 | ## Usage 20 | 21 | ``` 22 | Usage: 23 | caddyplug [plugins...] 24 | 25 | Commands: 26 | install install plugins 27 | uninstall uninstall plugins 28 | list list plugins 29 | install-caddy install caddy 30 | package get plugin package 31 | ``` 32 | 33 | Example 34 | 35 | ```sh 36 | $ caddyplug install git linode 37 | ✓ git 38 | ✓ linode 39 | ``` 40 | 41 | ## Goal 42 | 43 | ### Building 44 | 45 | #### Current: 46 | 47 | - Edit source and add import line for plugin 48 | - Rebuild Caddy 49 | - Or select plugins and download on caddyserver.com/download 50 | - Repeat 51 | 52 | #### Desired: 53 | 54 | - Install plugins 55 | 56 | ### Docker 57 | 58 | #### Current: 59 | 60 | Option 1 61 | 62 | - Search for Docker image with desired plugins 63 | - Give up and clone abiosoft/caddy (or similar) image 64 | - Modify plugins arg in Dockerfile 65 | - Worry about keeping track of upgrades to parent git/docker repo. 66 | 67 | Option 2 68 | 69 | - Use [abiosoft/caddy:builder](https://github.com/abiosoft/caddy-docker/blob/master/BUILDER.md) 70 | - Requires `docker build` and/or pushing custom image to own registry 71 | 72 | #### Desired: 73 | 74 | Add plugins as required 75 | 76 | ```Dockerfile 77 | FROM abiosoft/caddy:plugin # Hopefully this changes to 'FROM caddy' 78 | RUN caddyplug install git hugo digitalocean 79 | ``` 80 | 81 | ## Caveats 82 | 83 | - Only works on Linux/macOS. 84 | - Due to limitations of Go plugins, Caddy and plugins must be built with same Go version. Installing Caddy with caddyplug is recommended to ensure this. 85 | - Not compatible with caddyserver.com/download yet. Requires [`CGO_ENABLED=1`](https://github.com/golang/go/issues/19569). 86 | - Large Docker images. Multi-stage builds may help. 87 | - Fetches `master` of plugin repositories. 88 | - `go build --buildmode=plugin` is slow. Stop building on-demand, maybe. 89 | - This is experimental and reliant on the [stability of Go plugins](https://github.com/golang/go/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aopen%20plugins). 90 | 91 | ## Note 92 | 93 | - This is not an official Caddy product. 94 | -------------------------------------------------------------------------------- /caddyplug/fetch.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "go/ast" 6 | "go/parser" 7 | "go/token" 8 | "os" 9 | "path" 10 | "path/filepath" 11 | "strconv" 12 | "strings" 13 | ) 14 | 15 | var fetchers = map[string]pluginFetcher{ 16 | "http": fetcherFunc(fetchHTTPPlugins), 17 | "dns": fetcherFunc(fetchDNSPlugins), 18 | "others": fetcherFunc(fetchOtherPlugins), 19 | } 20 | 21 | type pluginFetcher interface { 22 | FetchPlugins() ([]Plugin, error) 23 | } 24 | 25 | type fetcherFunc func() ([]Plugin, error) 26 | 27 | func (f fetcherFunc) FetchPlugins() ([]Plugin, error) { return f() } 28 | 29 | func fetchHTTPPlugins() ([]Plugin, error) { 30 | var plugins []Plugin 31 | fset := token.NewFileSet() 32 | file := filepath.Join(goPath(), "src", directivesFile) 33 | f, err := parser.ParseFile(fset, file, nil, parser.ParseComments) 34 | if err != nil { 35 | return plugins, err 36 | } 37 | node, ok := f.Scope.Lookup("directives").Decl.(*ast.ValueSpec) 38 | if !ok { 39 | return plugins, fmt.Errorf("parsing error") 40 | } 41 | 42 | cmap := ast.NewCommentMap(fset, f, f.Comments) 43 | c := node.Values[0].(*ast.CompositeLit) 44 | for _, m := range c.Elts { 45 | if cm, ok := cmap[m]; ok { 46 | pkg := strings.TrimSpace(cm[len(cm)-1].Text()) 47 | directive, err := strconv.Unquote(m.(*ast.BasicLit).Value) 48 | if err != nil { 49 | return plugins, err 50 | } 51 | // asserting that the comment word count is 1 may not be the best way 52 | // to confirm it is a repo path. 53 | if len(strings.Fields(pkg)) == 1 { 54 | plugin := Plugin{ 55 | Name: directive, 56 | Package: pkg, 57 | Type: "http", 58 | } 59 | plugins = append(plugins, plugin) 60 | } 61 | } 62 | } 63 | return plugins, nil 64 | } 65 | 66 | func fetchDNSPlugins() ([]Plugin, error) { 67 | var plugins []Plugin 68 | srcDir := filepath.Join(goPath(), "src", dnsProvidersPackage) 69 | d, err := os.Open(srcDir) 70 | if err != nil { 71 | return plugins, err 72 | } 73 | stats, err := d.Readdir(-1) 74 | if err != nil { 75 | return plugins, err 76 | } 77 | for _, stat := range stats { 78 | provider := stat.Name() 79 | // skip hidden files 80 | if strings.HasPrefix(provider, ".") || !stat.IsDir() { 81 | continue 82 | } 83 | plugin := Plugin{ 84 | Name: provider, 85 | Package: path.Join(dnsProvidersPackage, provider), 86 | Type: "dns", 87 | } 88 | plugins = append(plugins, plugin) 89 | } 90 | return plugins, nil 91 | } 92 | 93 | // TODO: this needs to be dynamic. 94 | func fetchOtherPlugins() ([]Plugin, error) { 95 | return []Plugin{ 96 | { 97 | Type: "server", 98 | Name: "net", 99 | Package: "github.com/pieterlouw/caddy-net/caddynet", 100 | }, 101 | { 102 | Type: "server", 103 | Name: "dns", 104 | Package: "github.com/coredns/coredns/core/dnsserver", 105 | }, 106 | { 107 | Type: "caddyfile", 108 | Name: "docker", 109 | Package: "github.com/lucaslorentz/caddy-docker-proxy/plugin", 110 | }, 111 | { 112 | Type: "hook", 113 | Name: "service", 114 | Package: "github.com/hacdias/caddy-service", 115 | }, 116 | }, nil 117 | } 118 | -------------------------------------------------------------------------------- /caddyplug/deps.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "os" 8 | "path/filepath" 9 | "strings" 10 | 11 | "github.com/abiosoft/errs" 12 | ) 13 | 14 | type dependencies []struct { 15 | name string 16 | importPath string 17 | installed bool 18 | updateFunc func() error 19 | } 20 | 21 | var packageDependecies = dependencies{ 22 | {name: "caddy", importPath: "github.com/caddyserver/caddy", updateFunc: fetchCaddy}, 23 | {name: "dnsproviders", importPath: "github.com/caddyserver/dnsproviders", updateFunc: fetchDNSProviders}, 24 | {name: "hook.pluginloader", importPath: "github.com/abiosoft/caddyplug", updateFunc: fetchCaddyPlug}, 25 | } 26 | 27 | func (d dependencies) installed() bool { 28 | for _, dep := range d { 29 | if !dep.installed { 30 | return false 31 | } 32 | } 33 | return true 34 | } 35 | 36 | func (d dependencies) missing() string { 37 | var s []string 38 | for i := range d { 39 | if !d[i].installed { 40 | s = append(s, d[i].name) 41 | } 42 | } 43 | return strings.Join(s, ", ") 44 | } 45 | 46 | func (d dependencies) check() bool { 47 | var buf bytes.Buffer 48 | err := shellCmd{Stdout: &buf, Dir: goPath(), Silent: true}. 49 | run("go", "list", "./...") 50 | if err != nil { 51 | return false 52 | } 53 | scanner := bufio.NewScanner(&buf) 54 | for scanner.Scan() { 55 | line := strings.TrimSpace(scanner.Text()) 56 | for i := range d { 57 | if strings.HasPrefix(line, d[i].importPath) { 58 | d[i].installed = true 59 | } 60 | } 61 | } 62 | return d.installed() 63 | } 64 | 65 | func (d dependencies) update() error { 66 | if d.check() { 67 | return nil 68 | } 69 | log("fetching missing dependencies:", d.missing()) 70 | var e errs.Group 71 | for _, dep := range d { 72 | if !dep.installed { 73 | e.Add(dep.updateFunc) 74 | } 75 | } 76 | e.Add(func() error { 77 | log("done fetching depedencies.") 78 | log() 79 | return nil 80 | }) 81 | return e.Exec() 82 | } 83 | 84 | func fetchCaddy() error { 85 | var e errs.Group 86 | e.Add(func() error { 87 | return shellCmd{}.run("go", "get", "-d", "github.com/caddyserver/caddy") 88 | }) 89 | caddyPath := filepath.Join(goPath(), "src", "github.com/caddyserver/caddy") 90 | e.Add(func() error { 91 | return shellCmd{Dir: caddyPath, Silent: true}. 92 | run("git", "checkout", caddyVersion) 93 | }) 94 | e.Add(func() error { 95 | return install("github.com/caddyserver/caddy") 96 | }) 97 | return e.Exec() 98 | } 99 | 100 | func fetchCaddyPlug() error { 101 | return install("github.com/abiosoft/caddyplug") 102 | } 103 | 104 | func fetchDNSProviders() error { 105 | var e errs.Group 106 | dnsDir := filepath.Join(goPath(), "src", dnsProvidersPackage) 107 | if _, err := os.Stat(dnsDir); err != nil { 108 | e.Add(func() error { 109 | return shellCmd{}.run("git", "clone", "https://"+dnsProvidersPackage, dnsDir) 110 | }) 111 | } 112 | dnsProvidersPath := filepath.Join(goPath(), "src", dnsProvidersPackage) 113 | e.Add(func() error { 114 | return shellCmd{Dir: dnsProvidersPath, Silent: true}. 115 | run("git", "checkout", dnsProvidersVersion) 116 | }) 117 | return e.Exec() 118 | } 119 | 120 | func fetchDependencies() error { 121 | return packageDependecies.update() 122 | } 123 | 124 | func log(a ...interface{}) { 125 | fmt.Fprintln(os.Stderr, a...) 126 | } 127 | -------------------------------------------------------------------------------- /caddyplug/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | "os/exec" 8 | "path/filepath" 9 | "runtime" 10 | "strings" 11 | "sync" 12 | 13 | "github.com/abiosoft/caddyplug/internal" 14 | ) 15 | 16 | const ( 17 | // TODO Go plugins require plugins and loaders to be built with same library versions. 18 | // this is not scalable, introduce flags maybe. 19 | caddyVersion = "master" 20 | dnsProvidersVersion = "master" 21 | 22 | directivesFile = "github.com/caddyserver/caddy/caddyhttp/httpserver/plugin.go" 23 | dnsProvidersPackage = "github.com/caddyserver/dnsproviders" 24 | caddyPackage = "github.com/caddyserver/caddy" 25 | 26 | pluginSrc = `package main 27 | 28 | import _ "{package}" 29 | ` 30 | ) 31 | 32 | func usage(err ...interface{}) { 33 | exitWithError(append(err, ` Usage: 34 | caddyplug [plugins...] 35 | 36 | Commands: 37 | install install plugins 38 | uninstall uninstall plugins 39 | list list plugins 40 | install-caddy install caddy 41 | package get plugin package 42 | `)...) 43 | } 44 | 45 | func init() { 46 | switch runtime.GOOS { 47 | case "linux", "darwin": 48 | default: 49 | exitWithError("caddyplug is only supported on Linux and macOS") 50 | } 51 | 52 | // init once 53 | once.pluginPath = map[string]*sync.Once{} 54 | for _, pluginType := range []string{"http", "dns", "server", "caddyfile", "hook"} { 55 | once.pluginPath[pluginType] = &sync.Once{} 56 | } 57 | } 58 | 59 | func main() { 60 | if len(os.Args) < 2 { 61 | usage() 62 | return 63 | } 64 | var pluginNames []string 65 | if len(os.Args) > 2 { 66 | pluginNames = os.Args[2:] 67 | } 68 | cmd, ok := commands[os.Args[1]] 69 | if !ok { 70 | usage(fmt.Sprintf("unkown command %s", os.Args[1])) 71 | return 72 | } 73 | 74 | if err := initPlugins(); err != nil { 75 | exitWithError(err) 76 | } 77 | cmd(pluginNames) 78 | } 79 | 80 | type shellCmd struct { 81 | Silent bool 82 | Stdin bool 83 | Stdout io.Writer 84 | Dir string 85 | } 86 | 87 | func (s shellCmd) run(command string, args ...string) error { 88 | cmd := exec.Command(command, args...) 89 | if !s.Silent { 90 | cmd.Stdout = os.Stderr 91 | cmd.Stderr = os.Stderr 92 | } 93 | if s.Stdout != nil { 94 | cmd.Stdout = s.Stdout 95 | } 96 | if s.Stdin { 97 | cmd.Stdin = os.Stdin 98 | } 99 | if s.Dir != "" { 100 | cmd.Dir = s.Dir 101 | } 102 | cmd.Env = env() 103 | return cmd.Run() 104 | } 105 | 106 | var once struct { 107 | goPath sync.Once 108 | pluginPath map[string]*sync.Once 109 | } 110 | 111 | func goPath() string { 112 | p := filepath.Join(internal.LibDir(), "gopath") 113 | once.goPath.Do(func() { 114 | os.MkdirAll(p, 0755) 115 | }) 116 | return p 117 | } 118 | 119 | func systemGoPath() string { 120 | if os.Getenv("GOPATH") == "" { 121 | return filepath.Join(os.Getenv("HOME"), "go") 122 | } 123 | return os.Getenv("GOPATH") 124 | } 125 | 126 | func pluginPath(pluginType string) string { 127 | p := filepath.Join(internal.PluginsDir(), pluginType) 128 | once.pluginPath[pluginType].Do(func() { 129 | os.MkdirAll(p, 0755) 130 | }) 131 | return p 132 | } 133 | 134 | // env replaces the GOPATH in env vars and returns 135 | // resulting env vars. 136 | func env() []string { 137 | env := []string{ 138 | "GOPATH=" + goPath(), 139 | } 140 | for _, e := range os.Environ() { 141 | if strings.HasPrefix(e, "GOPATH=") { 142 | continue 143 | } 144 | env = append(env, e) 145 | } 146 | return env 147 | } 148 | -------------------------------------------------------------------------------- /caddyplug/command.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | "path/filepath" 8 | "sort" 9 | "strings" 10 | 11 | "golang.org/x/sys/unix" 12 | 13 | "github.com/abiosoft/errs" 14 | "github.com/fatih/color" 15 | ) 16 | 17 | var ( 18 | commands = map[string]func([]string){ 19 | "install": installPlugins, 20 | "uninstall": uninstallPlugins, 21 | "list": listPlugins, 22 | "install-caddy": installCaddy, 23 | "package": pluginPackage, 24 | "help": func([]string) { usage() }, 25 | } 26 | 27 | successMark = color.GreenString("✓") 28 | errorMark = color.RedString("✗") 29 | ) 30 | 31 | func installPlugins(pluginNames []string) { 32 | var outputs []string 33 | var errored bool 34 | for _, pluginName := range pluginNames { 35 | plugin, ok := plugins[pluginName] 36 | if !ok { 37 | outputs = append(outputs, " "+errorMark+" "+pluginName+" - plugin not found") 38 | errored = true 39 | continue 40 | } 41 | log("installing", plugin.Name+"...") 42 | if err := plugin.Build(); err != nil { 43 | fmt.Println(err) 44 | errored = true 45 | outputs = append(outputs, " "+errorMark+" "+plugin.Name) 46 | } else { 47 | outputs = append(outputs, " "+successMark+" "+plugin.Name) 48 | } 49 | } 50 | if len(outputs) > 0 { 51 | for _, p := range outputs { 52 | fmt.Println(p) 53 | } 54 | } 55 | if errored { 56 | os.Exit(1) 57 | } 58 | } 59 | 60 | func uninstallPlugins(pluginNames []string) { 61 | var success []string 62 | var failures []string 63 | for _, pluginName := range pluginNames { 64 | plugin, ok := plugins[pluginName] 65 | if !ok { 66 | exitWithError(fmt.Sprintf("plugin not found %s", pluginName)) 67 | } 68 | if err := plugin.Remove(); err != nil { 69 | log(err) 70 | failures = append(failures, plugin.Name) 71 | } else { 72 | success = append(success, plugin.Name) 73 | } 74 | } 75 | if len(success) > 0 { 76 | fmt.Println("Uninstalled:") 77 | fmt.Println(" ", strings.Join(success, ", ")) 78 | } 79 | if len(failures) > 0 { 80 | fmt.Println("Failed to uninstall:") 81 | fmt.Println(" ", strings.Join(failures, ", ")) 82 | } 83 | } 84 | 85 | func listPlugins([]string) { 86 | for pluginType, fetcher := range fetchers { 87 | plugins, err := fetcher.FetchPlugins() 88 | if err != nil { 89 | fmt.Println(err) 90 | return 91 | } 92 | sort.Slice(plugins, func(i, j int) bool { 93 | if plugins[i].Installed() != plugins[j].Installed() { 94 | return plugins[i].Installed() 95 | } 96 | return plugins[i].Name < plugins[j].Name 97 | }) 98 | if len(plugins) > 1 { 99 | fmt.Println(pluginType + ":") 100 | } 101 | for _, plugin := range plugins { 102 | check := " " 103 | if plugin.Installed() { 104 | check = " ✓" 105 | } 106 | fmt.Println(check, plugin.Name) 107 | } 108 | } 109 | } 110 | 111 | const ( 112 | pluginLoaderFile = "caddy/caddymain/pluginloader.go" 113 | pluginLoaderSrc = `package caddymain 114 | import _ "github.com/abiosoft/caddyplug"` 115 | ) 116 | 117 | func installCaddy([]string) { 118 | fmt.Println("installing Caddy...") 119 | outputFile := "/usr/bin/caddy" 120 | 121 | // if not writable, fall back to local paths 122 | if !writable("/usr/bin") { 123 | outputFile = "/usr/local/bin/caddy" 124 | // check if GOBIN is in PATH and use it instead 125 | for _, binPath := range strings.Split(os.Getenv("PATH"), 126 | string([]byte{filepath.ListSeparator})) { 127 | if filepath.Clean(binPath) == filepath.Join(systemGoPath(), "bin") { 128 | outputFile = filepath.Join(systemGoPath(), "bin", "caddy") 129 | break 130 | } 131 | } 132 | } 133 | 134 | var e errs.Group 135 | pluginFile := filepath.Join(goPath(), "src", caddyPackage, pluginLoaderFile) 136 | e.Add(func() error { 137 | return ioutil.WriteFile(pluginFile, []byte(pluginLoaderSrc), 0644) 138 | }) 139 | e.Add(func() error { 140 | return shellCmd{}. 141 | run("go", "build", "-o", outputFile, caddyPackage+"/caddy") 142 | }) 143 | e.Add(func() error { 144 | fmt.Println(" ", successMark, "installed Caddy in", outputFile) 145 | return nil 146 | }) 147 | e.Add(func() error { 148 | return os.Remove(pluginFile) 149 | }) 150 | 151 | if err := e.Exec(); err != nil { 152 | exitWithError(err) 153 | } 154 | } 155 | 156 | func pluginPackage(args []string) { 157 | if len(args) == 0 { 158 | exitWithError("plugin name required") 159 | } 160 | name := args[0] 161 | p, ok := plugins[name] 162 | if !ok { 163 | exitWithError("plugin not found") 164 | } 165 | fmt.Println(p.Package) 166 | } 167 | 168 | func writable(path string) bool { 169 | return unix.Access(path, unix.W_OK) == nil 170 | } 171 | 172 | func exitWithError(errs ...interface{}) { 173 | if len(errs) > 0 { 174 | fmt.Fprintln(os.Stderr, errs...) 175 | } 176 | os.Exit(1) 177 | } 178 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Abiola Ibrahim 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------