ShellSession跟业务隔离

This commit is contained in:
xiongziliang
2017-12-01 11:42:49 +08:00
parent e2d509e63f
commit 473b9356a6
11 changed files with 183 additions and 1765 deletions

View File

@@ -1,107 +0,0 @@
/*
* MIT License
*
* 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.
*/
#include "CMD.h"
#include "ShellSession.h"
#include "Rtsp/RtspMediaSource.h"
#include "Rtmp/RtmpMediaSource.h"
using namespace ZL::Rtsp;
using namespace ZL::Rtmp;
namespace ZL {
namespace Shell {
mutex OptionParser::mtx_opt;
CMD::CMD() {
}
CMD::~CMD() {
}
CMD_help::CMD_help() {
parser.reset( new OptionParser(nullptr));
(*parser) << Option('c', "cmd", Option::ArgNone, "list all command", [](OutStream *stream,const char *arg) {
_StrPrinter printer;
for (auto &pr : ShellSession::g_mapCmd) {
printer << "\t" << pr.first << ":" << pr.second.description() << "\r\n";
}
stream->response(printer << endl);
return false;
}) << endl;
}
CMD_rtsp::CMD_rtsp() {
parser.reset(new OptionParser(nullptr));
(*parser) << Option('l', "list", Option::ArgNone, "list all media source of rtsp", [](OutStream *stream,const char *arg) {
_StrPrinter printer;
auto mediaSet = RtspMediaSource::getMediaSet();
for (auto &src : mediaSet) {
printer << "\t" << src << "\r\n";
}
stream->response(printer << endl);
return false;
}) << endl;
}
CMD_rtmp::CMD_rtmp() {
parser.reset(new OptionParser(nullptr));
(*parser) << Option('l', "list", Option::ArgNone, "list all media source of rtmp", [](OutStream *stream,const char *arg) {
_StrPrinter printer;
auto mediaSet = RtmpMediaSource::getMediaSet();
for (auto &src : mediaSet) {
printer << "\t" << src << "\r\n";
}
stream->response(printer << endl);
return false;
}) << endl;
}
} /* namespace Shell */
} /* namespace ZL */

View File

