12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- package agi
- import (
- "encoding/json"
- "io/ioutil"
- "log"
- "net/http"
- "path/filepath"
- "strings"
- "time"
- "imuslab.com/arozos/mod/common"
- )
- //Handle request from EXTERNAL RESTFUL API
- func (g *Gateway) ExtAPIHandler(w http.ResponseWriter, r *http.Request) {
- // get db
- sysdb := g.Option.UserHandler.GetDatabase()
- if !sysdb.TableExists("external_agi") {
- common.SendErrorResponse(w, "Bad Request, invaild database")
- return
- }
- // get the request URI from the r.URL
- requestURI := filepath.ToSlash(filepath.Clean(r.URL.Path))
- subpathElements := strings.Split(requestURI[1:], "/")
- // check if it contains only two part, [rexec uuid]
- if len(subpathElements) != 2 {
- common.SendErrorResponse(w, "Bad Request, invaild request sent")
- return
- }
- // check if UUID exists in the database
- if sysdb.KeyExists("external_agi", subpathElements[1]) {
- common.SendErrorResponse(w, "Bad Request, invaild UUID entered")
- return
- }
- // get the info from the database
- var dat struct {
- Username string `json:"username"`
- Path string `json:"path"`
- }
- jsonData := ""
- sysdb.Read("external_agi", subpathElements[1], &jsonData)
- json.Unmarshal([]byte(jsonData), &dat)
- usernameFromDb := dat.Username
- pathFromDb := dat.Path
- // get the userinfo and the realPath
- userInfo, err := g.Option.UserHandler.GetUserInfoFromUsername(usernameFromDb)
- if err != nil {
- common.SendErrorResponse(w, "Bad username")
- return
- }
- _, realPath, err := virtualPathToRealPath(pathFromDb, userInfo)
- if err != nil {
- common.SendErrorResponse(w, "Bad filepath")
- return
- }
- // read the file and store it into scriptContent
- scriptContentByte, err := ioutil.ReadFile(realPath)
- if err != nil {
- common.SendErrorResponse(w, "Bad file I/O")
- return
- }
- scriptContent := string(scriptContentByte)
- // execute!
- start := time.Now()
- g.ExecuteAGIScript(scriptContent, "", "", w, r, userInfo)
- duration := time.Since(start)
- log.Println("[Remote AGI] IP:", r.RemoteAddr, " executed the script ", pathFromDb, "(", realPath, ")", " on behalf of", userInfo.Username, "with total duration: ", duration)
- }
|