main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "crypto/sha256"
  7. "database/sql"
  8. "encoding/base64"
  9. "encoding/json"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "log"
  14. "log/syslog"
  15. "net/http"
  16. "os"
  17. "strconv"
  18. "strings"
  19. "github.com/google/uuid"
  20. "github.com/jasonlvhit/gocron"
  21. "github.com/labstack/echo"
  22. "github.com/labstack/echo/middleware"
  23. "gopkg.in/gomail.v2"
  24. )
  25. var _appversion string = "0.1"
  26. var _appname string = "ZiCloud-API"
  27. var URL string = "https://ipa-cl.zi-tel.com"
  28. var OvirtURL string = "https://ovirt-cl.zi-tel.com"
  29. var RealIP string
  30. var secretKey = []byte("P*%!5+u!$y+cgM+P8bybzgnXpsd2Lv2z") // 32 bytes
  31. type _response struct {
  32. Message string `json:"message"`
  33. Origin string `json:"origin"`
  34. Code int `json:"code"`
  35. }
  36. func uuidgen(resource string) (string, int) {
  37. id := uuid.New()
  38. if len(resource) < 3 {
  39. return "resource name should be at least 3 characters!", 1001
  40. }
  41. //fmt.Println("uuidGen for ", id, " at ", resource)
  42. {
  43. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  44. if err != nil {
  45. return "Error in DB Layer", 1001
  46. }
  47. defer db.Close()
  48. insert, err := db.Query("INSERT INTO uuid VALUES ( '" + fmt.Sprintf("%s", id) + "'," +
  49. "'" + resource + "'," +
  50. "NOW()" +
  51. " )")
  52. if err != nil {
  53. return "Error in DB Layer", 1001
  54. }
  55. defer insert.Close()
  56. }
  57. return fmt.Sprintf("%s", id), 1000
  58. }
  59. func audit(txt string) {
  60. syslogger, err := syslog.New(syslog.LOG_INFO, _appname)
  61. if err != nil {
  62. log.Fatalln(err)
  63. }
  64. log.SetOutput(syslogger)
  65. log.Println(txt)
  66. }
  67. func basicAuth(username, password string) string {
  68. auth := username + "@IPA:" + password
  69. return base64.StdEncoding.EncodeToString([]byte(auth))
  70. }
  71. func sendMail(str string, subject string, recipient string, attachment []string) {
  72. m := gomail.NewMessage()
  73. m.SetHeader("From", "zicloud@zi-tel.com")
  74. m.SetHeader("To", recipient)
  75. buff := make([]byte, 8)
  76. rand.Read(buff)
  77. random_str := base64.StdEncoding.EncodeToString(buff)
  78. //fmt.Println(random_str)
  79. m.SetHeader("Message-Id", "<"+random_str+"@ZiCloud.com>")
  80. //m.SetAddressHeader("Cc", "dan@example.com", "Dan")
  81. m.SetHeader("Subject", subject)
  82. m.SetBody("text/html", str+"</br>")
  83. if len(attachment) > 0 {
  84. for _, i := range attachment {
  85. m.Attach(i)
  86. }
  87. }
  88. d := gomail.NewDialer("mail.zi-tel.com", 25, "zicloud@zi-tel.com", "5Sd?^AQx@r2OGRvS?i|DO0")
  89. // Send the email to Bob, Cora and Dan.
  90. if err := d.DialAndSend(m); err != nil {
  91. panic(err)
  92. }
  93. }
  94. //func sendMail(str string, subject string, recipient string, attachment []string) {
  95. // auth := smtp.PlainAuth("", "zicloud@zi-tel.com", "5Sd?^AQx@r2OGRvS?i|DO0", "mail.zi-tel.com")
  96. // to := []string{recipient}
  97. // buff := make([]byte, 8)
  98. // rand.Read(buff)
  99. // random_str := base64.StdEncoding.EncodeToString(buff)
  100. // msg := []byte("To:" + recipient + "\r\n" +
  101. // "Date: " + time.Now().Format(time.RFC1123) + "\r\n" +
  102. // "Message-Id: <" + random_str + "@ZiCloud.com>" + "\r\n" +
  103. // "subject: " + subject + "\r\n" +
  104. // "From: ZiCloud <" + "zicloud@zi-tel.com" + ">\r\n" +
  105. // str)
  106. // err := smtp.SendMail("mail.zi-tel.com:25", auth, "zicloud@zi-tel.com", to, msg)
  107. // if err != nil {
  108. // log.Fatal(err)
  109. // }
  110. //}
  111. func extractIP(next echo.HandlerFunc) echo.HandlerFunc {
  112. return func(c echo.Context) error {
  113. RealIP = c.RealIP()
  114. audit("Recieved request from: " + RealIP)
  115. return next(c)
  116. }
  117. }
  118. func main() {
  119. if len(os.Args) != 3 {
  120. fmt.Println("Wrong Usage:\n\t ./CMD IP Port")
  121. audit("Application in the wrong way")
  122. os.Exit(1)
  123. }
  124. s := gocron.NewScheduler()
  125. s.Every(5).Seconds().Do(task)
  126. go s.Start()
  127. echoHandler := echo.New()
  128. echoHandler.Use(extractIP)
  129. echoHandler.Use(middleware.CORSWithConfig(middleware.CORSConfig{
  130. AllowOrigins: []string{"*", "*"},
  131. AllowMethods: []string{http.MethodGet, http.MethodPost},
  132. }))
  133. audit("Application " + _appname + " (" + _appversion + ") Started by " + os.Getenv("USER"))
  134. echoHandler.GET("/", func(c echo.Context) error {
  135. return c.String(http.StatusOK, "Hello, World!")
  136. })
  137. h := &handler{}
  138. echoHandler.POST("/login", h.login)
  139. echoHandler.POST("/uuidgen", h.uuidgen)
  140. //echoHandler.GET("/admin", h.uuidgen, isLoggedIn, isAdmin)
  141. echoHandler.POST("/addUser", h.addUser, isLoggedIn, isAdmin)
  142. echoHandler.POST("/editUser", h.editUser, isLoggedIn, isAdmin)
  143. echoHandler.POST("/showUser", h.showUser, isLoggedIn, isAdmin)
  144. echoHandler.POST("/disableUser", h.disableUser, isLoggedIn, isAdmin)
  145. echoHandler.POST("/resetUser", h.resetUser)
  146. echoHandler.GET("/verifyUser", h.verifyUser)
  147. echoHandler.POST("/dnsrecordadd", h.dnsrecordadd, isLoggedIn, isAdmin)
  148. echoHandler.POST("/forgetpassword", h.forgetpassword, isLoggedIn, isAdmin)
  149. echoHandler.POST("/token", h.token, isLoggedIn)
  150. echoHandler.POST("/ListServices", h.ListServices, isLoggedIn)
  151. echoHandler.POST("/PriceCalc", h.PriceCalc, isLoggedIn)
  152. iaas := &ovirt{}
  153. echoHandler.GET("/ovirtListVMs", iaas.listVM, isLoggedIn)
  154. echoHandler.POST("/ovirtVNC", iaas.VNC, isLoggedIn)
  155. echoHandler.GET("/ovirtListTemplates", iaas.listTemplate, isLoggedIn)
  156. echoHandler.POST("/ovirtAddVM", iaas.addvm, isLoggedIn)
  157. echoHandler.POST("/ovirtStartVM", iaas.StartVM, isLoggedIn)
  158. echoHandler.POST("/ovirtStopVM", iaas.StopVM, isLoggedIn)
  159. echoHandler.POST("/ovirtRebootVM", iaas.RebootVM, isLoggedIn)
  160. echoHandler.POST("/ovirtPowerOffVM", iaas.PowerOffVM, isLoggedIn)
  161. echoHandler.POST("/ovirtResetVM", iaas.ResetVM, isLoggedIn)
  162. echoHandler.POST("/ovirtAddNIC", iaas.AddNIC, isLoggedIn)
  163. echoHandler.POST("/ovirtAddDisk", iaas.AddDisk, isLoggedIn)
  164. echoHandler.POST("/ovirtEditVM", iaas.EditVM, isLoggedIn)
  165. echoHandler.POST("/ovirtResetPassword", iaas.ResetPassword, isLoggedIn)
  166. echoHandler.POST("/vmDetails", iaas.vmDetails, isLoggedIn)
  167. echoHandler.POST("/vmHistory", iaas.vmHistory, isLoggedIn)
  168. echoHandler.GET("/SSHKeyGen", iaas.SSHKeyGen, isLoggedIn)
  169. echoHandler.POST("/ovirtPayment", iaas.ovirtPayment, isLoggedIn)
  170. echoHandler.POST("/ovirtSuspend", iaas.ovirtSuspend, isLoggedIn)
  171. billing := billing{}
  172. echoHandler.POST("/billingList", billing.list, isLoggedIn)
  173. echoHandler.POST("/billingShow", billing.Show, isLoggedIn)
  174. echoHandler.Logger.Fatal(echoHandler.Start(os.Args[1] + ":" + os.Args[2]))
  175. }
  176. func encrypt(key []byte, text string) string {
  177. // key := []byte(keyText)
  178. //fmt.Println("Encrypt by: ", key)
  179. plaintext := []byte(text)
  180. block, err := aes.NewCipher(key)
  181. if err != nil {
  182. //panic(err)
  183. fmt.Println("encrypt got error")
  184. return ""
  185. }
  186. // The IV needs to be unique, but not secure. Therefore it's common to
  187. // include it at the beginning of the ciphertext.
  188. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  189. iv := ciphertext[:aes.BlockSize]
  190. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  191. fmt.Println("encrypt got error")
  192. return ""
  193. }
  194. stream := cipher.NewCFBEncrypter(block, iv)
  195. stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
  196. // convert to base64
  197. return base64.URLEncoding.EncodeToString(ciphertext)
  198. }
  199. func decrypt(key []byte, cryptoText string) string {
  200. ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
  201. //fmt.Println("Decrypt by: ", key)
  202. block, err := aes.NewCipher(key)
  203. if err != nil {
  204. fmt.Println("encrypt got error")
  205. return ""
  206. //panic(err)
  207. }
  208. // The IV needs to be unique, but not secure. Therefore it's common to
  209. // include it at the beginning of the ciphertext.
  210. if len(ciphertext) < aes.BlockSize {
  211. fmt.Println("encrypt got error")
  212. return ""
  213. //panic("ciphertext too short")
  214. }
  215. iv := ciphertext[:aes.BlockSize]
  216. ciphertext = ciphertext[aes.BlockSize:]
  217. stream := cipher.NewCFBDecrypter(block, iv)
  218. // XORKeyStream can work in-place if the two arguments are the same.
  219. stream.XORKeyStream(ciphertext, ciphertext)
  220. return fmt.Sprintf("%s", ciphertext)
  221. }
  222. func task() {
  223. type Task struct {
  224. UUID string `json:"uuid"`
  225. TaskAPICall string `json:"taskapicall"`
  226. Ruuid string `json:"ruuid"`
  227. CronExpression string `json:"cronexpression"`
  228. object_active string `json:"object_active"`
  229. Type string `json:"type"` //0: createVM , 1: VMInitialization
  230. }
  231. //fmt.Println("Task is being performed.")
  232. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  233. results, err := db.Query("select sch.uuid as UUID ,task_apiCall as TaskAPICall, cron_expression as CronExpression , related_uuid as Ruuid, sch.type as type,sp.active as object_active from scheduler sch join service_profile sp on sp.uuid=sch.related_uuid where sch.active=1")
  234. //results, err := db.Query("SELECT uuid as UUID ,task_apiCall as TaskAPICall , cron_expression as CronExpression , related_uuid as Ruuid, type FROM scheduler where active=1")
  235. for results.Next() {
  236. var res Task
  237. err = results.Scan(&res.UUID, &res.TaskAPICall, &res.CronExpression, &res.Ruuid, &res.Type, &res.object_active)
  238. if err != nil {
  239. panic(err.Error()) // proper error handling instead of panic in your app
  240. }
  241. taskType := 0
  242. taskType, _ = strconv.Atoi(res.Type)
  243. ObjAct, _ := strconv.Atoi(res.object_active)
  244. fmt.Println("Running Task : ", res.UUID)
  245. if taskType == 0 {
  246. createVM(res.Ruuid, res.TaskAPICall, res.UUID)
  247. } else if taskType == 1 && ObjAct != -3 {
  248. VMInitialization(res.Ruuid, res.TaskAPICall, res.UUID)
  249. } else if taskType == 2 {
  250. } else {
  251. }
  252. //fmt.Println("query ruuid: ", res.Ruuid)
  253. }
  254. if err != nil {
  255. panic(err.Error()) // proper error handling instead of panic in your app
  256. }
  257. if err != nil {
  258. panic(err.Error())
  259. }
  260. defer db.Close()
  261. //iaas := &ovirt{}
  262. //fmt.Println("down",iaas.vmStatus("4f0e58ff-fb75-4a3d-9262-bd3714db52a6"))
  263. //fmt.Println("up",iaas.vmStatus("6b84a5dc-1c83-43e0-9ea6-dd86413bccc0"))
  264. }
  265. func addTask(uuid string, taskAPICall string, cronExpression string, origin string, description string, related_uuid string, _type string, active string) string {
  266. {
  267. /*
  268. types:
  269. 0: VM Create
  270. 1: VM Initialize
  271. 2: VM Start
  272. 3: VM Stop
  273. */
  274. //fmt.Println("Add Task:", uuid)
  275. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  276. if err != nil {
  277. }
  278. defer db.Close()
  279. //INSERT INTO `zicloud`.`scheduler`(`uuid`, `taskAPICall`, active`, `cron_expression`, `origin`, NOW()) VALUES ('xx', 'xx', 'xx', 0, 'xx', 'xx');
  280. insert, err := db.Query("INSERT INTO scheduler VALUES (" +
  281. " '" + uuid + "'," +
  282. "'" + taskAPICall + "'," +
  283. "'" + active + "'," +
  284. "'" + cronExpression + "'," +
  285. "'" + origin + "'," +
  286. "'" + description + "'," +
  287. "'" + related_uuid + "'," +
  288. _type + "," +
  289. "NOW()" +
  290. " )")
  291. if err != nil {
  292. }
  293. defer insert.Close()
  294. }
  295. return "OK"
  296. }
  297. func toggleTask(uuid string, active int) {
  298. db, err := sql.Open("mysql", MySQLUSER+":"+MySQLPASS+"@tcp(127.0.0.1:3306)/zicloud")
  299. if err != nil {
  300. }
  301. update, err := db.Query("update scheduler set active='" + fmt.Sprintf("%s", active) + "' where uuid='" + uuid + "'")
  302. defer db.Close()
  303. if err != nil {
  304. }
  305. defer update.Close()
  306. }
  307. func runAPICall(apiCall addVMTask) []byte {
  308. url := apiCall.URL
  309. method := apiCall.Method
  310. __json := apiCall.JSON
  311. //fmt.Println("runAPICALL: ", __json)
  312. client := &http.Client{}
  313. payload := strings.NewReader(__json)
  314. req, err := http.NewRequest(method, url, payload)
  315. _headers := apiCall.Headers
  316. for _, v := range _headers {
  317. req.Header.Add(v.Name, v.Value)
  318. }
  319. if err != nil {
  320. fmt.Println(err)
  321. }
  322. res, err := client.Do(req)
  323. defer res.Body.Close()
  324. body, _ := ioutil.ReadAll(res.Body)
  325. return body
  326. }
  327. func VMPowerMng(relatedUuid string, apiCall string, uuid string) {
  328. startVM := addVMTask{}
  329. _err := json.Unmarshal([]byte(apiCall), &startVM)
  330. if _err != nil {
  331. fmt.Println("Error in VMPowerMng: ", _err.Error())
  332. }
  333. _sha256 := sha256.Sum256([]byte(relatedUuid))
  334. var hashChannel_ = make(chan []byte, 1)
  335. hashChannel_ <- _sha256[:]
  336. //fmt.Println(" startVM.JSON: ", startVM.JSON)
  337. startVM.JSON = decrypt(<-hashChannel_, startVM.JSON)
  338. //fmt.Println("decrypted json: ",startVM.JSON)
  339. runAPICall(startVM)
  340. toggleTask(uuid, 0)
  341. }