@@ -1,272 +0,0 @@
/*
* MIT License
*
* 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.
*/
#ifndef SRC_SHELL_CMD_H_
#define SRC_SHELL_CMD_H_
#if defined(_WIN32)
#include "win32/getopt.h"
#else
#include <getopt.h>
#endif //defined(_WIN32)
#include <string>
#include <vector>
#include <iostream>
#include <functional>
#include <unordered_map>
#include "Util/util.h"
#include "Util/logger.h"
using namespace std;
using namespace ZL::Util;
namespace ZL {
namespace Shell {
class OutStream {
public:
virtual ~OutStream() {
}
virtual void response(const string &str) =0;
virtual string &operator[](const string &) =0;
virtual int erase(const string &) =0;
};
class Option {
public:
typedef function<bool(OutStream *stream, const char *arg)> OptionHandler;
enum ArgType {
ArgNone = no_argument,
ArgRequired = required_argument,
ArgOptional = optional_argument
};
Option() {
}
Option(char _shortOpt, const char *_longOpt, enum ArgType _argType,
const char *_des, const OptionHandler &_cb) {
shortOpt = _shortOpt;
longOpt = _longOpt;
argType = _argType;
des = _des;
cb = _cb;
}
virtual ~Option() {
}
bool operator()(OutStream *stream, const char *arg){
return cb ? cb(stream,arg): true;
}
private:
friend class OptionParser;
char shortOpt;
string longOpt;
enum ArgType argType;
string des;
OptionHandler cb;
};
class OptionParser {
public:
typedef function< void(OutStream *stream, const unordered_multimap<char, string> &)> OptionCompleted;
OptionParser(const OptionCompleted &_cb) {
onCompleted = _cb;
helper = Option('h', "help", Option::ArgNone, "print this message", [this](OutStream *stream,const char *arg)->bool {
_StrPrinter printer;
for (auto &pr : options) {
printer<<"\t-"<<pr.first<<"\t--"<<pr.second.longOpt<<"\t"<<pr.second.des<<"\r\n";
}
auto sendStr=printer<<endl;
stream->response(sendStr);
return false;
});
}
virtual ~OptionParser() {
}
OptionParser &operator <<(const Option &option) {
options.emplace(option.shortOpt, option);
return *this;
}
void operator <<(ostream&(*f)(ostream&)) {
str_shortOpt.clear();
vec_longOpt.clear();
(*this) << helper;
struct option tmp;
for (auto &pr : options) {
//long opt
tmp.name = (char *)pr.second.longOpt.data();
tmp.has_arg = pr.second.argType;
tmp.flag = NULL;
tmp.val = pr.first;
vec_longOpt.emplace_back(tmp);
//short opt
str_shortOpt.push_back(pr.first);
switch (pr.second.argType) {
case Option::ArgRequired:
str_shortOpt.append(":");
break;
case Option::ArgOptional:
str_shortOpt.append("::");
break;
default:
break;
}
}
tmp.flag=0;
tmp.name=0;
tmp.has_arg=0;
tmp.val=0;
vec_longOpt.emplace_back(tmp);
}
bool operator ()(OutStream *stream, int argc, char *argv[]) {
lock_guard<mutex> lck(mtx_opt);
unordered_multimap<char, string> allArg;
int opt;
optind = 0;
while ((opt = getopt_long(argc, argv, &str_shortOpt[0], &vec_longOpt[0],NULL)) != -1) {
auto it = options.find(opt);
if (it == options.end()) {
string sendStr = StrPrinter << "\tUnrecognized option. Enter \"-h\" to get help.\r\n" << endl;
stream->response(sendStr);
return true;
}
allArg.emplace(it->first, optarg ? optarg : "");
if (!it->second(stream, optarg)) {
return true;
}
optarg = NULL;
}
if(!allArg.size() && options.size()){
helper(stream,"");
return true;
}
if (onCompleted) {
onCompleted(stream, allArg);
}
return true;
}
private:
unordered_map<char, Option> options;
OptionCompleted onCompleted;
vector<struct option> vec_longOpt;
string str_shortOpt;
Option helper;
static mutex mtx_opt;
};
class CMD {
public:
CMD();
virtual ~CMD();
virtual const char *description() const {
return "description";
}
bool operator ()(OutStream *stream, int argc, char *argv[]) const {
return (*parser)(stream, argc, argv);
}
protected:
mutable std::shared_ptr<OptionParser> parser;
};
template<typename C>
class CMDInstance {
public:
static CMD &Instance() {
static C instance;
return (CMD &) instance;
}
};
class CMD_help: public CMD {
public:
CMD_help();
virtual ~CMD_help() {
}
const char *description() const override {
return "打印帮助信息.";
}
};
class CMD_rtsp: public CMD {
public:
CMD_rtsp();
virtual ~CMD_rtsp() {
}
const char *description() const override {
return "查看rtsp服务器相关信息.";
}
};
class CMD_rtmp: public CMD {
public:
CMD_rtmp();
virtual ~CMD_rtmp() {
}
const char *description() const override {
return "查看rtmp服务器相关信息.";
}
};
} /* namespace Shell */
} /* namespace ZL */
#endif /* SRC_SHELL_CMD_H_ */

60
src/Shell/ShellCMD.cpp Normal file
View File

