stop.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2023 The frp 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. package sub
  15. import (
  16. "encoding/base64"
  17. "fmt"
  18. "io"
  19. "net/http"
  20. "os"
  21. "strings"
  22. "github.com/spf13/cobra"
  23. "github.com/fatedier/frp/pkg/config"
  24. v1 "github.com/fatedier/frp/pkg/config/v1"
  25. )
  26. func init() {
  27. rootCmd.AddCommand(stopCmd)
  28. }
  29. var stopCmd = &cobra.Command{
  30. Use: "stop",
  31. Short: "Stop the running frpc",
  32. RunE: func(cmd *cobra.Command, args []string) error {
  33. cfg, _, _, _, err := config.LoadClientConfig(cfgFile)
  34. if err != nil {
  35. fmt.Println(err)
  36. os.Exit(1)
  37. }
  38. err = stopClient(cfg)
  39. if err != nil {
  40. fmt.Printf("frpc stop error: %v\n", err)
  41. os.Exit(1)
  42. }
  43. fmt.Printf("stop success\n")
  44. return nil
  45. },
  46. }
  47. func stopClient(clientCfg *v1.ClientCommonConfig) error {
  48. if clientCfg.WebServer.Port == 0 {
  49. return fmt.Errorf("the port of web server shoud be set if you want to use stop feature")
  50. }
  51. req, err := http.NewRequest("POST", "http://"+
  52. clientCfg.WebServer.Addr+":"+
  53. fmt.Sprintf("%d", clientCfg.WebServer.Port)+"/api/stop", nil)
  54. if err != nil {
  55. return err
  56. }
  57. authStr := "Basic " + base64.StdEncoding.EncodeToString(
  58. []byte(clientCfg.WebServer.User+":"+clientCfg.WebServer.Password))
  59. req.Header.Add("Authorization", authStr)
  60. resp, err := http.DefaultClient.Do(req)
  61. if err != nil {
  62. return err
  63. }
  64. defer resp.Body.Close()
  65. if resp.StatusCode == 200 {
  66. return nil
  67. }
  68. body, err := io.ReadAll(resp.Body)
  69. if err != nil {
  70. return err
  71. }
  72. return fmt.Errorf("code [%d], %s", resp.StatusCode, strings.TrimSpace(string(body)))
  73. }