ShellSession.cpp 5.21 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2
 * MIT License
xzl committed
3
 *
xiongziliang committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
xzl committed
25 26 27
 */

#include "ShellSession.h"
28 29
#include "Common/config.h"
#include "Util/CMD.h"
xzl committed
30
#include "Util/onceToken.h"
31
#include "Util/NoticeCenter.h"
xzl committed
32

33
using namespace Config;
xzl committed
34 35 36 37 38 39
using namespace ZL::Util;

namespace ZL {
namespace Shell {

ShellSession::ShellSession(const std::shared_ptr<ThreadPool> &_th,
40
                           const Socket::Ptr &_sock) :
41
        TcpSession(_th, _sock) {
42
    pleaseInputUser();
xzl committed
43 44 45 46 47
}

ShellSession::~ShellSession() {
}

48
void ShellSession::onRecv(const Buffer::Ptr&buf) {
xzl committed
49
	//DebugL << hexdump(buf->data(), buf->size());
50 51
    GET_CONFIG_AND_REGISTER(uint32_t,maxReqSize,Config::Shell::kMaxReqSize);
    if (m_strRecvBuf.size() + buf->size() >= maxReqSize) {
xzl committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
		WarnL << "接收缓冲区溢出!";
		shutdown();
		return;
	}
	m_beatTicker.resetTime();
	m_strRecvBuf.append(buf->data(), buf->size());
	if (m_strRecvBuf.find("\xff\xf4\xff\0xfd\x06") != std::string::npos) {
		WarnL << "收到Ctrl+C.";
		send("\033[0m\r\n	Bye bye!\r\n");
		shutdown();
		return;
	}
	size_t index;
	string line;
	while ((index = m_strRecvBuf.find("\r\n")) != std::string::npos) {
		line = m_strRecvBuf.substr(0, index);
		m_strRecvBuf.erase(0, index + 2);
69
		if (!onCommandLine(line)) {
xzl committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83
			shutdown();
			return;
		}
	}
}

void ShellSession::onManager() {
	if (m_beatTicker.elapsedTime() > 1000 * 60 * 5) {
		//5 miniutes for alive
		shutdown();
		return;
	}
}

84
inline bool ShellSession::onCommandLine(const string& line) {
85 86 87
    auto loginInterceptor = m_loginInterceptor;
    if (loginInterceptor) {
		bool ret = loginInterceptor(line);
xzl committed
88 89
		return ret;
	}
90 91 92 93 94 95 96 97 98 99 100 101
    try {
        std::shared_ptr<stringstream> ss(new stringstream);
        CMDRegister::Instance()(line,ss);
        send(ss->str());
    }catch(ExitException &ex){
        return false;
    }catch(std::exception &ex){
        send(ex.what());
        send("\r\n");
    }
    printShellPrefix();
	return true;
xzl committed
102 103
}

104
inline void ShellSession::pleaseInputUser() {
xzl committed
105
	send("\033[0m");
106
	send(StrPrinter << SERVER_NAME << " login: " << endl);
107 108
	m_loginInterceptor = [this](const string &user_name) {
		m_strUserName=user_name;
109
        pleaseInputPasswd();
xzl committed
110 111 112
		return true;
	};
}
113
inline void ShellSession::pleaseInputPasswd() {
xzl committed
114
	send("Password: \033[8m");
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	m_loginInterceptor = [this](const string &passwd) {
        auto onAuth = [this](const string &errMessage){
            if(!errMessage.empty()){
                //鉴权失败
                send(StrPrinter
                     <<"\033[0mAuth failed("
                     << errMessage
                     <<"), please try again.\r\n"
                     <<m_strUserName<<"@"<<SERVER_NAME
                     <<"'s password: \033[8m"
                     <<endl);
                return;
            }
            send("\033[0m");
            send("-----------------------------------------\r\n");
            send(StrPrinter<<"欢迎来到"<<SERVER_NAME<<", 你可输入\"help\"查看帮助.\r\n"<<endl);
            send("-----------------------------------------\r\n");
            printShellPrefix();
            m_loginInterceptor=nullptr;
        };

        weak_ptr<ShellSession> weakSelf = dynamic_pointer_cast<ShellSession>(shared_from_this());
        Broadcast::AuthInvoker invoker = [weakSelf,onAuth](const string &errMessage){
            auto strongSelf =  weakSelf.lock();
            if(!strongSelf){
                return;
            }
            strongSelf->async([errMessage,weakSelf,onAuth](){
                auto strongSelf =  weakSelf.lock();
                if(!strongSelf){
                    return;
                }
                onAuth(errMessage);
            });
        };

151
        auto flag = NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastShellLogin,m_strUserName,passwd,invoker,*this);
152 153 154 155
        if(!flag){
            //如果无人监听shell登录事件,那么默认shell无法登录
            onAuth("please listen kBroadcastShellLogin event");
        }
xzl committed
156 157 158 159
		return true;
	};
}

160
inline void ShellSession::printShellPrefix() {
161
	send(StrPrinter << m_strUserName << "@" << SERVER_NAME << "# " << endl);
xzl committed
162 163
}

164
}/* namespace Shell */
xzl committed
165
} /* namespace ZL */