Files
hsa/code-server-like/app/sockets/terminal_service.py

252 lines
11 KiB
Python

import os
import select
import time
import uuid
import subprocess
import threading
from flask import Blueprint, request, current_app, session
from flask_socketio import Namespace, join_room, leave_room, emit, SocketIO, rooms, disconnect
from threading import Thread
import sys
from ..extensions import socketio
import pty
import termios
import struct
import fcntl
import psutil
TERM_INIT_CONFIG = {
# instead of local server runnning this web terminal service
# "domain" is the target that you want to access through local server (with this web terminal)
# and before doing so - make sure you have username and port (on the "domain") to implement remote access
'domain': '127.0.0.1', # or ip address like 192.168.10.11
'client_path': {
'telnet': '/usr/bin/telnet', # confirmed location of your client binary (with cmd like 'which telnet')
'ssh': '/usr/bin/ssh'
}
}
terminal_bp = Blueprint('terminal', __name__, url_prefix='/vsc-like')
def set_winsize(fd, row, col, xpix=0, ypix=0):
try:
winsize = struct.pack("HHHH", row, col, xpix, ypix)
fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
except (OSError, IOError):
# File descriptor closed or invalid, do nothing
pass
def read_and_forward_pty_output(fd=None, pid=None, room_id=None,namespace=None):
"""
read data on pty master from the pty slave, and emit to the web terminal visitor
"""
max_read_bytes = 1024 * 20
timeout=0.1
try:
while True:
socketio.sleep(timeout)
timeout=min(timeout*2, 0.4)
# using flask default web server, or uwsgi production web server
# when the child process is terminated, it will not disappear from linux process list
# and keep staying as a zombie process until the parent exits.
try:
child_process = psutil.Process(pid)
except psutil.NoSuchProcess as err:
# Process already terminated, clean up any zombie
try:
os.waitpid(pid, os.WNOHANG)
except Exception:
pass
return
if child_process.status() not in ('running', 'sleeping'):
# Process is terminated or in other state, clean up
try:
child_process.wait(timeout=1)
except Exception:
try:
os.waitpid(pid, os.WNOHANG)
except Exception:
pass
return
if fd:
timeout_sec = 0
try:
# Check if file descriptor is still valid by trying to select on it
(data_ready, _, _) = select.select([fd], [], [], timeout_sec)
if data_ready:
timeout=0.1
try:
output = os.read(fd, max_read_bytes).decode()
except (OSError, IOError, EOFError) as err:
# File descriptor closed or other IO error, exit gracefully
return
except UnicodeDecodeError as err:
output = """
***AQUI WEB TERM ERR***
Unicode decode error: {}
***********************
""".format(err)
# the key for different visitor to get different terminal (instead of mixing up)
# is to let the background task push pty response to each one's own (default) ROOM!
try:
namespace.emit("pty_output", {"output": output}, room=room_id)
except Exception:
# If emit fails, the client is probably disconnected, exit
return
except (OSError, IOError) as err:
# File descriptor closed or invalid, exit gracefully
return
except Exception as e:
# Catch any other unexpected exceptions to prevent server crash
pass
finally:
# Clean up file descriptor if it's open
if fd:
try:
os.close(fd)
except Exception:
pass
class VSCLikeNameSpace(Namespace):
def on_connect(self):
"""new client connected"""
if session.get('terminal_config', {}).get('child_pid', None):
print(session['terminal_config']['child_pid'])
# already started child process, don't start another
return
# create child process attached to a pty we can read from and write to
(child_pid, fd) = pty.fork()
lesson_path = session.get('path')
if child_pid == 0:
# this is the child process fork.
# anything printed here will show up in the pty, including the output
# of this subprocess
# subprocess.run('bash')
term_type = session.get('terminal_config').get('term_type')
path = TERM_INIT_CONFIG.get('client_path', {}).get(term_type, None)
if not path:
print("Can't locate {} binary, exit".format(term_type))
disconnect()
if term_type == 'telnet':
# switch to the right location of your telnet binary (example comes from OSX which got telnet from brew)
# or you can also make work like auto-detection, or manually but configurable
os.execl(path, 'telnet', '-l', session['terminal_config']['username'],
session['terminal_config']['domain'], '{}'.format(session['terminal_config']['port']))
elif term_type == 'ssh':
os.execl(path,'ssh', '-p','22',
#'{}'.format(session['terminal_config']['port']),
'{}@{}'.format(session['terminal_config']['username'], session['terminal_config']['domain']))
else:
current_app.logger.debug("wrong term type {}".format(term_type))
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
else:
session['terminal_config']['fd'] = fd
session['terminal_config']['child_pid'] = child_pid
session['terminal_config']['room_id'] = rooms()[0]
session.modified = True
set_winsize(fd, 50, 50)
current_app.logger.debug("child pid = {}".format(child_pid))
current_app.logger.debug("rooms of this session = {}".format(rooms()))
socketio.start_background_task(read_and_forward_pty_output, fd, child_pid, rooms()[0],self)
current_app.logger.debug("background task running")
# print(session)
def on_pty_input(self, data):
"""write to the child pty, which now is the ssh process from this machine to the 'domain' configured
"""
print(f"get data {data}")
try:
child_process = psutil.Process(session.get('terminal_config').get('child_pid'))
except psutil.NoSuchProcess as err:
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
if child_process.status() not in ('running', 'sleeping'):
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
# print(session)
# print(data, 'from input')
fd = session.get('terminal_config').get('fd')
if fd:
# print("writing to ptd: %s" % data["input"])
# os.write(fd, data["input"].encode('ascii'))
try:
os.write(fd, data["input"].encode())
except (OSError, IOError):
# File descriptor closed or invalid, clean up
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
def on_resize(self, data):
try:
child_process = psutil.Process(session.get('terminal_config').get('child_pid'))
except psutil.NoSuchProcess as err:
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
if child_process.status() not in ('running', 'sleeping'):
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
fd = session.get('terminal_config').get('fd')
if fd:
# 检查文件描述符是否有效
try:
# 尝试一个简单的操作来检查文件描述符是否有效
os.fstat(fd)
set_winsize(fd, data["rows"], data["cols"])
except (OSError, IOError):
# 文件描述符无效,清理资源
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
def on_disconnect(self):
terminal_config = session.get('terminal_config', {})
child_pid = terminal_config.get('child_pid')
fd = terminal_config.get('fd')
# 先关闭文件描述符,避免其他操作尝试使用无效的文件描述符
if fd:
try:
os.close(fd)
except Exception:
pass
if child_pid:
try:
child_process = psutil.Process(child_pid)
if child_process.status() in ('running', 'sleeping'):
# if visitor just close the browser tab then left alone the pty here
# it should be terminated by the parent process after
child_process.terminate()
# Wait for the process to terminate and collect its exit status
child_process.wait(timeout=2)
current_app.logger.debug('user left the pty alone, terminated and waited')
except psutil.NoSuchProcess as err:
# Process already terminated, try to wait anyway to clean up any zombie
try:
os.waitpid(child_pid, os.WNOHANG)
except Exception:
pass
except psutil.TimeoutExpired:
# If process didn't terminate in time, kill it forcefully
try:
child_process.kill()
child_process.wait(timeout=1)
except Exception:
pass
except Exception as err:
current_app.logger.error(f'Error terminating process: {err}')
# Reset session config
session['terminal_config'] = TERM_INIT_CONFIG
current_app.logger.debug('Client disconnected')