@@ -0,0 +1,60 @@
//
// Created by xzl on 2017/12/1.
//
#include "Util/CMD.h"
#include "Rtsp/RtspMediaSource.h"
#include "Rtmp/RtmpMediaSource.h"
using namespace ZL::Util;
using namespace ZL::Rtsp;
using namespace ZL::Rtmp;
namespace ZL {
namespace Shell {
class CMD_rtsp: public CMD {
public:
CMD_rtsp(){
_parser.reset(new OptionParser(nullptr));
(*_parser) << Option('l', "list", Option::ArgNone, nullptr,false, "list all media source of rtsp",
[](const std::shared_ptr<ostream> &stream, const string &arg) {
auto mediaSet = RtspMediaSource::getMediaSet();
for (auto &src : mediaSet) {
(*stream) << "\t" << src << "\r\n";
}
return false;
});
}
virtual ~CMD_rtsp() {}
const char *description() const override {
return "查看rtsp服务器相关信息.";
}
};
class CMD_rtmp: public CMD {
public:
CMD_rtmp(){
_parser.reset(new OptionParser(nullptr));
(*_parser) << Option('l', "list", Option::ArgNone,nullptr,false, "list all media source of rtmp",
[](const std::shared_ptr<ostream> &stream, const string &arg) {
auto mediaSet = RtmpMediaSource::getMediaSet();
for (auto &src : mediaSet) {
(*stream) << "\t" << src << "\r\n";
}
return false;
});
}
virtual ~CMD_rtmp() {}
const char *description() const override {
return "查看rtmp服务器相关信息.";
}
};
static onceToken s_token([]() {
REGIST_CMD(rtmp);
REGIST_CMD(rtsp);
}, nullptr);
}/* namespace Shell */
} /* namespace ZL */

View File

