api.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package core
  2. import (
  3. "JsRpc/config"
  4. "JsRpc/utils"
  5. "github.com/gin-gonic/gin"
  6. "github.com/gorilla/websocket"
  7. log "github.com/sirupsen/logrus"
  8. "github.com/unrolled/secure"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. )
  14. var (
  15. upGrader = websocket.Upgrader{
  16. CheckOrigin: func(r *http.Request) bool { return true },
  17. }
  18. gm = &sync.Mutex{}
  19. hlSyncMap sync.Map
  20. )
  21. // Message 请求和传递请求
  22. type Message struct {
  23. Action string `json:"action"`
  24. Param string `json:"param"`
  25. }
  26. type ApiParam struct {
  27. GroupName string `form:"group" json:"group"`
  28. ClientId string `form:"clientId" json:"clientId"`
  29. Action string `form:"action" json:"action"`
  30. Param string `form:"param" json:"param"`
  31. Code string `form:"code" json:"code"` // 直接eval的代码
  32. }
  33. // Clients 客户端信息
  34. type Clients struct {
  35. clientGroup string
  36. clientId string
  37. actionData map[string]chan string
  38. clientWs *websocket.Conn
  39. }
  40. // NewClient initializes a new Clients instance
  41. func NewClient(group string, uid string, ws *websocket.Conn) *Clients {
  42. return &Clients{
  43. clientGroup: group,
  44. clientId: uid,
  45. actionData: make(map[string]chan string, 1), // action有消息后就保存到chan里
  46. clientWs: ws,
  47. }
  48. }
  49. func GinJsonMsg(c *gin.Context, code int, msg string) {
  50. c.JSON(code, gin.H{"status": code, "data": msg})
  51. return
  52. }
  53. // ws, provides inject function for a job
  54. func ws(c *gin.Context) {
  55. group, clientId := c.Query("group"), c.Query("clientId")
  56. //必须要group名字,不然不让它连接ws
  57. if group == "" {
  58. return
  59. }
  60. //没有给客户端id的话 就用时间戳给他生成一个
  61. if clientId == "" {
  62. clientId = utils.GetUUID()
  63. }
  64. wsClient, err := upGrader.Upgrade(c.Writer, c.Request, nil)
  65. if err != nil {
  66. log.Error("websocket err:", err)
  67. return
  68. }
  69. client := NewClient(group, clientId, wsClient)
  70. hlSyncMap.Store(group+"->"+clientId, client)
  71. utils.LogPrint("新上线group:" + group + ",clientId:->" + clientId)
  72. for {
  73. //等待数据
  74. _, message, err := wsClient.ReadMessage()
  75. if err != nil {
  76. break
  77. }
  78. msg := string(message)
  79. check := []uint8{104, 108, 94, 95, 94}
  80. strIndex := strings.Index(msg, string(check))
  81. if strIndex >= 1 {
  82. action := msg[:strIndex]
  83. client.actionData[action] <- msg[strIndex+5:]
  84. if len(msg) > 100 {
  85. utils.LogPrint("get_message:", msg[strIndex+5:101]+"......")
  86. } else {
  87. utils.LogPrint("get_message:", msg[strIndex+5:])
  88. }
  89. } else {
  90. log.Error(msg, "message error")
  91. }
  92. }
  93. defer func(ws *websocket.Conn) {
  94. _ = ws.Close()
  95. utils.LogPrint(group+"->"+clientId, "下线了")
  96. hlSyncMap.Range(func(key, value interface{}) bool {
  97. //client, _ := value.(*Clients)
  98. if key == group+"->"+clientId {
  99. hlSyncMap.Delete(key)
  100. }
  101. return true
  102. })
  103. }(wsClient)
  104. }
  105. func wsTest(c *gin.Context) {
  106. testClient, _ := upGrader.Upgrade(c.Writer, c.Request, nil)
  107. for {
  108. //等待数据
  109. _, message, err := testClient.ReadMessage()
  110. if err != nil {
  111. break
  112. }
  113. msg := string(message)
  114. utils.LogPrint("接收到测试消息", msg)
  115. _ = testClient.WriteMessage(websocket.BinaryMessage, []byte(msg))
  116. }
  117. defer func(ws *websocket.Conn) {
  118. _ = ws.Close()
  119. }(testClient)
  120. }
  121. func GetCookie(c *gin.Context) {
  122. var RequestParam ApiParam
  123. if err := c.ShouldBind(&RequestParam); err != nil {
  124. GinJsonMsg(c, http.StatusBadRequest, err.Error())
  125. return
  126. }
  127. group := c.Query("group")
  128. if group == "" {
  129. GinJsonMsg(c, http.StatusBadRequest, "需要传入group")
  130. return
  131. }
  132. clientId := RequestParam.ClientId
  133. client := getRandomClient(group, clientId)
  134. if client == nil {
  135. GinJsonMsg(c, http.StatusBadRequest, "没有找到对应的group或clientId,请通过list接口查看现有的注入")
  136. return
  137. }
  138. c3 := make(chan string, 1)
  139. go client.GQueryFunc("_execjs", utils.ConcatCode("document.cookie"), c3)
  140. c.JSON(http.StatusOK, gin.H{"status": 200, "group": client.clientGroup, "clientId": client.clientId, "data": <-c3})
  141. }
  142. func GetHtml(c *gin.Context) {
  143. var RequestParam ApiParam
  144. if err := c.ShouldBind(&RequestParam); err != nil {
  145. GinJsonMsg(c, http.StatusBadRequest, err.Error())
  146. return
  147. }
  148. group := c.Query("group")
  149. if group == "" {
  150. GinJsonMsg(c, http.StatusBadRequest, "需要传入group")
  151. return
  152. }
  153. clientId := RequestParam.ClientId
  154. client := getRandomClient(group, clientId)
  155. if client == nil {
  156. GinJsonMsg(c, http.StatusBadRequest, "没有找到对应的group或clientId,请通过list接口查看现有的注入")
  157. return
  158. }
  159. c3 := make(chan string, 1)
  160. go client.GQueryFunc("_execjs", utils.ConcatCode("document.documentElement.outerHTML"), c3)
  161. c.JSON(http.StatusOK, gin.H{"status": 200, "group": client.clientGroup, "clientId": client.clientId, "data": <-c3})
  162. }
  163. // GetResult 接收web请求参数,并发给客户端获取结果
  164. func getResult(c *gin.Context) {
  165. var RequestParam ApiParam
  166. if err := c.ShouldBind(&RequestParam); err != nil {
  167. GinJsonMsg(c, http.StatusBadRequest, err.Error())
  168. return
  169. }
  170. group := RequestParam.GroupName
  171. if group == "" {
  172. GinJsonMsg(c, http.StatusBadRequest, "需要传入group")
  173. return
  174. }
  175. action := RequestParam.Action
  176. if action == "" {
  177. GinJsonMsg(c, http.StatusOK, "请传入action来调用客户端方法")
  178. return
  179. }
  180. clientId := RequestParam.ClientId
  181. client := getRandomClient(group, clientId)
  182. if client == nil {
  183. GinJsonMsg(c, http.StatusBadRequest, "没有找到对应的group或clientId,请通过list接口查看现有的注入")
  184. return
  185. }
  186. c2 := make(chan string, 1)
  187. go client.GQueryFunc(action, RequestParam.Param, c2)
  188. //把管道传过去,获得值就返回了
  189. c.JSON(http.StatusOK, gin.H{"status": 200, "group": client.clientGroup, "clientId": client.clientId, "data": <-c2})
  190. }
  191. func execjs(c *gin.Context) {
  192. var RequestParam ApiParam
  193. if err := c.ShouldBind(&RequestParam); err != nil {
  194. GinJsonMsg(c, http.StatusBadRequest, err.Error())
  195. return
  196. }
  197. Action := "_execjs"
  198. //获取参数
  199. group := RequestParam.GroupName
  200. if group == "" {
  201. GinJsonMsg(c, http.StatusBadRequest, "需要传入group")
  202. return
  203. }
  204. JsCode := RequestParam.Code
  205. if JsCode == "" {
  206. GinJsonMsg(c, http.StatusBadRequest, "请传入代码")
  207. return
  208. }
  209. clientId := RequestParam.ClientId
  210. client := getRandomClient(group, clientId)
  211. if client == nil {
  212. GinJsonMsg(c, http.StatusBadRequest, "没有找到对应的group或clientId,请通过list接口查看现有的注入")
  213. return
  214. }
  215. c2 := make(chan string)
  216. go client.GQueryFunc(Action, JsCode, c2)
  217. c.JSON(200, gin.H{"status": "200", "group": client.clientGroup, "name": client.clientId, "data": <-c2})
  218. }
  219. func getList(c *gin.Context) {
  220. var data = make(map[string][]string)
  221. hlSyncMap.Range(func(_, value interface{}) bool {
  222. client, ok := value.(*Clients)
  223. if !ok {
  224. return true // 继续遍历
  225. }
  226. group := client.clientGroup
  227. data[group] = append(data[group], client.clientId)
  228. return true
  229. })
  230. c.JSON(http.StatusOK, gin.H{"status": 200, "data": data})
  231. }
  232. func index(c *gin.Context) {
  233. c.String(200, "你好,我是黑脸怪~")
  234. }
  235. func tlsHandler(HttpsHost string) gin.HandlerFunc {
  236. return func(c *gin.Context) {
  237. secureMiddleware := secure.New(secure.Options{
  238. SSLRedirect: true,
  239. SSLHost: HttpsHost,
  240. })
  241. err := secureMiddleware.Process(c.Writer, c.Request)
  242. if err != nil {
  243. c.Abort()
  244. return
  245. }
  246. c.Next()
  247. }
  248. }
  249. func getGinMode(mode string) string {
  250. switch mode {
  251. case "release":
  252. return gin.ReleaseMode
  253. case "debug":
  254. return gin.DebugMode
  255. case "test":
  256. return gin.TestMode
  257. }
  258. return gin.ReleaseMode // 默认就是release模式
  259. }
  260. func setupRouters(conf config.ConfStruct) *gin.Engine {
  261. router := gin.Default()
  262. if conf.Cors { // 是否开启cors中间件
  263. router.Use(CorsMiddleWare())
  264. }
  265. return router
  266. }
  267. func InitAPI(conf config.ConfStruct) {
  268. gin.SetMode(getGinMode(conf.Mode))
  269. router := setupRouters(conf)
  270. setJsRpcRouters(router) // 核心路由
  271. var sb strings.Builder
  272. sb.WriteString("当前监听地址:")
  273. sb.WriteString(conf.BasicListen)
  274. sb.WriteString(" ssl启用状态:")
  275. sb.WriteString(strconv.FormatBool(conf.HttpsServices.IsEnable))
  276. if conf.HttpsServices.IsEnable {
  277. sb.WriteString(" https监听地址:")
  278. sb.WriteString(conf.HttpsServices.HttpsListen)
  279. }
  280. log.Infoln(sb.String())
  281. err := router.Run(conf.BasicListen)
  282. if err != nil {
  283. log.Errorln("服务启动失败..")
  284. }
  285. }