selfpaste.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "math/rand"
  7. "os"
  8. "flag"
  9. "gopkg.in/yaml.v2"
  10. "net/http"
  11. "io/ioutil"
  12. "bytes"
  13. "mime/multipart"
  14. "encoding/json"
  15. )
  16. /**
  17. * This program is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU General Public License as published by
  19. * the Free Software Foundation, either version 3 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.
  29. *
  30. * 2019 - 2023 https://://www.bananas-playground.net/projekt/selfpaste
  31. */
  32. /**
  33. * !WARNING!
  34. * This is a very simple, with limited experience written, go program.
  35. * Use at own risk and feel free to improve
  36. */
  37. const website = "https://www.bananas-playground.net/projekt/selfpaste"
  38. const version = "1.0"
  39. // used for non-existing default config
  40. const letters = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
  41. // command line parameters
  42. var optsVerbose bool
  43. var optsCreateConfig bool
  44. var optsDebug bool
  45. // config
  46. var cfg Config
  47. // config file struct
  48. type Config struct {
  49. Endpoint struct {
  50. Host string `yaml:"host"`
  51. Secret string `yaml:"secret"`
  52. } `yaml:"endpoint"`
  53. }
  54. // response json struct
  55. type Response struct {
  56. Message string `json:"message"`
  57. Status int `json:"status"`
  58. }
  59. /**
  60. * Main
  61. */
  62. func main() {
  63. // parse commandline parameters
  64. flag.BoolVar(&optsVerbose, "verbose", false, "Produce verbose output")
  65. flag.BoolVar(&optsCreateConfig, "create-config-file", false, "Create default config file")
  66. flag.BoolVar(&optsDebug, "debug", false, "Print debug infos")
  67. flag.Parse()
  68. if optsDebug {
  69. fmt.Println("verbose:", optsVerbose)
  70. fmt.Println("create-config-file:", optsCreateConfig)
  71. fmt.Println("debug:", optsDebug)
  72. }
  73. // load the config and populate Config
  74. loadConfig()
  75. // get the paylout
  76. payload := getInput()
  77. if optsDebug { log.Println(payload) }
  78. // do the upload and get the response
  79. responseString := uploadCall(payload)
  80. response := Response{}
  81. json.Unmarshal([]byte(responseString), &response)
  82. // print the result and link to the pasty
  83. fmt.Printf("Status: %d\n", response.Status)
  84. fmt.Printf("Message: %s\n", response.Message)
  85. }
  86. /**
  87. * Check and display error with additional message
  88. */
  89. func errorCheck(e error, msg string) {
  90. if e != nil {
  91. log.Fatal(msg,e)
  92. }
  93. }
  94. /**
  95. * just a random string
  96. */
  97. func randStringBytes(n int) string {
  98. b := make([]byte, n)
  99. for i := range b {
  100. b[i] = letters[rand.Intn(len(letters))]
  101. }
  102. return string(b)
  103. }
  104. /**
  105. * load or even create a default config
  106. * $HOME/.selfpaste.yaml
  107. */
  108. func loadConfig() {
  109. homeDir, err := os.UserHomeDir()
  110. errorCheck(err, "No $HOME directory available?")
  111. if optsVerbose { log.Printf("Your $HOME: %s \n", homeDir) }
  112. var configFile = homeDir + "/.selfpaste.yaml"
  113. if _, err := os.Stat(configFile); errors.Is(err, os.ErrNotExist) {
  114. log.Printf("Config file not found: %s \n", configFile)
  115. if optsCreateConfig {
  116. log.Printf("Creating new default config file: %s \n", configFile)
  117. newConfig, err := os.Create(configFile)
  118. errorCheck(err, "Can not create config file!")
  119. defer newConfig.Close()
  120. _, err = fmt.Fprintf(newConfig, "# selfpaste go client config file.\n")
  121. errorCheck(err, "Can not write to new config file")
  122. fmt.Fprintf(newConfig, "# See %s for more details.\n", website)
  123. fmt.Fprintf(newConfig, "# Version: %s\n", version)
  124. fmt.Fprintf(newConfig, "endpoint:\n")
  125. fmt.Fprintf(newConfig, " host: http://your-seflpaste-endpoi.nt\n")
  126. fmt.Fprintf(newConfig, " secret: %s\n", randStringBytes(50))
  127. log.Fatalf("New default config file created: - %s - Edit and launch again!",configFile)
  128. }
  129. }
  130. existingConfigFile, err := os.Open(configFile)
  131. errorCheck(err, "Can not open config file")
  132. defer existingConfigFile.Close()
  133. if optsVerbose { log.Printf("Reading config file: %s \n", configFile) }
  134. var decoder = yaml.NewDecoder(existingConfigFile)
  135. err = decoder.Decode(&cfg)
  136. errorCheck(err, "Can not decode config file")
  137. if cfg.Endpoint.Host == "" || cfg.Endpoint.Secret == "" {
  138. log.Fatal("Empty config?")
  139. }
  140. if optsDebug {
  141. log.Println(cfg.Endpoint.Host)
  142. log.Println(cfg.Endpoint.Secret)
  143. }
  144. }
  145. /**
  146. * Do a http POST call to the defined endpoint
  147. * and upload the payload
  148. * Return response body as string
  149. */
  150. func uploadCall(payload string) string {
  151. if optsVerbose { log.Println("Starting to upload data") }
  152. if optsDebug { log.Println(payload) }
  153. if len(payload) == 0 {
  154. log.Fatal("Nothing provided to upload")
  155. }
  156. // Buffer to store our request body as bytes
  157. var requestBody bytes.Buffer
  158. // Create a multipart writer
  159. multiPartWriter := multipart.NewWriter(&requestBody)
  160. // file field
  161. fileWriter, err := multiPartWriter.CreateFormFile("pasty", "pastyfile")
  162. errorCheck(err, "Can not create form file field")
  163. fileWriter.Write([]byte(payload))
  164. dlField, err := multiPartWriter.CreateFormField("dl")
  165. errorCheck(err, "Can not create form dl field")
  166. dlField.Write([]byte(cfg.Endpoint.Secret))
  167. multiPartWriter.Close()
  168. req, err := http.NewRequest(http.MethodPost, cfg.Endpoint.Host, &requestBody)
  169. errorCheck(err, "Can not create http request")
  170. // We need to set the content type from the writer, it includes necessary boundary as well
  171. req.Header.Set("Content-Type", multiPartWriter.FormDataContentType())
  172. req.Header.Set("User-Agent", "selfpasteAgent/1.0");
  173. // Do the request
  174. client := &http.Client{}
  175. response, err := client.Do(req)
  176. errorCheck(err, "POST request failed")
  177. responseBody, err := ioutil.ReadAll(response.Body)
  178. errorCheck(err, "Can not read response body")
  179. if optsVerbose { log.Println("Request done") }
  180. if optsDebug {
  181. log.Printf("Response status code: %d\n",response.StatusCode)
  182. log.Printf("Response headers: %#v\n", response.Header)
  183. log.Println(string(responseBody))
  184. }
  185. return string(responseBody)
  186. }
  187. /**
  188. * check if file is provided as commandline argument
  189. * or piped into
  190. * return the read data as string
  191. */
  192. func getInput() string {
  193. if optsVerbose { log.Println("Getting input") }
  194. var inputString string
  195. if filename := flag.Arg(0); filename != "" {
  196. if optsVerbose { log.Println("Read from file argument") }
  197. bytes, err := os.ReadFile(filename)
  198. errorCheck(err, "Error opening file")
  199. inputString = string(bytes)
  200. } else {
  201. stat, _ := os.Stdin.Stat()
  202. if (stat.Mode() & os.ModeCharDevice) == 0 {
  203. if optsVerbose { log.Println("data is being piped") }
  204. bytes, _ := ioutil.ReadAll(os.Stdin)
  205. inputString = string(bytes)
  206. }
  207. }
  208. if len(inputString) == 0 {
  209. log.Fatal("Nothing provided to upload")
  210. }
  211. return inputString
  212. }