@@ -24,12 +24,10 @@
* SOFTWARE.
*/
#include "Common/config.h"
#include "ShellSession.h"
#include "Util/logger.h"
#include "Util/util.h"
#include "Common/config.h"
#include "Util/CMD.h"
#include "Util/onceToken.h"
#include "Util/mini.h"
using namespace ZL::Util;
@@ -37,20 +35,16 @@ namespace ZL {
namespace Shell {
unordered_map<string, string> ShellSession::g_mapUser;
map<string, CMD &> ShellSession::g_mapCmd;
string ShellSession::g_serverName;
#define SHELL_REG_CMD(cmd) g_mapCmd.emplace(#cmd,CMDInstance<CMD_##cmd>::Instance())
ShellSession::ShellSession(const std::shared_ptr<ThreadPool> &_th,
const Socket::Ptr &_sock) :
TcpLimitedSession(_th, _sock) {
static onceToken token([]() {
SHELL_REG_CMD(rtmp);
SHELL_REG_CMD(rtsp);
SHELL_REG_CMD(help);
g_serverName = mINI::Instance()[Config::Shell::kServerName];
}, nullptr);
requestLogin();
const Socket::Ptr &_sock) :
TcpLimitedSession(_th, _sock) {
static onceToken token([]() {
g_serverName = mINI::Instance()[Config::Shell::kServerName];
}, nullptr);
pleaseInputUser();
}
ShellSession::~ShellSession() {
@@ -77,16 +71,13 @@ void ShellSession::onRecv(const Socket::Buffer::Ptr&buf) {
while ((index = m_strRecvBuf.find("\r\n")) != std::string::npos) {
line = m_strRecvBuf.substr(0, index);
m_strRecvBuf.erase(0, index + 2);
if (!onProcessLine(line)) {
if (!onCommandLine(line)) {
shutdown();
return;
}
}
}
void ShellSession::onError(const SockException& err) {
}
void ShellSession::onManager() {
if (m_beatTicker.elapsedTime() > 1000 * 60 * 5) {
//5 miniutes for alive
@@ -94,66 +85,39 @@ void ShellSession::onManager() {
return;
}
}
static int getArgs(char *buf, char *argv[], int max_argc = 16) {
int argc = 0;
bool start = false;
int len = strlen(buf);
for (int i = 0; i < len; i++) {
if (argc == max_argc) {
break;
}
if (buf[i] != ' ' && buf[i] != '\t' && buf[i] != '\r'
&& buf[i] != '\n') {
if (!start) {
start = true;
argv[argc++] = buf + i;
}
} else {
buf[i] = '\0';
start = false;
}
}
return argc;
}
inline bool ShellSession::onProcessLine(const string& line) {
inline bool ShellSession::onCommandLine(const string& line) {
if (m_requestCB) {
bool ret = m_requestCB(line);
return ret;
}
//cmd process
char *argv[16];
int argc = getArgs((char *) line.data(), argv, sizeof(argv));
if (argc == 0) {
sendHead();
return true;
}
string cmd = argv[0];
auto it = g_mapCmd.find(cmd);
if (it == g_mapCmd.end()) {
auto sendStr = StrPrinter << "\tUnrecognized option:\"" << cmd << "\",Enter \"help\" to get help.\r\n" << endl;
send(sendStr);
sendHead();
return true;
}
bool ret = it->second(this, argc, argv);
sendHead();
return ret;
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;
}
inline void ShellSession::requestLogin() {
inline void ShellSession::pleaseInputUser() {
send("\033[0m");
send(StrPrinter << g_serverName << " login: " << endl);
m_requestCB = [this](const string &line) {
m_strUserName=line;
requestPasswd();
pleaseInputPasswd();
return true;
};
}
inline void ShellSession::requestPasswd() {
inline void ShellSession::pleaseInputPasswd() {
send("Password: \033[8m");
m_requestCB = [this](const string &passwd) {
if(!authUser(m_strUserName,passwd)) {
if(!onAuth(m_strUserName, passwd)) {
send(StrPrinter
<<"\033[0mPermission denied,"
<<" please try again.\r\n"
@@ -166,17 +130,17 @@ inline void ShellSession::requestPasswd() {
send("-----------------------------------------\r\n");
send(StrPrinter<<"欢迎来到"<<g_serverName<<", 你可输入\"help\"查看帮助.\r\n"<<endl);
send("-----------------------------------------\r\n");
sendHead();
printShellPrefix();
m_requestCB=nullptr;
return true;
};
}
inline void ShellSession::sendHead() {
send(StrPrinter << m_strUserName << "@" << g_serverName << ":" << endl);
inline void ShellSession::printShellPrefix() {
send(StrPrinter << m_strUserName << "@" << g_serverName << "# " << endl);
}
inline bool ShellSession::authUser(const string& user, const string& pwd) {
inline bool ShellSession::onAuth(const string &user, const string &pwd) {
auto it = g_mapUser.find(user);
if (it == g_mapUser.end()) {
//WarnL << user << " " << pwd;
@@ -185,6 +149,5 @@ inline bool ShellSession::authUser(const string& user, const string& pwd) {
return it->second == pwd;
}
}
/* namespace Shell */
}/* namespace Shell */
} /* namespace ZL */

View File

@@ -28,7 +28,6 @@
#define SRC_SHELL_SHELLSESSION_H_
#include <functional>
#include "CMD.h"
#include "Common/config.h"
#include "Util/TimeTicker.h"
#include "Network/TcpLimitedSession.h"
@@ -40,40 +39,31 @@ using namespace ZL::Network;
namespace ZL {
namespace Shell {
class ShellSession: public TcpLimitedSession<MAX_TCP_SESSION>, public OutStream {
class ShellSession: public TcpLimitedSession<MAX_TCP_SESSION> {
public:
ShellSession(const std::shared_ptr<ThreadPool> &_th, const Socket::Ptr &_sock);
virtual ~ShellSession();
void onRecv(const Socket::Buffer::Ptr &) override;
void onError(const SockException &err) override;
void onError(const SockException &err) override {};
void onManager() override;
static void addUser(const string &userName,const string &userPwd){
g_mapUser[userName] = userPwd;
}
private:
friend class CMD_help;
inline bool onProcessLine(const string &);
inline void requestLogin();
inline void requestPasswd();
inline void sendHead();
inline bool authUser(const string &user, const string &pwd);
void response(const string &str) override{
send(str);
}
string &operator[](const string &key) override{
return m_mapConfig[key];
}
int erase(const string &key) override{
return m_mapConfig.erase(key);
}
inline bool onCommandLine(const string &);
inline bool onAuth(const string &user, const string &pwd);
inline void pleaseInputUser();
inline void pleaseInputPasswd();
inline void printShellPrefix();
function<bool(const string &)> m_requestCB;
string m_strRecvBuf;
Ticker m_beatTicker;
string m_strUserName;
unordered_map<string,string> m_mapConfig;
static unordered_map<string, string> g_mapUser;
static map<string, CMD&> g_mapCmd;
static string g_serverName;
};