handlers.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. // Copyright 2019 Yunion
  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 service
  15. import (
  16. "context"
  17. "encoding/base64"
  18. "fmt"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "strconv"
  23. "strings"
  24. "yunion.io/x/jsonutils"
  25. "yunion.io/x/log"
  26. "yunion.io/x/pkg/errors"
  27. "yunion.io/x/pkg/gotypes"
  28. "yunion.io/x/pkg/util/httputils"
  29. "yunion.io/x/pkg/util/regutils"
  30. agapi "yunion.io/x/onecloud/pkg/apis/apigateway"
  31. compute_api "yunion.io/x/onecloud/pkg/apis/compute"
  32. webconsole_api "yunion.io/x/onecloud/pkg/apis/webconsole"
  33. "yunion.io/x/onecloud/pkg/appsrv"
  34. "yunion.io/x/onecloud/pkg/appsrv/dispatcher"
  35. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  36. "yunion.io/x/onecloud/pkg/cloudcommon/policy"
  37. "yunion.io/x/onecloud/pkg/httperrors"
  38. "yunion.io/x/onecloud/pkg/mcclient"
  39. "yunion.io/x/onecloud/pkg/mcclient/auth"
  40. modules "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
  41. "yunion.io/x/onecloud/pkg/mcclient/modules/k8s"
  42. "yunion.io/x/onecloud/pkg/util/netutils2"
  43. "yunion.io/x/onecloud/pkg/util/seclib2"
  44. "yunion.io/x/onecloud/pkg/webconsole/command"
  45. "yunion.io/x/onecloud/pkg/webconsole/models"
  46. o "yunion.io/x/onecloud/pkg/webconsole/options"
  47. "yunion.io/x/onecloud/pkg/webconsole/server"
  48. "yunion.io/x/onecloud/pkg/webconsole/session"
  49. )
  50. const (
  51. ApiPathPrefix = "/webconsole/"
  52. ConnectPathPrefix = "/connect/"
  53. WebsockifyPathPrefix = "/websockify/"
  54. WebsocketProxyPathPrefix = "/wsproxy/"
  55. )
  56. func initHandlers(app *appsrv.Application, isSlave bool) {
  57. app.AddHandler("GET", ApiPathPrefix+"sftp/<session-id>/list", server.HandleSftpList)
  58. app.AddHandler("GET", ApiPathPrefix+"sftp/<session-id>/download", server.HandleSftpDownload)
  59. if !isSlave {
  60. app.AddHandler("POST", ApiPathPrefix+"k8s/<podName>/shell", auth.Authenticate(handleK8sShell))
  61. app.AddHandler("POST", ApiPathPrefix+"climc/shell", auth.Authenticate(handleClimcShell))
  62. app.AddHandler("POST", ApiPathPrefix+"k8s/<podName>/log", auth.Authenticate(handleK8sLog))
  63. app.AddHandler("POST", ApiPathPrefix+"baremetal/<id>", auth.Authenticate(handleBaremetalShell))
  64. app.AddHandler("POST", ApiPathPrefix+"ssh/<ip>", auth.Authenticate(handleSshShell))
  65. app.AddHandler("POST", ApiPathPrefix+"server/<id>", auth.Authenticate(handleServerRemoteConsole))
  66. app.AddHandler("POST", ApiPathPrefix+"adb/<id>/shell", auth.Authenticate(handleAdbShell))
  67. app.AddHandler("POST", ApiPathPrefix+"server-rdp/<id>", auth.Authenticate(handleServerRemoteRDPConsole))
  68. app.AddHandler("POST", ApiPathPrefix+"sftp/<session-id>/upload", server.HandleSftpUpload)
  69. }
  70. for _, man := range []db.IModelManager{
  71. models.GetCommandLogManager(),
  72. } {
  73. db.RegisterModelManager(man)
  74. handler := db.NewModelHandler(man)
  75. dispatcher.AddModelDispatcher(ApiPathPrefix, app, handler, isSlave)
  76. }
  77. }
  78. func fetchK8sEnv(ctx context.Context, w http.ResponseWriter, r *http.Request) (*command.K8sEnv, error) {
  79. params, _, body := appsrv.FetchEnv(ctx, w, r)
  80. if !gotypes.IsNil(body) && body.Contains("webconsole") {
  81. body, _ = body.Get("webconsole")
  82. }
  83. k8sReq := webconsole_api.SK8sRequest{}
  84. err := body.Unmarshal(&k8sReq)
  85. if err != nil {
  86. return nil, errors.Wrap(err, "body.Unmarshal SK8sRequest")
  87. }
  88. if k8sReq.Cluster == "" {
  89. k8sReq.Cluster = "default"
  90. }
  91. if k8sReq.Namespace == "" {
  92. k8sReq.Namespace = "default"
  93. }
  94. podName := params["<podName>"]
  95. adminSession := auth.GetAdminSession(ctx, o.Options.Region)
  96. data := jsonutils.NewDict()
  97. ret, err := k8s.KubeClusters.GetSpecific(adminSession, k8sReq.Cluster, "kubeconfig", data)
  98. if err != nil {
  99. return nil, err
  100. }
  101. conf, err := ret.GetString("kubeconfig")
  102. if err != nil {
  103. return nil, httperrors.NewNotFoundError("Not found cluster %q kubeconfig", k8sReq.Cluster)
  104. }
  105. f, err := os.CreateTemp("", "kubeconfig-")
  106. if err != nil {
  107. return nil, fmt.Errorf("Save kubeconfig error: %v", err)
  108. }
  109. defer f.Close()
  110. f.WriteString(conf)
  111. return &command.K8sEnv{
  112. Session: adminSession,
  113. Cluster: k8sReq.Cluster,
  114. Namespace: k8sReq.Namespace,
  115. Pod: podName,
  116. Container: k8sReq.Container,
  117. Kubeconfig: f.Name(),
  118. Data: body,
  119. }, nil
  120. }
  121. type CloudEnv struct {
  122. ClientSessin *mcclient.ClientSession
  123. Params map[string]string
  124. Query jsonutils.JSONObject
  125. Body jsonutils.JSONObject
  126. Ctx context.Context
  127. }
  128. func fetchCloudEnv(ctx context.Context, w http.ResponseWriter, r *http.Request) (*CloudEnv, error) {
  129. params, query, body := appsrv.FetchEnv(ctx, w, r)
  130. userCred := auth.FetchUserCredential(ctx, policy.FilterPolicyCredential)
  131. if userCred == nil {
  132. return nil, httperrors.NewUnauthorizedError("No token founded")
  133. }
  134. if !gotypes.IsNil(body) && body.Contains("webconsole") {
  135. body, _ = body.Get("webconsole")
  136. }
  137. s := auth.Client().NewSession(ctx, o.Options.Region, "", "internal", userCred)
  138. return &CloudEnv{
  139. ClientSessin: s,
  140. Params: params,
  141. Query: query,
  142. Body: body,
  143. Ctx: ctx,
  144. }, nil
  145. }
  146. func handleK8sCommand(
  147. ctx context.Context,
  148. w http.ResponseWriter,
  149. r *http.Request,
  150. cmdFactory func(*command.K8sEnv) command.ICommand,
  151. ) {
  152. env, err := fetchK8sEnv(ctx, w, r)
  153. if err != nil {
  154. httperrors.GeneralServerError(ctx, w, err)
  155. return
  156. }
  157. cmd := cmdFactory(env)
  158. handleCommandSession(ctx, cmd, w)
  159. }
  160. func handleK8sShell(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  161. handleK8sCommand(ctx, w, r, command.NewPodBashCommand)
  162. }
  163. func handleK8sLog(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  164. handleK8sCommand(ctx, w, r, command.NewPodLogCommand)
  165. }
  166. func handleSshShell(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  167. env, err := fetchCloudEnv(ctx, w, r)
  168. if err != nil {
  169. httperrors.GeneralServerError(ctx, w, err)
  170. return
  171. }
  172. sshConnInfo := session.SSshConnectionInfo{}
  173. if !gotypes.IsNil(env.Body) {
  174. err = env.Body.Unmarshal(&sshConnInfo)
  175. if err != nil {
  176. httperrors.InputParameterError(ctx, w, "unmarshal error: %s", err.Error())
  177. return
  178. }
  179. }
  180. idStr := env.Params["<ip>"]
  181. if !regutils.MatchIPAddr(idStr) {
  182. var tryServer = func() error {
  183. ip, port, guestDetails, err := session.ResolveServerSSHIPPortById(ctx, env.ClientSessin, idStr, sshConnInfo.IP, sshConnInfo.Port)
  184. if err != nil {
  185. return err
  186. }
  187. sshConnInfo.IP = ip
  188. sshConnInfo.Port = port
  189. sshConnInfo.GuestDetails = guestDetails
  190. return nil
  191. }
  192. var tryHost = func() error {
  193. ip, port, hostDetails, err := session.ResolveHostSSHIPPortById(ctx, env.ClientSessin, idStr, sshConnInfo.IP, sshConnInfo.Port)
  194. if err != nil {
  195. return err
  196. }
  197. sshConnInfo.IP = ip
  198. sshConnInfo.Port = port
  199. sshConnInfo.HostDetails = hostDetails
  200. return nil
  201. }
  202. switch sshConnInfo.ResourceType {
  203. case "server":
  204. err = tryServer()
  205. if err != nil {
  206. httperrors.GeneralServerError(ctx, w, err)
  207. return
  208. }
  209. case "host":
  210. err = tryHost()
  211. if err != nil {
  212. httperrors.GeneralServerError(ctx, w, err)
  213. return
  214. }
  215. default:
  216. for _, try := range []func() error{
  217. tryServer,
  218. tryHost,
  219. } {
  220. err = try()
  221. if err == nil {
  222. s := session.NewSshSession(ctx, env.ClientSessin, sshConnInfo)
  223. handleSshSession(ctx, s, w)
  224. return
  225. }
  226. }
  227. httperrors.NewResourceNotFoundError("%s not found", idStr)
  228. return
  229. }
  230. } else {
  231. // directly ssh IP should be deprecated gradually
  232. sshConnInfo.IP = idStr
  233. }
  234. s := session.NewSshSession(ctx, env.ClientSessin, sshConnInfo)
  235. handleSshSession(ctx, s, w)
  236. }
  237. func handleSshSession(ctx context.Context, session *session.SSshSession, w http.ResponseWriter) {
  238. log.Infof("handleSshSession %s", jsonutils.Marshal(session).String())
  239. handleDataSession(ctx, session, w, "ws", nil, false)
  240. }
  241. func handleBaremetalShell(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  242. env, err := fetchCloudEnv(ctx, w, r)
  243. if err != nil {
  244. httperrors.GeneralServerError(ctx, w, err)
  245. return
  246. }
  247. hostId := env.Params["<id>"]
  248. ret, err := modules.Hosts.GetSpecific(env.ClientSessin, hostId, "ipmi", nil)
  249. if err != nil {
  250. httperrors.GeneralServerError(ctx, w, err)
  251. return
  252. }
  253. info := command.IpmiInfo{}
  254. err = ret.Unmarshal(&info)
  255. if err != nil {
  256. httperrors.GeneralServerError(ctx, w, err)
  257. return
  258. }
  259. cmd, err := command.NewIpmitoolSolCommand(&info, env.ClientSessin)
  260. if err != nil {
  261. httperrors.GeneralServerError(ctx, w, err)
  262. return
  263. }
  264. handleCommandSession(ctx, cmd, w)
  265. }
  266. func handleClimcShell(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  267. env, err := fetchCloudEnv(ctx, w, r)
  268. if err != nil {
  269. httperrors.GeneralServerError(ctx, w, err)
  270. return
  271. }
  272. info := webconsole_api.ClimcSshInfo{}
  273. err = env.Body.Unmarshal(&info)
  274. if err != nil {
  275. httperrors.GeneralServerError(ctx, w, err)
  276. return
  277. }
  278. cmd, err := command.NewClimcSshCommand(&info, env.ClientSessin)
  279. if err != nil {
  280. httperrors.GeneralServerError(ctx, w, err)
  281. return
  282. }
  283. handleCommandSession(ctx, cmd, w)
  284. }
  285. func handleServerRemoteConsole(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  286. env, err := fetchCloudEnv(ctx, w, r)
  287. if err != nil {
  288. httperrors.GeneralServerError(ctx, w, err)
  289. return
  290. }
  291. query := env.Body
  292. srvId := env.Params["<id>"]
  293. info, err := session.NewRemoteConsoleInfoByCloud(env.ClientSessin, srvId, query)
  294. if err != nil {
  295. httperrors.GeneralServerError(ctx, w, err)
  296. return
  297. }
  298. switch info.Protocol {
  299. case session.ALIYUN, session.QCLOUD, session.OPENSTACK,
  300. session.VMRC, session.ZSTACK, session.CTYUN,
  301. session.HUAWEI, session.HCS, session.APSARA,
  302. session.JDCLOUD, session.CLOUDPODS, session.PROXMOX,
  303. session.VOLCENGINE, session.BAIDU, session.CNWARE, session.KSYUN, session.ECLOUD:
  304. responsePublicCloudConsole(ctx, info, w)
  305. case session.VNC:
  306. handleDataSession(ctx, info, w, "no-vnc", url.Values{"password": {info.GetPassword()}}, true)
  307. case session.SPICE:
  308. handleDataSession(ctx, info, w, "spice", url.Values{"password": {info.GetPassword()}}, true)
  309. case session.WMKS:
  310. handleDataSession(ctx, info, w, "wmks", url.Values{"password": {info.GetPassword()}}, true)
  311. default:
  312. httperrors.NotAcceptableError(ctx, w, "Unspported remote console protocol: %s", info.Protocol)
  313. }
  314. }
  315. func handleServerRemoteRDPConsole(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  316. env, err := fetchCloudEnv(ctx, w, r)
  317. if err != nil {
  318. httperrors.GeneralServerError(ctx, w, err)
  319. return
  320. }
  321. query := env.Body
  322. srvId := env.Params["<id>"]
  323. info, err := session.NewRemoteRDPConsoleInfoByCloud(ctx, env.ClientSessin, srvId, query)
  324. if err != nil {
  325. httperrors.GeneralServerError(ctx, w, err)
  326. return
  327. }
  328. handleDataSession(ctx, info, w, "rdp", url.Values{"password": {info.GetPassword()}}, false)
  329. }
  330. func responsePublicCloudConsole(ctx context.Context, info *session.RemoteConsoleInfo, w http.ResponseWriter) {
  331. params, err := info.GetConnectParams()
  332. if err != nil {
  333. httperrors.GeneralServerError(ctx, w, err)
  334. return
  335. }
  336. resp := webconsole_api.ServerRemoteConsoleResponse{
  337. ConnectParams: params,
  338. }
  339. sendJSON(w, resp.JSON(resp))
  340. }
  341. func handleDataSession(ctx context.Context, sData session.ISessionData, w http.ResponseWriter, base string, connParams url.Values, b64Encode bool) {
  342. s, err := session.Manager.Save(sData)
  343. if err != nil {
  344. httperrors.GeneralServerError(ctx, w, err)
  345. return
  346. }
  347. dispInfo, err := sData.GetDisplayInfo(ctx)
  348. if err != nil {
  349. httperrors.GeneralServerError(ctx, w, err)
  350. return
  351. }
  352. params, err := s.GetConnectParams(connParams, dispInfo)
  353. if err != nil {
  354. httperrors.GeneralServerError(ctx, w, err)
  355. return
  356. }
  357. var accessUrl string
  358. {
  359. connParams, err := seclib2.AES_256.CbcEncodeBase64([]byte(params), []byte(agapi.DefaultEncryptKey))
  360. if err != nil {
  361. httperrors.GeneralServerError(ctx, w, err)
  362. return
  363. }
  364. dataVal := url.Values{}
  365. dataVal.Add("data", connParams)
  366. accessUrl = httputils.JoinPath(o.Options.ApiServer, fmt.Sprintf("web-console/%s?%s", base, dataVal.Encode()))
  367. }
  368. if b64Encode {
  369. params = base64.StdEncoding.EncodeToString([]byte(params))
  370. }
  371. resp := webconsole_api.ServerRemoteConsoleResponse{
  372. AccessUrl: accessUrl,
  373. ConnectParams: params,
  374. Session: s.Id,
  375. }
  376. sendJSON(w, resp.JSON(resp))
  377. }
  378. func handleCommandSession(ctx context.Context, cmd command.ICommand, w http.ResponseWriter) {
  379. handleDataSession(ctx, session.WrapCommandSession(cmd), w, "tty", nil, false)
  380. }
  381. func sendJSON(w http.ResponseWriter, body jsonutils.JSONObject) {
  382. ret := jsonutils.NewDict()
  383. if body != nil {
  384. ret.Add(body, "webconsole")
  385. }
  386. appsrv.SendJSON(w, ret)
  387. }
  388. func handleAdbShell(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  389. env, err := fetchCloudEnv(ctx, w, r)
  390. if err != nil {
  391. httperrors.GeneralServerError(ctx, w, err)
  392. return
  393. }
  394. serverId := env.Params["<id>"]
  395. serverDetails := compute_api.ServerDetails{}
  396. resp, err := modules.Servers.GetById(env.ClientSessin, serverId, nil)
  397. if err != nil {
  398. httperrors.GeneralServerError(ctx, w, err)
  399. return
  400. }
  401. err = resp.Unmarshal(&serverDetails)
  402. if err != nil {
  403. httperrors.GeneralServerError(ctx, w, err)
  404. return
  405. }
  406. phoneIp := ""
  407. adbPort := -1
  408. connStr, _ := env.Body.GetString("conn")
  409. if len(connStr) > 0 {
  410. parts := strings.Split(connStr, ":")
  411. if len(parts) > 0 {
  412. phoneIp = parts[0]
  413. if len(parts) > 1 {
  414. adbPort, _ = strconv.Atoi(parts[1])
  415. }
  416. if adbPort == 0 {
  417. adbPort = 5555
  418. }
  419. }
  420. }
  421. if len(phoneIp) == 0 {
  422. // fallback
  423. if len(serverDetails.Nics) > 0 {
  424. phoneIp = serverDetails.Nics[0].IpAddr
  425. portMaps := serverDetails.Nics[0].PortMappings
  426. for i := range portMaps {
  427. portMap := portMaps[i]
  428. if portMap.Port == 5555 && portMap.Protocol == "tcp" {
  429. adbPort = *portMap.HostPort
  430. break
  431. }
  432. }
  433. var errMsgs []string
  434. if !regutils.MatchIP4Addr(phoneIp) {
  435. errMsgs = append(errMsgs, "invalid phone IP")
  436. }
  437. if adbPort < 0 {
  438. errMsgs = append(errMsgs, "adb port not found")
  439. }
  440. if len(errMsgs) > 0 {
  441. httperrors.GeneralServerError(ctx, w, httperrors.NewNotSupportedError("%s", strings.Join(errMsgs, ";")))
  442. return
  443. }
  444. } else {
  445. httperrors.GeneralServerError(ctx, w, httperrors.NewNotSupportedError("porting_mapping not supported"))
  446. return
  447. }
  448. {
  449. // test phoneIP is accessible
  450. err := netutils2.TestTcpPort(phoneIp, 5555, 3, 3)
  451. if err != nil {
  452. log.Errorf("TestTcpPort %s:%d fail %s", phoneIp, 5555, err)
  453. phoneIp = serverDetails.HostEIP
  454. if len(phoneIp) == 0 {
  455. phoneIp = serverDetails.HostAccessIp
  456. }
  457. } else {
  458. adbPort = 5555
  459. }
  460. }
  461. }
  462. info := command.SAdbShellInfo{
  463. HostIp: phoneIp,
  464. HostPort: adbPort,
  465. }
  466. cmd, err := command.NewAdbShellCommand(&info, env.ClientSessin)
  467. if err != nil {
  468. httperrors.GeneralServerError(ctx, w, err)
  469. return
  470. }
  471. handleCommandSession(ctx, cmd, w)
  472. }