diff --git a/CMakeLists.txt b/CMakeLists.txt index 56a4810..d5f33be 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ set(TARS_VERSION "2.0.0") add_definitions(-DTARS_VERSION="${TARS_VERSION}") set(TARS_MYSQL 1) add_definitions(-DTARS_MYSQL=${TARS_MYSQL}) -set(TARS_SSL 0) +set(TARS_SSL 1) add_definitions(-DTARS_SSL=${TARS_SSL}) set(TARS_HTTP2 0) add_definitions(-DTARS_HTTP2=${TARS_HTTP2}) @@ -53,33 +53,52 @@ set(CMAKE_INSTALL_PREFIX ${INSTALL_PREFIX}) #------------------------------------------------------------- set(APP_LIBRARIES) +set(OPEN_MYSQL "OFF") +set(OPEN_NGHTTP2 "OFF") +set(OPEN_SSL "OFF") +set(OPEN_ZLIB "OFF") +set(OPEN_PROTOBUF "OFF") set(THIRDPARTY_PATH "${CMAKE_BINARY_DIR}/src") +if(TARS_MYSQL) + set(OPEN_MYSQL "ON") + set(MYSQL_DIR_INC "${THIRDPARTY_PATH}/mysql-lib/include") + set(MYSQL_DIR_LIB "${THIRDPARTY_PATH}/mysql-lib/libmysql") + include_directories(${MYSQL_DIR_INC}) + link_directories(${MYSQL_DIR_LIB}) +endif() -set(MYSQL_DIR_INC "${THIRDPARTY_PATH}/mysql-lib/include") -set(MYSQL_DIR_LIB "${THIRDPARTY_PATH}/mysql-lib/libmysql") -include_directories(${MYSQL_DIR_INC}) -link_directories(${MYSQL_DIR_LIB}) +if(TARS_PROTOBUF) + set(OPEN_PROTOBUF "ON") + set(PROTOBUF_DIR_INC "${THIRDPARTY_PATH}/protobuf-lib/src") + set(PROTOBUF_DIR_LIB "${THIRDPARTY_PATH}/protobuf-lib") + include_directories(${PROTOBUF_DIR_INC}) + link_directories(${PROTOBUF_DIR_LIB}) +endif() -set(PROTOBUF_DIR_INC "${THIRDPARTY_PATH}/protobuf-lib/src") -set(PROTOBUF_DIR_LIB "${THIRDPARTY_PATH}/protobuf-lib") -include_directories(${PROTOBUF_DIR_INC}) -link_directories(${PROTOBUF_DIR_LIB}) +if(TARS_ZLIB) + set(OPEN_ZLIB "ON") + set(ZLIB_DIR_INC "${THIRDPARTY_PATH}/z-lib") + set(ZLIB_DIR_LIB "${THIRDPARTY_PATH}/z-lib") + include_directories(${ZLIB_DIR_INC}) + link_directories(${ZLIB_DIR_LIB}) +endif() -set(ZLIB_DIR_INC "${THIRDPARTY_PATH}/z-lib") -set(ZLIB_DIR_LIB "${THIRDPARTY_PATH}/z-lib") -include_directories(${ZLIB_DIR_INC}) -link_directories(${ZLIB_DIR_LIB}) +if(TARS_HTTP2) + set(OPEN_NGHTTP2 "ON") + set(NGHTTP2_DIR_INC "${THIRDPARTY_PATH}/nghttp2-lib/lib/includes/") + set(NGHTTP2_DIR_LIB "${THIRDPARTY_PATH}/nghttp2-lib/lib") + include_directories(${NGHTTP2_DIR_INC}) + link_directories(${NGHTTP2_DIR_LIB}) +endif() -set(NGHTTP2_DIR_INC "${THIRDPARTY_PATH}/nghttp2-lib/lib/includes/") -set(NGHTTP2_DIR_LIB "${THIRDPARTY_PATH}/nghttp2-lib/lib") -include_directories(${NGHTTP2_DIR_INC}) -link_directories(${NGHTTP2_DIR_LIB}) - -set(SSL_DIR_INC "${THIRDPARTY_PATH}/openssl-lib/include/") -set(SSL_DIR_LIB "${THIRDPARTY_PATH}/openssl-lib") -include_directories(${SSL_DIR_INC}) -link_directories(${SSL_DIR_LIB}) +if(TARS_SSL) + set(OPEN_SSL "ON") + set(SSL_DIR_INC "${THIRDPARTY_PATH}/openssl-lib/include/") + set(SSL_DIR_LIB "${THIRDPARTY_PATH}/openssl-lib") + include_directories(${SSL_DIR_INC}) + link_directories(${SSL_DIR_LIB}) +endif() set(LIB_MYSQL) set(LIB_NGHTTP2) diff --git a/examples/AuthDemo/CMakeLists.txt b/examples/AuthDemo/CMakeLists.txt new file mode 100644 index 0000000..6345c28 --- /dev/null +++ b/examples/AuthDemo/CMakeLists.txt @@ -0,0 +1,5 @@ + +include_directories(Server) +add_subdirectory(Server) +add_subdirectory(Client) + diff --git a/examples/AuthDemo/Client/CMakeLists.txt b/examples/AuthDemo/Client/CMakeLists.txt new file mode 100644 index 0000000..d32ce92 --- /dev/null +++ b/examples/AuthDemo/Client/CMakeLists.txt @@ -0,0 +1 @@ +build_tars_server("AuthClient" "AuthServer") \ No newline at end of file diff --git a/examples/AuthDemo/Client/config.conf b/examples/AuthDemo/Client/config.conf new file mode 100755 index 0000000..9ea7492 --- /dev/null +++ b/examples/AuthDemo/Client/config.conf @@ -0,0 +1,33 @@ + + + + + #tarsregistry locator + locator = tars.tarsregistry.QueryObj@tcp -h 127.0.0.1 -p 17890 + #max invoke timeout + sync-invoke-timeout = 5000 + #refresh endpoint interval + refresh-endpoint-interval = 10000 + #stat obj + stat = tars.tarsstat.StatObj + #max send queue length limit + sendqueuelimit = 100000 + #async queue length limit + asyncqueuecap = 100000 + #async callback thread num + asyncthread = 3 + #net thread + netthread = 1 + #merge net and sync thread + mergenetasync = 0 + #module name + modulename = TestApp.AuthClient + #server crt + ca = ../examples/AuthDemo/certs/server.crt + #can be empty + cert = ../examples/AuthDemo/certs/client.crt + #can be empty + key = ../examples/AuthDemo/certs/client.key + + + diff --git a/examples/AuthDemo/Client/main.cpp b/examples/AuthDemo/Client/main.cpp new file mode 100644 index 0000000..f46d230 --- /dev/null +++ b/examples/AuthDemo/Client/main.cpp @@ -0,0 +1,224 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +#include +#include "servant/Communicator.h" +#include "Hello.h" +#include "util/tc_option.h" + +using namespace std; +using namespace tars; +using namespace TestApp; + +Communicator* _comm; + +static string helloObj = "TestApp.AuthServer.AuthObj@ssl -h 127.0.0.1 -p 9016"; + +struct Param +{ + int count; + string call; + int thread; + int buffersize; + int netthread; + + HelloPrx pPrx; +}; + +Param param; +std::atomic callback_count(0); + +struct HelloCallback : public HelloPrxCallback +{ + HelloCallback(int64_t t, int i, int c) : start(t), cur(i), count(c) + { + + } + + //call back + virtual void callback_testHello(int ret, const string &r) + { + assert(ret == 0); + callback_count++; + + if(cur == count-1) + { + int64_t cost = TC_Common::now2us() - start; + cout << "callback_testHello count:" << count << ", " << cost << " us, avg:" << 1.*cost/count << "us" << endl; + } + } + + virtual void callback_testHello_exception(tars::Int32 ret) + { + cout << "callback exception:" << ret << endl; + } + + int64_t start; + int cur; + int count; +}; + + +void syncCall(int c) +{ + string buffer(param.buffersize, 'a'); + + int64_t t = TC_Common::now2us(); + //发起远程调用 + for (int i = 0; i < c; ++i) + { + string r; + + try + { + + param.pPrx->testHello(buffer, r); + } + catch(exception& e) + { + cout << "exception:" << e.what() << endl; + } + ++callback_count; + } + + int64_t cost = TC_Common::now2us() - t; + cout << "syncCall total:" << cost << "us, avg:" << 1.*cost/c << "us" << endl; +} + + +void asyncCall(int c) +{ + int64_t t = TC_Common::now2us(); + + string buffer(param.buffersize, 'a'); + + //发起远程调用 + for (int i = 0; i < c; ++i) + { + HelloPrxCallbackPtr p = new HelloCallback(t, i, c); + + try + { + param.pPrx->async_testHello(p, buffer); + } + catch(exception& e) + { + cout << "exception:" << e.what() << endl; + } + } + + int64_t cost = TC_Common::now2us() - t; + cout << "asyncCall send:" << cost << "us, avg:" << 1.*cost/c << "us" << endl; +} + +int main(int argc, char *argv[]) +{ + try + { + if (argc < 6) + { + cout << "Usage:" << argv[0] << "--config=conf --count=1000 --call=[sync|async] --thread=1 --buffersize=1000 --netthread=1" << endl; + + return 0; + } + + TC_Option option; + option.decode(argc, argv); + + param.count = TC_Common::strto(option.getValue("count")); + if(param.count <= 0) param.count = 1000; + param.buffersize = TC_Common::strto(option.getValue("buffersize")); + if(param.buffersize <= 0) param.buffersize = 1000; + param.call = option.getValue("call"); + if(param.call.empty()) param.call = "sync"; + param.thread = TC_Common::strto(option.getValue("thread")); + if(param.thread <= 0) param.thread = 1; + param.netthread = TC_Common::strto(option.getValue("netthread")); + if(param.netthread <= 0) param.netthread = 1; + + _comm = new Communicator(); + + TC_Config conf; + conf.parseFile(option.getValue("config")); + _comm->setProperty(conf); + + TarsRollLogger::getInstance()->logger()->setLogLevel(6); + + _comm->setProperty("sendqueuelimit", "1000000"); + _comm->setProperty("asyncqueuecap", "1000000"); + + _comm->setProperty("netthread", TC_Common::tostr(param.netthread)); + + param.pPrx = _comm->stringToProxy(helloObj); + + param.pPrx->tars_connect_timeout(5000); + param.pPrx->tars_async_timeout(60*1000); + param.pPrx->tars_ping(); + + int64_t start = TC_Common::now2us(); + + std::function func; + + if (param.call == "sync") + { + func = syncCall; + } + else if (param.call == "async") + { + func = asyncCall; + } + else + { + cout << "no func, exits" << endl; + exit(0); + } + + vector vt; + for(int i = 0 ; i< param.thread; i++) + { + vt.push_back(new std::thread(func, param.count)); + } + + std::thread print([&]{while(callback_count != param.count * param.thread) { + cout << param.call << ": ----------finish count:" << callback_count << endl; + std::this_thread::sleep_for(std::chrono::seconds(1)); + };}); + + for(size_t i = 0 ; i< vt.size(); i++) + { + vt[i]->join(); + delete vt[i]; + } + + cout << "(pid:" << std::this_thread::get_id() << ")" + << "(count:" << param.count << ")" + << "(use ms:" << (TC_Common::now2us() - start)/1000 << ")" + << endl; + + while(callback_count != param.count * param.thread) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + print.join(); + cout << "----------finish count:" << callback_count << endl; + } + catch(exception &ex) + { + cout << ex.what() << endl; + } + cout << "main return." << endl; + + return 0; +} diff --git a/examples/AuthDemo/Server/CMakeLists.txt b/examples/AuthDemo/Server/CMakeLists.txt new file mode 100644 index 0000000..c22147f --- /dev/null +++ b/examples/AuthDemo/Server/CMakeLists.txt @@ -0,0 +1 @@ +build_tars_server("AuthServer" "") diff --git a/examples/AuthDemo/Server/Hello.h b/examples/AuthDemo/Server/Hello.h new file mode 100644 index 0000000..f85e089 --- /dev/null +++ b/examples/AuthDemo/Server/Hello.h @@ -0,0 +1,471 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 2.0.0. +// ********************************************************************** + +#ifndef __HELLO_H_ +#define __HELLO_H_ + +#include +#include +#include +#include "tup/Tars.h" +#include "tup/TarsJson.h" +using namespace std; +#include "servant/ServantProxy.h" +#include "servant/Servant.h" + + +namespace TestApp +{ + + /* callback of async proxy for client */ + class HelloPrxCallback: public tars::ServantProxyCallback + { + public: + virtual ~HelloPrxCallback(){} + virtual void callback_test(tars::Int32 ret) + { throw std::runtime_error("callback_test() override incorrect."); } + virtual void callback_test_exception(tars::Int32 ret) + { throw std::runtime_error("callback_test_exception() override incorrect."); } + + virtual void callback_testHello(tars::Int32 ret, const std::string& sRsp) + { throw std::runtime_error("callback_testHello() override incorrect."); } + virtual void callback_testHello_exception(tars::Int32 ret) + { throw std::runtime_error("callback_testHello_exception() override incorrect."); } + + public: + virtual const map & getResponseContext() const + { + CallbackThreadData * pCbtd = CallbackThreadData::getData(); + assert(pCbtd != NULL); + + if(!pCbtd->getContextValid()) + { + throw TC_Exception("cann't get response context"); + } + return pCbtd->getResponseContext(); + } + + public: + virtual int onDispatch(tars::ReqMessagePtr msg) + { + static ::std::string __Hello_all[]= + { + "test", + "testHello" + }; + pair r = equal_range(__Hello_all, __Hello_all+2, string(msg->request.sFuncName)); + if(r.first == r.second) return tars::TARSSERVERNOFUNCERR; + switch(r.first - __Hello_all) + { + case 0: + { + if (msg->response->iRet != tars::TARSSERVERSUCCESS) + { + callback_test_exception(msg->response->iRet); + + return msg->response->iRet; + } + tars::TarsInputStream _is; + + _is.setBuffer(msg->response->sBuffer); + tars::Int32 _ret; + _is.read(_ret, 0, true); + + CallbackThreadData * pCbtd = CallbackThreadData::getData(); + assert(pCbtd != NULL); + + pCbtd->setResponseContext(msg->response->context); + + callback_test(_ret); + + pCbtd->delResponseContext(); + + return tars::TARSSERVERSUCCESS; + + } + case 1: + { + if (msg->response->iRet != tars::TARSSERVERSUCCESS) + { + callback_testHello_exception(msg->response->iRet); + + return msg->response->iRet; + } + tars::TarsInputStream _is; + + _is.setBuffer(msg->response->sBuffer); + tars::Int32 _ret; + _is.read(_ret, 0, true); + + std::string sRsp; + _is.read(sRsp, 2, true); + CallbackThreadData * pCbtd = CallbackThreadData::getData(); + assert(pCbtd != NULL); + + pCbtd->setResponseContext(msg->response->context); + + callback_testHello(_ret, sRsp); + + pCbtd->delResponseContext(); + + return tars::TARSSERVERSUCCESS; + + } + } + return tars::TARSSERVERNOFUNCERR; + } + + }; + typedef tars::TC_AutoPtr HelloPrxCallbackPtr; + + /* callback of coroutine async proxy for client */ + class HelloCoroPrxCallback: public HelloPrxCallback + { + public: + virtual ~HelloCoroPrxCallback(){} + public: + virtual const map & getResponseContext() const { return _mRspContext; } + + virtual void setResponseContext(const map &mContext) { _mRspContext = mContext; } + + public: + int onDispatch(tars::ReqMessagePtr msg) + { + static ::std::string __Hello_all[]= + { + "test", + "testHello" + }; + + pair r = equal_range(__Hello_all, __Hello_all+2, string(msg->request.sFuncName)); + if(r.first == r.second) return tars::TARSSERVERNOFUNCERR; + switch(r.first - __Hello_all) + { + case 0: + { + if (msg->response->iRet != tars::TARSSERVERSUCCESS) + { + callback_test_exception(msg->response->iRet); + + return msg->response->iRet; + } + tars::TarsInputStream _is; + + _is.setBuffer(msg->response->sBuffer); + try + { + tars::Int32 _ret; + _is.read(_ret, 0, true); + + setResponseContext(msg->response->context); + + callback_test(_ret); + + } + catch(std::exception &ex) + { + callback_test_exception(tars::TARSCLIENTDECODEERR); + + return tars::TARSCLIENTDECODEERR; + } + catch(...) + { + callback_test_exception(tars::TARSCLIENTDECODEERR); + + return tars::TARSCLIENTDECODEERR; + } + + return tars::TARSSERVERSUCCESS; + + } + case 1: + { + if (msg->response->iRet != tars::TARSSERVERSUCCESS) + { + callback_testHello_exception(msg->response->iRet); + + return msg->response->iRet; + } + tars::TarsInputStream _is; + + _is.setBuffer(msg->response->sBuffer); + try + { + tars::Int32 _ret; + _is.read(_ret, 0, true); + + std::string sRsp; + _is.read(sRsp, 2, true); + setResponseContext(msg->response->context); + + callback_testHello(_ret, sRsp); + + } + catch(std::exception &ex) + { + callback_testHello_exception(tars::TARSCLIENTDECODEERR); + + return tars::TARSCLIENTDECODEERR; + } + catch(...) + { + callback_testHello_exception(tars::TARSCLIENTDECODEERR); + + return tars::TARSCLIENTDECODEERR; + } + + return tars::TARSSERVERSUCCESS; + + } + } + return tars::TARSSERVERNOFUNCERR; + } + + protected: + map _mRspContext; + }; + typedef tars::TC_AutoPtr HelloCoroPrxCallbackPtr; + + /* proxy for client */ + class HelloProxy : public tars::ServantProxy + { + public: + typedef map TARS_CONTEXT; + tars::Int32 test(const map &context = TARS_CONTEXT(),map * pResponseContext = NULL) + { + tars::TarsOutputStream _os; + std::map _mStatus; + shared_ptr rep = tars_invoke(tars::TARSNORMAL,"test", _os, context, _mStatus); + if(pResponseContext) + { + pResponseContext->swap(rep->context); + } + + tars::TarsInputStream _is; + _is.setBuffer(rep->sBuffer); + tars::Int32 _ret; + _is.read(_ret, 0, true); + return _ret; + } + + void async_test(HelloPrxCallbackPtr callback,const map& context = TARS_CONTEXT()) + { + tars::TarsOutputStream _os; + std::map _mStatus; + tars_invoke_async(tars::TARSNORMAL,"test", _os, context, _mStatus, callback); + } + + void coro_test(HelloCoroPrxCallbackPtr callback,const map& context = TARS_CONTEXT()) + { + tars::TarsOutputStream _os; + std::map _mStatus; + tars_invoke_async(tars::TARSNORMAL,"test", _os, context, _mStatus, callback, true); + } + + tars::Int32 testHello(const std::string & sReq,std::string &sRsp,const map &context = TARS_CONTEXT(),map * pResponseContext = NULL) + { + tars::TarsOutputStream _os; + _os.write(sReq, 1); + _os.write(sRsp, 2); + std::map _mStatus; + shared_ptr rep = tars_invoke(tars::TARSNORMAL,"testHello", _os, context, _mStatus); + if(pResponseContext) + { + pResponseContext->swap(rep->context); + } + + tars::TarsInputStream _is; + _is.setBuffer(rep->sBuffer); + tars::Int32 _ret; + _is.read(_ret, 0, true); + _is.read(sRsp, 2, true); + return _ret; + } + + void async_testHello(HelloPrxCallbackPtr callback,const std::string &sReq,const map& context = TARS_CONTEXT()) + { + tars::TarsOutputStream _os; + _os.write(sReq, 1); + std::map _mStatus; + tars_invoke_async(tars::TARSNORMAL,"testHello", _os, context, _mStatus, callback); + } + + void coro_testHello(HelloCoroPrxCallbackPtr callback,const std::string &sReq,const map& context = TARS_CONTEXT()) + { + tars::TarsOutputStream _os; + _os.write(sReq, 1); + std::map _mStatus; + tars_invoke_async(tars::TARSNORMAL,"testHello", _os, context, _mStatus, callback, true); + } + + HelloProxy* tars_hash(int64_t key) + { + return (HelloProxy*)ServantProxy::tars_hash(key); + } + + HelloProxy* tars_consistent_hash(int64_t key) + { + return (HelloProxy*)ServantProxy::tars_consistent_hash(key); + } + + HelloProxy* tars_set_timeout(int msecond) + { + return (HelloProxy*)ServantProxy::tars_set_timeout(msecond); + } + + static const char* tars_prxname() { return "HelloProxy"; } + }; + typedef tars::TC_AutoPtr HelloPrx; + + /* servant for server */ + class Hello : public tars::Servant + { + public: + virtual ~Hello(){} + virtual tars::Int32 test(tars::TarsCurrentPtr current) = 0; + static void async_response_test(tars::TarsCurrentPtr current, tars::Int32 _ret) + { + if (current->getRequestVersion() == TUPVERSION ) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(current->getRequestVersion()); + tarsAttr.put("", _ret); + + vector sTupResponseBuffer; + tarsAttr.encode(sTupResponseBuffer); + current->sendResponse(tars::TARSSERVERSUCCESS, sTupResponseBuffer); + } + else + { + tars::TarsOutputStream _os; + _os.write(_ret, 0); + + current->sendResponse(tars::TARSSERVERSUCCESS, _os.getByteBuffer()); + } + } + + virtual tars::Int32 testHello(const std::string & sReq,std::string &sRsp,tars::TarsCurrentPtr current) = 0; + static void async_response_testHello(tars::TarsCurrentPtr current, tars::Int32 _ret, const std::string &sRsp) + { + if (current->getRequestVersion() == TUPVERSION ) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(current->getRequestVersion()); + tarsAttr.put("", _ret); + tarsAttr.put("sRsp", sRsp); + + vector sTupResponseBuffer; + tarsAttr.encode(sTupResponseBuffer); + current->sendResponse(tars::TARSSERVERSUCCESS, sTupResponseBuffer); + } + else + { + tars::TarsOutputStream _os; + _os.write(_ret, 0); + + _os.write(sRsp, 2); + + current->sendResponse(tars::TARSSERVERSUCCESS, _os.getByteBuffer()); + } + } + + public: + int onDispatch(tars::TarsCurrentPtr _current, vector &_sResponseBuffer) + { + static ::std::string __TestApp__Hello_all[]= + { + "test", + "testHello" + }; + + pair r = equal_range(__TestApp__Hello_all, __TestApp__Hello_all+2, _current->getFuncName()); + if(r.first == r.second) return tars::TARSSERVERNOFUNCERR; + switch(r.first - __TestApp__Hello_all) + { + case 0: + { + tars::TarsInputStream _is; + _is.setBuffer(_current->getRequestBuffer()); + if (_current->getRequestVersion() == TUPVERSION) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(_current->getRequestVersion()); + tarsAttr.decode(_current->getRequestBuffer()); + } + else + { + } + tars::Int32 _ret = test(_current); + if(_current->isResponse()) + { + if (_current->getRequestVersion() == TUPVERSION ) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(_current->getRequestVersion()); + tarsAttr.put("", _ret); + tarsAttr.encode(_sResponseBuffer); + } + else + { + tars::TarsOutputStream _os; + _os.write(_ret, 0); + _os.swap(_sResponseBuffer); + } + } + return tars::TARSSERVERSUCCESS; + + } + case 1: + { + tars::TarsInputStream _is; + _is.setBuffer(_current->getRequestBuffer()); + std::string sReq; + std::string sRsp; + if (_current->getRequestVersion() == TUPVERSION) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(_current->getRequestVersion()); + tarsAttr.decode(_current->getRequestBuffer()); + tarsAttr.get("sReq", sReq); + tarsAttr.getByDefault("sRsp", sRsp, sRsp); + } + else + { + _is.read(sReq, 1, true); + _is.read(sRsp, 2, false); + } + tars::Int32 _ret = testHello(sReq,sRsp, _current); + if(_current->isResponse()) + { + if (_current->getRequestVersion() == TUPVERSION ) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(_current->getRequestVersion()); + tarsAttr.put("", _ret); + tarsAttr.put("sRsp", sRsp); + tarsAttr.encode(_sResponseBuffer); + } + else + { + tars::TarsOutputStream _os; + _os.write(_ret, 0); + _os.write(sRsp, 2); + _os.swap(_sResponseBuffer); + } + } + return tars::TARSSERVERSUCCESS; + + } + } + return tars::TARSSERVERNOFUNCERR; + } + }; + + +} + + + +#endif diff --git a/examples/AuthDemo/Server/Hello.tars b/examples/AuthDemo/Server/Hello.tars new file mode 100644 index 0000000..174c4f3 --- /dev/null +++ b/examples/AuthDemo/Server/Hello.tars @@ -0,0 +1,26 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +module TestApp +{ + +interface Hello +{ + int test(); + int testHello(string sReq, out string sRsp); +}; + +}; diff --git a/examples/AuthDemo/Server/HelloImp.cpp b/examples/AuthDemo/Server/HelloImp.cpp new file mode 100644 index 0000000..e5f5767 --- /dev/null +++ b/examples/AuthDemo/Server/HelloImp.cpp @@ -0,0 +1,43 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +#include "HelloImp.h" +#include "servant/Application.h" + +using namespace std; + +////////////////////////////////////////////////////// +void HelloImp::initialize() +{ + //initialize servant here: + //... +} + +////////////////////////////////////////////////////// +void HelloImp::destroy() +{ + //destroy servant here: + //... +} + +int HelloImp::testHello(const std::string &sReq, std::string &sRsp, tars::TarsCurrentPtr current) +{ +// TLOGDEBUG("HelloImp::testHellosReq:"<(ServerConfig::Application + "." + ServerConfig::ServerName + ".AuthObj"); +} +///////////////////////////////////////////////////////////////// +void +HelloServer::destroyApp() +{ + //destroy application here: + //... +} +///////////////////////////////////////////////////////////////// +int +main(int argc, char* argv[]) +{ + try + { + g_app.main(argc, argv); + g_app.waitForShutdown(); + } + catch (std::exception& e) + { + cerr << "std::exception:" << e.what() << std::endl; + } + catch (...) + { + cerr << "unknown exception." << std::endl; + } + return -1; +} +///////////////////////////////////////////////////////////////// diff --git a/examples/AuthDemo/Server/HelloServer.h b/examples/AuthDemo/Server/HelloServer.h new file mode 100644 index 0000000..0fbc36b --- /dev/null +++ b/examples/AuthDemo/Server/HelloServer.h @@ -0,0 +1,50 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +#ifndef _HelloServer_H_ +#define _HelloServer_H_ + +#include +#include "servant/Application.h" + +using namespace tars; + +/** + * + **/ +class HelloServer : public Application +{ +public: + /** + * + **/ + virtual ~HelloServer() {}; + + /** + * + **/ + virtual void initialize(); + + /** + * + **/ + virtual void destroyApp(); +}; + +extern HelloServer g_app; + +//////////////////////////////////////////// +#endif diff --git a/examples/AuthDemo/Server/config.conf b/examples/AuthDemo/Server/config.conf new file mode 100755 index 0000000..bf578d2 --- /dev/null +++ b/examples/AuthDemo/Server/config.conf @@ -0,0 +1,72 @@ + + + + + #tarsregistry locator + locator = tars.tarsregistry.QueryObj@tcp -h 127.0.0.1 -p 17890 + #max invoke timeout + sync-invoke-timeout = 5000 + #refresh endpoint interval + refresh-endpoint-interval = 10000 + #stat obj + stat = tars.tarsstat.StatObj + #max send queue length limit + sendqueuelimit = 100000 + #async queue length limit + asyncqueuecap = 100000 + #async callback thread num + asyncthread = 3 + #net thread + netthread = 1 + #merge net and sync thread + mergenetasync = 0 + #module name + modulename = TestApp.AuthClient + + + + + #not cout + closecout = 0 + #app name + app = TestApp + #server name + server = AuthServer + #path + basepath = ./ + datapath = ./ + #log path + logpath = ./ + #merge net and imp thread + mergenetimp = 0 + #local ip, for tarsnode +# local = tcp -h 127.0.0.1 -p 15001 -t 10000 + + #tarsnode +# node = ServerObj@tcp -h 127.0.0.1 -p 2345 -t 10000 + #config obj +# config = tars.tarsconfig.ConfigObj + #notify obj +# notify = tars.tarsconfig.NotifyObj + #log obj +# log = tars.tarslog.LogObj + + + #ip:port:timeout + endpoint = tcp -h 127.0.0.1 -p 9016 -t 10000 + #allow ip + allow = + #max connection num + maxconns = 4096 + #imp thread num + threads = 5 + #servant + servant = TestApp.AuthServer.AuthObj + #queue capacity + queuecap = 1000000 + #tars protocol + protocol = tars + + + + diff --git a/examples/AuthDemo/certs/ca.crt b/examples/AuthDemo/certs/ca.crt new file mode 100644 index 0000000..a57ea14 --- /dev/null +++ b/examples/AuthDemo/certs/ca.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDCzCCAfOgAwIBAgIUfmd8TIa6hXXp/KibyRhjrYGhY+gwDQYJKoZIhvcNAQEL +BQAwFTETMBEGA1UEAwwKKi5kZW1vLmNvbTAeFw0yMDAyMTMxMjMwNDdaFw0zMzEw +MjIxMjMwNDdaMBUxEzARBgNVBAMMCiouZGVtby5jb20wggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDOV6uDon7+RDiCpHzOaAa5P1vtj1k0YEkWbLwsBBDT +wYdkXnnfYHxQfY9kh9Gp13Otx0xCdTVBDQAlAxqAK9zH7dgxxysvcQE2ZL9mnkFx +BksP6kHRM//HQM9ylaPCgyA5L2nsixLZ4ipkI1td+n/nL6mB4GIAhwSVJlN74CXE +FXPjMaS7dEdRfdVz6gD2h1L8jFF9f7S9ZawZ8kw+JWUKflzr0L9mRGbuhukCJ+3N +TZFKHSL1Yy0NsE0nM8X0ncmpQExQ0sqrKgmAHnju9jXvMbxMjFI2AwrLPtV8U2Hg +ziztJmdPqM8LIQZpmeynq9eP1+AD7PEu8C7LsV5wTWndAgMBAAGjUzBRMB0GA1Ud +DgQWBBQ4RfWqsDwlD00IhcvCY40gYJtTuDAfBgNVHSMEGDAWgBQ4RfWqsDwlD00I +hcvCY40gYJtTuDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCj +DbEL8nvVzyhW01O3/5oJSd8Z1g+7WupLmtF5OZuKN2XKDICLRxtow7XHiJLlkgZW +4K/kJeXvbPYRrKTm6PHJ63bWKl6YaD3/Vm9wgCLC48ikrOqiEL2w/mI/zFeEvZ3K +U50tLnllY2L0NZxgRZ7wZZqU6qKMxHn7UMYtfzSf7XzBBXi6qzf290DNminr9YgT +afsP+cjL74TchyZifFqI+sGhXO9IY8+lrRYoUXUwcE0DPWHe08UrAtT1E1b7SU2o +pvlUABuUbufvTwu1Cj6mDqOjQQUmWDqNgb2FeNWsmdkBqrhxkLorLiNb5o/YgCKJ +Patq2TfT09tiaeNAl/cF +-----END CERTIFICATE----- diff --git a/examples/AuthDemo/certs/ca.key b/examples/AuthDemo/certs/ca.key new file mode 100644 index 0000000..d91cf9c --- /dev/null +++ b/examples/AuthDemo/certs/ca.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAzlerg6J+/kQ4gqR8zmgGuT9b7Y9ZNGBJFmy8LAQQ08GHZF55 +32B8UH2PZIfRqddzrcdMQnU1QQ0AJQMagCvcx+3YMccrL3EBNmS/Zp5BcQZLD+pB +0TP/x0DPcpWjwoMgOS9p7IsS2eIqZCNbXfp/5y+pgeBiAIcElSZTe+AlxBVz4zGk +u3RHUX3Vc+oA9odS/IxRfX+0vWWsGfJMPiVlCn5c69C/ZkRm7obpAiftzU2RSh0i +9WMtDbBNJzPF9J3JqUBMUNLKqyoJgB547vY17zG8TIxSNgMKyz7VfFNh4M4s7SZn +T6jPCyEGaZnsp6vXj9fgA+zxLvAuy7FecE1p3QIDAQABAoIBAG5V6tzEs2t7R0x0 +cFhev9mmy51IHccoBWz8T9KpieXxglhlPH35tf/EZDy5c5+CGdU+0MRosEVMkls4 +QZ9v1OsDf6t+eNUxdBiF3uMclJm/Z7vm47LeP1NokIURBzQnsb9iXx2hcD8Z9Nj/ +Hwgtvt78WYOdXEoz6HtotxNyVD940uEg9U3dPKBAVJRFtLa4pBtSbj1ZpElFsR/l +f94+uwgESsgZF7OZZiKEklLpC2/xPi4m/IDxCBjy3GW7nou6T1Cy90DBX7OfhFur +fQjcAzC4AKvGdkT/0ocQw6jdtGVzDgYEO7pD7r6rpubwsbYXaXOgBvzELUSM+nj3 +Lpv+anECgYEA9VBUAAzcn3mCvf5Dh/VrK997Ll4+/0F0SRFBGW2x/ChRKaIXIMCb +VGIRTIhPACl98v8ctwML9sYQ+4bBYabwTxkCtHS1OoZlUUUzCusVaQ+6VmbWHadd +Ua+Gl0cfM6S5jNpbkoiAG7lRA76GH+QfOlCawhgbWWGD5iT2wHBVk88CgYEA11S+ +kHDcPzlHHfiobFlJimeeb4j5G2I26fZSlaO5gAkD8yzxov7zMSSemfAE8j/fS0+6 +EZkArsyro9lATlWejdssndKku7uykuvwIQvKCYd13lD0/Cpvb101MuM7CcYXsoDv +z7vaaV94Xe8TgL3BY7+QYD7mANC1XwUZS17eVpMCgYEAxd+QkiXNw/kgg55X3JAS +bWYrl0BAMmcapGF9kERSX+IpbZqoayvRXyRnbcM5bhkJ1fr/r4OOn/Qt+KU+0UT1 +6+dxrhvBnz6O9RoLTRBIyeD83fq/VVYNyPj7aITe3ypM3Re4656dLz+w4INK7uh0 +Y/Zmjo8haFxnJznDq4AxFzMCgYAMwGb8lMJmOBUfED+hEvSI7rPyNPFTjtBjsIOZ +evWcQGxsdSfmGCT8rwd5ZD5WvjOR+SmyqxXgRByR+maVfPqDugv9WKEKwQXFL5Wr +z0/qmov/W1n2qOiqdqGU3uH7JTD4ECyjZ6N6g/3TyjmkcRhHuOtq1661M6bZ9qpV +zUtrYwKBgQDoV7ra5JQ217LB49ZXqWMyA5CGMf6NxMwVzPy7H+Pk2F6FQw7lXPEy +XCYD94lhcFuZIUkfqjbG96C1z18ALF7XaxwidYJlkrhXrgZigsJtcUG+RDaavpfI +u5qVhzJbGexoo7hXJeDvgilu525eoysmnlTATqNkRWdP7T4w+uu86w== +-----END RSA PRIVATE KEY----- diff --git a/examples/AuthDemo/certs/ca.srl b/examples/AuthDemo/certs/ca.srl new file mode 100644 index 0000000..9bafb6c --- /dev/null +++ b/examples/AuthDemo/certs/ca.srl @@ -0,0 +1 @@ +5C1561567852EF51D268687494029145127A56C3 diff --git a/examples/AuthDemo/certs/client.crt b/examples/AuthDemo/certs/client.crt new file mode 100644 index 0000000..dde025d --- /dev/null +++ b/examples/AuthDemo/certs/client.crt @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICsTCCAZkCFFwVYVZ4Uu9R0mhodJQCkUUSelbDMA0GCSqGSIb3DQEBCwUAMBUx +EzARBgNVBAMMCiouZGVtby5jb20wHhcNMjAwMjEzMTIzMDQ3WhcNMzMxMDIyMTIz +MDQ3WjAVMRMwEQYDVQQDDAoqLmRlbW8uY29tMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEAqOp2R0JnTBeKjQmHDjIKHlT5RLfk/RTksrw88xdrQgOLbceB +rjZg82yfTJkFW4rTVjjSphNbPCynFwg+BxK9MXfJr9Rs9dsBSpmCViXiw6pmDSZz +on691cL4PYEEeom8y5egp/OU6IQRcNwpyffiVDPYSR8qH3PzTi7RXLGNGtdLFi0I +YeZ+FYlGjTlBQRyqNvOD3nEvIocNtyWP9+D17wtPENA2AbWbHV2CbKFoc6Zx98Fw +KtVkz94Z4duzjLUZOwjcTWK+zKxfRzVDZtxlMTOA261N8CUha8nl+c4uNgTC0h0J +PE5JTewwXdGftNiR2xWgVLvWfbFg73x0RemoyQIDAQABMA0GCSqGSIb3DQEBCwUA +A4IBAQBxnTndUG6zfHVz5t/2j6pppqY93lXaHoi8VD2dXgtzda8BqgulwZAe8x2v +BAP522Ch3AusIFZs9ejLZt97BHkf30uhnoKKGhHsKDxq4ll338+PEWkvUdQNl1Xi +RZyC4VXwji4DABlM5BKtr0vNbYW8hkZWzOCmM1qHx8FbGmb4Z5lO3t4e7tCiwX72 +yY7/5zqZSS8b5BDMQJtDXjV2yZDJLsfdRx8NRuwsSNPQTkm+MFHLV42mO5vH0Ugb +ULHNRXQsThwO4p1y0Nlo4/Ti0qIh4II0sIkW9chigaGuqxo2D27L2o1hkBbjiLIY +blrKSx8QEWyC7Etnm4KT9Cxs5xmg +-----END CERTIFICATE----- diff --git a/examples/AuthDemo/certs/client.csr b/examples/AuthDemo/certs/client.csr new file mode 100644 index 0000000..2d8bd62 --- /dev/null +++ b/examples/AuthDemo/certs/client.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICWjCCAUICAQAwFTETMBEGA1UEAwwKKi5kZW1vLmNvbTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAKjqdkdCZ0wXio0Jhw4yCh5U+US35P0U5LK8PPMX +a0IDi23Hga42YPNsn0yZBVuK01Y40qYTWzwspxcIPgcSvTF3ya/UbPXbAUqZglYl +4sOqZg0mc6J+vdXC+D2BBHqJvMuXoKfzlOiEEXDcKcn34lQz2EkfKh9z804u0Vyx +jRrXSxYtCGHmfhWJRo05QUEcqjbzg95xLyKHDbclj/fg9e8LTxDQNgG1mx1dgmyh +aHOmcffBcCrVZM/eGeHbs4y1GTsI3E1ivsysX0c1Q2bcZTEzgNutTfAlIWvJ5fnO +LjYEwtIdCTxOSU3sMF3Rn7TYkdsVoFS71n2xYO98dEXpqMkCAwEAAaAAMA0GCSqG +SIb3DQEBCwUAA4IBAQBxzQt4BuF7HIAReW0RAWpAXoJVJlLKoObIuRwT0dqcHbRs +uZKovoKjhLlI0Cg2ljLj+p87fbHAl256pnUa91B+Qzy+NwNxltXqKE5fYuH1hvP1 +SRJ/qaXPbWmX7ZQ0y3eBE17HOAP4GVpURbsOVQdaxJOjxIeFG6H+FmKNMzCo8e+B +KB3bYCHCPSI8VLWPbKF8fbu1JmBstjikHEEW85WiV/ZGqnYIT2CijyuKFEzYwkZg +sIW5xjzqaYKo+RzwYeYqvL6kvniWHaxwdnEz3t0yr4V51ouPvoimSPHsA8qklQil ++ZgYlvSmeNTlQy80UoY81IzHiADxBTzscBPUjILW +-----END CERTIFICATE REQUEST----- diff --git a/examples/AuthDemo/certs/client.key b/examples/AuthDemo/certs/client.key new file mode 100644 index 0000000..ff280b6 --- /dev/null +++ b/examples/AuthDemo/certs/client.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAqOp2R0JnTBeKjQmHDjIKHlT5RLfk/RTksrw88xdrQgOLbceB +rjZg82yfTJkFW4rTVjjSphNbPCynFwg+BxK9MXfJr9Rs9dsBSpmCViXiw6pmDSZz +on691cL4PYEEeom8y5egp/OU6IQRcNwpyffiVDPYSR8qH3PzTi7RXLGNGtdLFi0I +YeZ+FYlGjTlBQRyqNvOD3nEvIocNtyWP9+D17wtPENA2AbWbHV2CbKFoc6Zx98Fw +KtVkz94Z4duzjLUZOwjcTWK+zKxfRzVDZtxlMTOA261N8CUha8nl+c4uNgTC0h0J +PE5JTewwXdGftNiR2xWgVLvWfbFg73x0RemoyQIDAQABAoIBACJPfbb7xf+uyHXd +eZFomKWQnRFYSSsfE1U65yZ5m0/NaITkAXNhmE/ZwIHOk0gE6uiYojEZvW57o3UK +N484PzXNHyqX+4n08k404ESfbXBRLGl/Zf2bwPOqpsHXcxFw6Ohx5DA5SgXwzZof +Hl3n/BEedtBjhCrfYox+9gfeCMtqm1s/TkiTe5l8slzzx0V7nLugz2xzaqnI8zpO ++JZpMlnQUh2XJ6ORHyHCI7sEqu/k2AswB+PduDUk/F2HdVzHBMcE8ZC4DrBaO7mS +SKwNwtw+SlakTnMvMhcHG29qMyLQKtHzc6SLlDCRtOjRDVgxecEDAkqyfve9FN93 +F6siQAECgYEA0FNIZSr/nTStT3B1K3XHSKiKJN8cZktUFfC15Yo7cYuT7aqnYh6g +dlm3Po0T66viL/yTA+vhbTTOTn5m0Gx3Yq6lPC4UVBp4s39UCzxQfXOJyTB/1ht2 +6SDEnom83EW6S/FklOnG5NZSDODw8B4XopMFnx6+69p32kldcJ/Ysw0CgYEAz5Jh +YJnx4AN4C4rNPBPkuRv/T/kfar2XVUA9dMlN9srMsIQiksH9tQQ9i1ABrjsnzCJp +IgRiMlHiiODr6JU71kdHddwLWetC0sjXVIF/7RZBl0QgcnS5z47YADxEWRKwWyUP +uz7Z/mMuV0kSGxp3+WMzoi2Wk6vqg6Nt9DilDa0CgYEAvgwsEDcAx96FeOID0ij5 +K1yt4eM0GlIAHJ/ioMvRXM1Tn06+snF0O2OvGr5C/Q1qJBLL35jxptm0l8ESdHNv +GjRvAw6advtLP50aA8H7P+cGPOckyCN4AEdnd6X6CA0IXj2SX5NBYgPvCFaxFqyt +LR/o0fePfsRn8FhbiOIaI4UCgYBOfM4/ZdaU2xrwWlrChc8tw41l4xBjHy9y9+iF +GX1WfVaqxDwCfEH/yYuv+t+3zvx8buKMD1ZGKrpbAZmSh6Npoeg+g6bzKEdLRtBN +Tu5datYAaa1POh3sgtngNOmvOKbgwAHTzq9FRqGGNcYX44lMDpu+jjhqvE3f2tM/ +zo9yvQKBgAfobnvYbaehkUB0bWlw9oURMfI6fI8T9EGhM0PvWsn0KaPqzsm9pBwS +eQKD88t+DxGQCFszdGE51N3av3matPABiiz0xSDbC0ywSkbcgiF3F3V6Ss9pYnVQ +NzLekf3JFRbpknvTeHbyaSqodeU8NC9lgVTGr46xkvUmNW4ixmqA +-----END RSA PRIVATE KEY----- diff --git a/examples/AuthDemo/certs/create.sh b/examples/AuthDemo/certs/create.sh new file mode 100644 index 0000000..b1b2375 --- /dev/null +++ b/examples/AuthDemo/certs/create.sh @@ -0,0 +1,28 @@ + +#create ca key +openssl genrsa -out ca.key 2048 + +#create ca crt +openssl req -x509 -new -nodes -key ca.key -subj "/CN=*.demo.com" -days 5000 -out ca.crt + +######################################################################################### +#create server key +openssl genrsa -out server.key 2048 + +#create server csr +openssl req -new -key server.key -subj "/CN=*.demo.com" -out server.csr + +#ca sign server, create server crt +openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 5000 + +######################################################################################### +#create client key +openssl genrsa -out client.key 2048 + +#create clilent csr +openssl req -new -key client.key -subj "/CN=*.demo.com" -out client.csr + +#ca sign client, create client crt +openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 5000 + +######################################################################################### \ No newline at end of file diff --git a/examples/AuthDemo/certs/server.crt b/examples/AuthDemo/certs/server.crt new file mode 100644 index 0000000..be34e7e --- /dev/null +++ b/examples/AuthDemo/certs/server.crt @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICsTCCAZkCFFwVYVZ4Uu9R0mhodJQCkUUSelbCMA0GCSqGSIb3DQEBCwUAMBUx +EzARBgNVBAMMCiouZGVtby5jb20wHhcNMjAwMjEzMTIzMDQ3WhcNMzMxMDIyMTIz +MDQ3WjAVMRMwEQYDVQQDDAoqLmRlbW8uY29tMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEA74MHigfRUfFvvS0ZSMCRiuxtkBZtAk+EeTMTcjamwgV8fMWz +JbtTqxn4325CqvXIcSs2H+c09C7pBufWzkwFFcEpSMokGEyjeKxXMmxhUC+q28yq +WiYim8l7btJZhMa3tpSQaWu+Ul0SctSt0OpM2onxq9s8KN7B0zM9tCmyLZ++IXxx +3yGjRRk1VtVyVePNILdf7EZBZXHu2daxf2GusYfQmV+KAG/r+YbX+7GXh2wZ/lGV +Ur4B6Pzoi/zUGoA7i7Zs/Y2S/yXsRD8UG6jid0slO4uBuiHa9RIjxNoe1NAqirBj +wBVNAbzfKOC7f/qiu5JhIg0qHbb50tXUvLZzbwIDAQABMA0GCSqGSIb3DQEBCwUA +A4IBAQCtk9bOoKdoF3UpDLijhBrmL7a13xT+Q5U3SiZiYw2pdz2FtGzZooQejmm6 +tDCmAisIZMiYS+X6Y2OoWe9dzEE1Rnx0227XPjhQvHAKsBfwL03N1Hw1LSzU7czf +/0pYWSyCVfL6f8DOeH2rnhBPHAE/FzDtnCaIDUtGC3I4ZuYrPBqDmmYTentWsPK3 +2++ay1Hcu/k9vSWTVQZG2bA1XEAlvy5lNaGRop+HI5V3fZiQiZe0+HM65dt68N4W +T72XY35kP3XXyYZLZjhMZPMZHrOeApSmfvFJimAyp2Ax1xtlmyBxyxh7vH33vxna +TXcK3o3hbraYKFihReIdzouG/4rN +-----END CERTIFICATE----- diff --git a/examples/AuthDemo/certs/server.csr b/examples/AuthDemo/certs/server.csr new file mode 100644 index 0000000..b9df041 --- /dev/null +++ b/examples/AuthDemo/certs/server.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICWjCCAUICAQAwFTETMBEGA1UEAwwKKi5kZW1vLmNvbTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAO+DB4oH0VHxb70tGUjAkYrsbZAWbQJPhHkzE3I2 +psIFfHzFsyW7U6sZ+N9uQqr1yHErNh/nNPQu6Qbn1s5MBRXBKUjKJBhMo3isVzJs +YVAvqtvMqlomIpvJe27SWYTGt7aUkGlrvlJdEnLUrdDqTNqJ8avbPCjewdMzPbQp +si2fviF8cd8ho0UZNVbVclXjzSC3X+xGQWVx7tnWsX9hrrGH0JlfigBv6/mG1/ux +l4dsGf5RlVK+Aej86Iv81BqAO4u2bP2Nkv8l7EQ/FBuo4ndLJTuLgboh2vUSI8Ta +HtTQKoqwY8AVTQG83yjgu3/6oruSYSINKh22+dLV1Ly2c28CAwEAAaAAMA0GCSqG +SIb3DQEBCwUAA4IBAQCVy2KgCiuQWWgy735Ym9hHoDaUtLgU1MG62s+ECgYlzz6j +ft88gCqZxVIMFUNqowekh9wan9XlGKYBwdPXpkIRB1Zg4mFoPamD6AMZEfUT1ooK +XJ0K6LE7Q4XY+HR/tHDsAf71QyKFblcIuRcIMFbOcp8paQENjYJpqiXfvQbmV7lS +StkIX3A2BBvogCc4qPZ90QHyOaALuVuquCkh1ULJhNLq+6sVW+bhUs9fGTOuhnJU +zYohoIJznxr5xglsLA5VnjZkmbtdewoHrvY+tNaAVEXFMEF9oBr8jtVuUiQGk7mF +o+dC43546tSaiqNxZ13rHsMDucC9fAS/O8AdeGr7 +-----END CERTIFICATE REQUEST----- diff --git a/examples/AuthDemo/certs/server.key b/examples/AuthDemo/certs/server.key new file mode 100644 index 0000000..622c9b9 --- /dev/null +++ b/examples/AuthDemo/certs/server.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEA74MHigfRUfFvvS0ZSMCRiuxtkBZtAk+EeTMTcjamwgV8fMWz +JbtTqxn4325CqvXIcSs2H+c09C7pBufWzkwFFcEpSMokGEyjeKxXMmxhUC+q28yq +WiYim8l7btJZhMa3tpSQaWu+Ul0SctSt0OpM2onxq9s8KN7B0zM9tCmyLZ++IXxx +3yGjRRk1VtVyVePNILdf7EZBZXHu2daxf2GusYfQmV+KAG/r+YbX+7GXh2wZ/lGV +Ur4B6Pzoi/zUGoA7i7Zs/Y2S/yXsRD8UG6jid0slO4uBuiHa9RIjxNoe1NAqirBj +wBVNAbzfKOC7f/qiu5JhIg0qHbb50tXUvLZzbwIDAQABAoIBADt/OSg4uO66Ix/D +TDyeWYlBIhZg+8NPLYFOBs6gdNxNsJbuJYqB9k7SrNgT88u0Mo6qRU+3h5gA7zIf +9WRZzgmRakgCruS6ZQFdDmwgMCxTKwZe2RJ71q0MZ/Unm8U39/sK/LSzZxvesu6D +looHKgA/tCEU3OTqMQvd9r4CfZiHUxHMdVbaV4skgLxUVSrkwPEv1OyreRsr6iVF +o+NJIN+WdPz236vrooYI91H17j8Tl5acHluu7Dr/q696FUYmrnfyO6dVMjai99fW +1124BGBH7kefJIDuxaur8J2txR4OBEVVhSx2Ghpe2JfNjZvpmia2m9Wo4t3JUSL0 +mxRl54ECgYEA+5kMNi9zDPKuGmUPLFsQAfk4eqcF69paBnEMOTd2nvWz03p/ugTW +o2bFs9s4McYJvnvWLSDlKP6NVIuSLaEBYuIHvjwR245NDxu9p+u9PTHZxbApkxNj +C3H/aIm/k0wtzHf943ShvLspjFqw7+q/nCf0T0oMrJaWkZWVI4vn1GcCgYEA87PY +qNPKiii3JwIMcgV9b3rDG6ulIj0lKKx5T8Jd+dVgLqGk3aah/PEsnVnBeg5YEB8r +MfqJ2OKzZ3t7jvJTX4pY9Q1zxFZ5R+rCWN5JdVZbofkekK29EkXIscVBf6YFlgAt +PbdVxZtZSKMRJB8+c+P9ovK5B0xQGg0bfJdRQ7kCgYEA8coFiFVVVc4rL0aLrG7f +FWZytryo3h57gdFGk/4PS3iJFuWUtipMM8BioxQ8DulpF9xe2gPQ9vKa0/NFyf// +Gw5prpJ//uXkfG6Gd0gAFz0/MdK4QZXSC3/Emqw2pdIB+YwfPGYrwPqFVVMa05Zg +CiwDh+d8Aqi9jq+YIg8j/mUCgYEAqzxGUzIlkXhUYOtWlVN4NLmcmDe+G1W9Y1v1 +DW70G1SrdXiM4FVyYsmPYKytfrbPd9x+vGpfK273QhII2oM4w9vw75bZLi7Ynwi8 +MDdYhEL+tcvWhzActtcj0o1YnXmpWSGcqE3Gzcd/L8OsiqYNet7K3BESo6cibXui +QaQNLLkCgYEA+tUOLkaJZlOuiEE5H5RDmFyC46G6R3Ukd5CQ/Dp4U75NLTIlEuGw +lIV/vcA0vy6WPL6rX2Gdm30oYq+xb+m9bDDCaXnkOxdPr5+1Zg4n3ibcFbBz/wmF +MjcYzC/D6dGK4r6h3tZeX7byNDVM26+qMJlgYd31FhoiFjlPLGuqFrs= +-----END RSA PRIVATE KEY----- diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 393ef81..13473ee 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -3,6 +3,12 @@ add_subdirectory(UtilDemo) add_subdirectory(CoroutineDemo) add_subdirectory(HttpDemo) add_subdirectory(CustomDemo) +add_subdirectory(AuthDemo) + +if(TARS_SSL) +add_subdirectory(SSLDemo) +endif() + add_subdirectory(PushDemo) add_subdirectory(QuickStartDemo) add_subdirectory(StressDemo) @@ -20,13 +26,27 @@ if(WIN32) COMMAND ../servant/script/busybox.exe bash ../examples/scripts/run-http.bat COMMENT "call run http") -if(TARS_HTTP2) + add_custom_target(run-auth + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + DEPENDS AuthServer AuthClient + COMMAND ../servant/script/busybox.exe bash ../examples/scripts/run-auth.bat + COMMENT "call run auth") + + if(TARS_HTTP2) add_custom_target(run-http2 WORKING_DIRECTORY ${CMAKE_BINARY_DIR} DEPENDS Http2Server Http2Client COMMAND ../servant/script/busybox.exe bash ../examples/scripts/run-http2.bat COMMENT "call run http2") -endif() + endif() + + if(TARS_SSL) + add_custom_target(run-ssl + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + DEPENDS SSLServer SSLClient + COMMAND ../servant/script/busybox.exe bash ../examples/scripts/run-ssl.bat + COMMENT "call run ssl") + endif() add_custom_target(run-co WORKING_DIRECTORY ${CMAKE_BINARY_DIR} @@ -55,6 +75,11 @@ endif() COMMAND ../servant/script/busybox.exe bash ../examples/scripts/run-push.bat COMMENT "call run all ${CMAKE_BINARY_DIR}") + add_custom_target(run-kill + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + COMMAND ../servant/script/busybox.exe bash ../examples/scripts/run-kill.bat + COMMENT "call run kill") + else(WIN32) add_custom_target(run-quick-start @@ -69,13 +94,27 @@ else(WIN32) COMMAND sh ../examples/scripts/run-http.sh COMMENT "call run http") -if(TARS_HTTP2) + add_custom_target(run-auth + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + DEPENDS AuthServer AuthClient + COMMAND sh ../examples/scripts/run-auth.sh + COMMENT "call run auth") + + if(TARS_HTTP2) add_custom_target(run-http2 WORKING_DIRECTORY ${CMAKE_BINARY_DIR} DEPENDS Http2Server Http2Client COMMAND sh ../examples/scripts/run-http2.sh COMMENT "call run http2") -endif() + endif() + + if(TARS_SSL) + add_custom_target(run-ssl + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + DEPENDS SSLServer SSLClient + COMMAND sh ../examples/scripts/run-ssl.sh + COMMENT "call run ssl") + endif() add_custom_target(run-co WORKING_DIRECTORY ${CMAKE_BINARY_DIR} @@ -103,4 +142,9 @@ endif() COMMAND sh ../examples/scripts/run-co.sh COMMAND sh ../examples/scripts/run-push.sh COMMENT "call run all") + + add_custom_target(run-kill + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + COMMAND sh ../examples/scripts/run-kill.sh + COMMENT "call run kill") endif(WIN32) \ No newline at end of file diff --git a/examples/QuickStartDemo/HelloServer/Server/HelloServer.cpp b/examples/QuickStartDemo/HelloServer/Server/SSLServer.cpp similarity index 100% rename from examples/QuickStartDemo/HelloServer/Server/HelloServer.cpp rename to examples/QuickStartDemo/HelloServer/Server/SSLServer.cpp diff --git a/examples/SSLDemo/CMakeLists.txt b/examples/SSLDemo/CMakeLists.txt new file mode 100644 index 0000000..6345c28 --- /dev/null +++ b/examples/SSLDemo/CMakeLists.txt @@ -0,0 +1,5 @@ + +include_directories(Server) +add_subdirectory(Server) +add_subdirectory(Client) + diff --git a/examples/SSLDemo/Client/CMakeLists.txt b/examples/SSLDemo/Client/CMakeLists.txt new file mode 100644 index 0000000..c82838c --- /dev/null +++ b/examples/SSLDemo/Client/CMakeLists.txt @@ -0,0 +1 @@ +build_tars_server("SSLClient" "SSLServer") \ No newline at end of file diff --git a/examples/SSLDemo/Client/config.conf b/examples/SSLDemo/Client/config.conf new file mode 100755 index 0000000..07daeb5 --- /dev/null +++ b/examples/SSLDemo/Client/config.conf @@ -0,0 +1,33 @@ + + + + + #tarsregistry locator + locator = tars.tarsregistry.QueryObj@tcp -h 127.0.0.1 -p 17890 + #max invoke timeout + sync-invoke-timeout = 5000 + #refresh endpoint interval + refresh-endpoint-interval = 10000 + #stat obj + stat = tars.tarsstat.StatObj + #max send queue length limit + sendqueuelimit = 100000 + #async queue length limit + asyncqueuecap = 100000 + #async callback thread num + asyncthread = 3 + #net thread + netthread = 1 + #merge net and sync thread + mergenetasync = 0 + #module name + modulename = TestApp.SSLClient + #server crt + ca = ../examples/SSLDemo/certs/server.crt + #can be empty + cert = ../examples/SSLDemo/certs/client.crt + #can be empty + key = ../examples/SSLDemo/certs/client.key + + + diff --git a/examples/SSLDemo/Client/main.cpp b/examples/SSLDemo/Client/main.cpp new file mode 100644 index 0000000..740d566 --- /dev/null +++ b/examples/SSLDemo/Client/main.cpp @@ -0,0 +1,224 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +#include +#include "servant/Communicator.h" +#include "ssl.h" +#include "util/tc_option.h" + +using namespace std; +using namespace tars; +using namespace TestApp; + +Communicator* _comm; + +static string helloObj = "TestApp.SSLServer.SSLObj@ssl -h 127.0.0.1 -p 9005"; + +struct Param +{ + int count; + string call; + int thread; + int buffersize; + int netthread; + + HelloPrx pPrx; +}; + +Param param; +std::atomic callback_count(0); + +struct HelloCallback : public HelloPrxCallback +{ + HelloCallback(int64_t t, int i, int c) : start(t), cur(i), count(c) + { + + } + + //call back + virtual void callback_testHello(int ret, const string &r) + { + assert(ret == 0); + callback_count++; + + if(cur == count-1) + { + int64_t cost = TC_Common::now2us() - start; + cout << "callback_testHello count:" << count << ", " << cost << " us, avg:" << 1.*cost/count << "us" << endl; + } + } + + virtual void callback_testHello_exception(tars::Int32 ret) + { + cout << "callback exception:" << ret << endl; + } + + int64_t start; + int cur; + int count; +}; + + +void syncCall(int c) +{ + string buffer(param.buffersize, 'a'); + + int64_t t = TC_Common::now2us(); + //发起远程调用 + for (int i = 0; i < c; ++i) + { + string r; + + try + { + param.pPrx->testHello(buffer, r); + } + catch(exception& e) + { + cout << "exception:" << e.what() << endl; + } + ++callback_count; + + } + + int64_t cost = TC_Common::now2us() - t; + cout << "syncCall total:" << cost << "us, avg:" << 1.*cost/c << "us" << endl; +} + + +void asyncCall(int c) +{ + int64_t t = TC_Common::now2us(); + + string buffer(param.buffersize, 'a'); + + //发起远程调用 + for (int i = 0; i < c; ++i) + { + HelloPrxCallbackPtr p = new HelloCallback(t, i, c); + + try + { + param.pPrx->async_testHello(p, buffer); + } + catch(exception& e) + { + cout << "exception:" << e.what() << endl; + } + } + + int64_t cost = TC_Common::now2us() - t; + cout << "asyncCall send:" << cost << "us, avg:" << 1.*cost/c << "us" << endl; +} + +int main(int argc, char *argv[]) +{ + try + { + if (argc < 6) + { + cout << "Usage:" << argv[0] << "--config=conf --count=1000 --call=[sync|async] --thread=1 --buffersize=1000 --netthread=1" << endl; + + return 0; + } + + TC_Option option; + option.decode(argc, argv); + + param.count = TC_Common::strto(option.getValue("count")); + if(param.count <= 0) param.count = 1000; + param.buffersize = TC_Common::strto(option.getValue("buffersize")); + if(param.buffersize <= 0) param.buffersize = 1000; + param.call = option.getValue("call"); + if(param.call.empty()) param.call = "sync"; + param.thread = TC_Common::strto(option.getValue("thread")); + if(param.thread <= 0) param.thread = 1; + param.netthread = TC_Common::strto(option.getValue("netthread")); + if(param.netthread <= 0) param.netthread = 1; + + _comm = new Communicator(); + + TC_Config conf; + conf.parseFile(option.getValue("config")); + _comm->setProperty(conf); + +// TarsRollLogger::getInstance()->logger()->setLogLevel(6); + + _comm->setProperty("sendqueuelimit", "1000000"); + _comm->setProperty("asyncqueuecap", "1000000"); + + _comm->setProperty("netthread", TC_Common::tostr(param.netthread)); + + param.pPrx = _comm->stringToProxy(helloObj); + + param.pPrx->tars_connect_timeout(5000); + param.pPrx->tars_async_timeout(60*1000); + param.pPrx->tars_ping(); + + int64_t start = TC_Common::now2us(); + + std::function func; + + if (param.call == "sync") + { + func = syncCall; + } + else if (param.call == "async") + { + func = asyncCall; + } + else + { + cout << "no func, exits" << endl; + exit(0); + } + + vector vt; + for(int i = 0 ; i< param.thread; i++) + { + vt.push_back(new std::thread(func, param.count)); + } + + std::thread print([&]{while(callback_count != param.count * param.thread) { + cout << param.call << ": ----------finish count:" << callback_count << endl; + std::this_thread::sleep_for(std::chrono::seconds(1)); + };}); + + for(size_t i = 0 ; i< vt.size(); i++) + { + vt[i]->join(); + delete vt[i]; + } + + cout << "(pid:" << std::this_thread::get_id() << ")" + << "(count:" << param.count << ")" + << "(use ms:" << (TC_Common::now2us() - start)/1000 << ")" + << endl; + + while(callback_count != param.count * param.thread) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + print.join(); + cout << "----------finish count:" << callback_count << endl; + } + catch(exception &ex) + { + cout << ex.what() << endl; + } + cout << "main return." << endl; + + return 0; +} diff --git a/examples/SSLDemo/Server/CMakeLists.txt b/examples/SSLDemo/Server/CMakeLists.txt new file mode 100644 index 0000000..fb2bea7 --- /dev/null +++ b/examples/SSLDemo/Server/CMakeLists.txt @@ -0,0 +1 @@ +build_tars_server("SSLServer" "") diff --git a/examples/SSLDemo/Server/SSLImp.cpp b/examples/SSLDemo/Server/SSLImp.cpp new file mode 100644 index 0000000..57e36ac --- /dev/null +++ b/examples/SSLDemo/Server/SSLImp.cpp @@ -0,0 +1,43 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +#include "SSLImp.h" +#include "servant/Application.h" + +using namespace std; + +////////////////////////////////////////////////////// +void SSLImp::initialize() +{ + //initialize servant here: + //... +} + +////////////////////////////////////////////////////// +void SSLImp::destroy() +{ + //destroy servant here: + //... +} + +int SSLImp::testHello(const std::string &sReq, std::string &sRsp, tars::TarsCurrentPtr current) +{ +// TLOGDEBUG("SSLImp::testHellosReq:"<(ServerConfig::Application + "." + ServerConfig::ServerName + ".SSLObj"); + addServant(ServerConfig::Application + "." + ServerConfig::ServerName + ".SSL2Obj"); +} +///////////////////////////////////////////////////////////////// +void +SSLServer::destroyApp() +{ + //destroy application here: + //... +} +///////////////////////////////////////////////////////////////// +int +main(int argc, char* argv[]) +{ + try + { + g_app.main(argc, argv); + g_app.waitForShutdown(); + } + catch (std::exception& e) + { + cerr << "std::exception:" << e.what() << std::endl; + } + catch (...) + { + cerr << "unknown exception." << std::endl; + } + return -1; +} +///////////////////////////////////////////////////////////////// diff --git a/examples/SSLDemo/Server/SSLServer.h b/examples/SSLDemo/Server/SSLServer.h new file mode 100644 index 0000000..5bfdbcc --- /dev/null +++ b/examples/SSLDemo/Server/SSLServer.h @@ -0,0 +1,50 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +#ifndef _HelloServer_H_ +#define _HelloServer_H_ + +#include +#include "servant/Application.h" + +using namespace tars; + +/** + * + **/ +class SSLServer : public Application +{ +public: + /** + * + **/ + virtual ~SSLServer() {}; + + /** + * + **/ + virtual void initialize(); + + /** + * + **/ + virtual void destroyApp(); +}; + +extern SSLServer g_app; + +//////////////////////////////////////////// +#endif diff --git a/examples/SSLDemo/Server/config.conf b/examples/SSLDemo/Server/config.conf new file mode 100755 index 0000000..002c91e --- /dev/null +++ b/examples/SSLDemo/Server/config.conf @@ -0,0 +1,95 @@ + + + + + #tarsregistry locator + locator = tars.tarsregistry.QueryObj@tcp -h 127.0.0.1 -p 17890 + #max invoke timeout + sync-invoke-timeout = 5000 + #refresh endpoint interval + refresh-endpoint-interval = 10000 + #stat obj + stat = tars.tarsstat.StatObj + #max send queue length limit + sendqueuelimit = 100000 + #async queue length limit + asyncqueuecap = 100000 + #async callback thread num + asyncthread = 3 + #net thread + netthread = 1 + #merge net and sync thread + mergenetasync = 0 + #module name + modulename = TestApp.SSLServer + + + + + #not cout + closecout = 0 + #app name + app = TestApp + #server name + server = SSLServer + #path + basepath = ./ + datapath = ./ + #log path + logpath = ./ + #merge net and imp thread + mergenetimp = 0 + #local ip, for tarsnode +# local = tcp -h 127.0.0.1 -p 15001 -t 10000 + + #tarsnode +# node = ServerObj@tcp -h 127.0.0.1 -p 2345 -t 10000 + #config obj +# config = tars.tarsconfig.ConfigObj + #notify obj +# notify = tars.tarsconfig.NotifyObj + #log obj +# log = tars.tarslog.LogObj + + #client crt, it can be empty when verifyclient is 0 + ca = ../examples/SSLDemo/certs/client.crt + cert = ../examples/SSLDemo/certs/server.crt + key = ../examples/SSLDemo/certs/server.key + #default is 0 + verifyclient = 0 + + + #ip:port:timeout + endpoint = ssl -h 127.0.0.1 -p 9005 -t 10000 + #allow ip + allow = + #max connection num + maxconns = 4096 + #imp thread num + threads = 5 + #servant + servant = TestApp.SSLServer.SSLObj + #queue capacity + queuecap = 1000000 + #tars protocol + protocol = tars + + + #ip:port:timeout + endpoint = ssl -h 127.0.0.1 -p 9006 -t 10000 + #allow ip + allow = + #max connection num + maxconns = 4096 + #imp thread num + threads = 5 + #servant + servant = TestApp.SSLServer.SSL2Obj + #queue capacity + queuecap = 1000000 + #tars protocol + protocol = tars + + + + diff --git a/examples/SSLDemo/Server/ssl.h b/examples/SSLDemo/Server/ssl.h new file mode 100644 index 0000000..53b5b30 --- /dev/null +++ b/examples/SSLDemo/Server/ssl.h @@ -0,0 +1,471 @@ +// ********************************************************************** +// This file was generated by a TARS parser! +// TARS version 2.0.0. +// ********************************************************************** + +#ifndef __SSL_H_ +#define __SSL_H_ + +#include +#include +#include +#include "tup/Tars.h" +#include "tup/TarsJson.h" +using namespace std; +#include "servant/ServantProxy.h" +#include "servant/Servant.h" + + +namespace TestApp +{ + + /* callback of async proxy for client */ + class HelloPrxCallback: public tars::ServantProxyCallback + { + public: + virtual ~HelloPrxCallback(){} + virtual void callback_test(tars::Int32 ret) + { throw std::runtime_error("callback_test() override incorrect."); } + virtual void callback_test_exception(tars::Int32 ret) + { throw std::runtime_error("callback_test_exception() override incorrect."); } + + virtual void callback_testHello(tars::Int32 ret, const std::string& sRsp) + { throw std::runtime_error("callback_testHello() override incorrect."); } + virtual void callback_testHello_exception(tars::Int32 ret) + { throw std::runtime_error("callback_testHello_exception() override incorrect."); } + + public: + virtual const map & getResponseContext() const + { + CallbackThreadData * pCbtd = CallbackThreadData::getData(); + assert(pCbtd != NULL); + + if(!pCbtd->getContextValid()) + { + throw TC_Exception("cann't get response context"); + } + return pCbtd->getResponseContext(); + } + + public: + virtual int onDispatch(tars::ReqMessagePtr msg) + { + static ::std::string __Hello_all[]= + { + "test", + "testHello" + }; + pair r = equal_range(__Hello_all, __Hello_all+2, string(msg->request.sFuncName)); + if(r.first == r.second) return tars::TARSSERVERNOFUNCERR; + switch(r.first - __Hello_all) + { + case 0: + { + if (msg->response->iRet != tars::TARSSERVERSUCCESS) + { + callback_test_exception(msg->response->iRet); + + return msg->response->iRet; + } + tars::TarsInputStream _is; + + _is.setBuffer(msg->response->sBuffer); + tars::Int32 _ret; + _is.read(_ret, 0, true); + + CallbackThreadData * pCbtd = CallbackThreadData::getData(); + assert(pCbtd != NULL); + + pCbtd->setResponseContext(msg->response->context); + + callback_test(_ret); + + pCbtd->delResponseContext(); + + return tars::TARSSERVERSUCCESS; + + } + case 1: + { + if (msg->response->iRet != tars::TARSSERVERSUCCESS) + { + callback_testHello_exception(msg->response->iRet); + + return msg->response->iRet; + } + tars::TarsInputStream _is; + + _is.setBuffer(msg->response->sBuffer); + tars::Int32 _ret; + _is.read(_ret, 0, true); + + std::string sRsp; + _is.read(sRsp, 2, true); + CallbackThreadData * pCbtd = CallbackThreadData::getData(); + assert(pCbtd != NULL); + + pCbtd->setResponseContext(msg->response->context); + + callback_testHello(_ret, sRsp); + + pCbtd->delResponseContext(); + + return tars::TARSSERVERSUCCESS; + + } + } + return tars::TARSSERVERNOFUNCERR; + } + + }; + typedef tars::TC_AutoPtr HelloPrxCallbackPtr; + + /* callback of coroutine async proxy for client */ + class HelloCoroPrxCallback: public HelloPrxCallback + { + public: + virtual ~HelloCoroPrxCallback(){} + public: + virtual const map & getResponseContext() const { return _mRspContext; } + + virtual void setResponseContext(const map &mContext) { _mRspContext = mContext; } + + public: + int onDispatch(tars::ReqMessagePtr msg) + { + static ::std::string __Hello_all[]= + { + "test", + "testHello" + }; + + pair r = equal_range(__Hello_all, __Hello_all+2, string(msg->request.sFuncName)); + if(r.first == r.second) return tars::TARSSERVERNOFUNCERR; + switch(r.first - __Hello_all) + { + case 0: + { + if (msg->response->iRet != tars::TARSSERVERSUCCESS) + { + callback_test_exception(msg->response->iRet); + + return msg->response->iRet; + } + tars::TarsInputStream _is; + + _is.setBuffer(msg->response->sBuffer); + try + { + tars::Int32 _ret; + _is.read(_ret, 0, true); + + setResponseContext(msg->response->context); + + callback_test(_ret); + + } + catch(std::exception &ex) + { + callback_test_exception(tars::TARSCLIENTDECODEERR); + + return tars::TARSCLIENTDECODEERR; + } + catch(...) + { + callback_test_exception(tars::TARSCLIENTDECODEERR); + + return tars::TARSCLIENTDECODEERR; + } + + return tars::TARSSERVERSUCCESS; + + } + case 1: + { + if (msg->response->iRet != tars::TARSSERVERSUCCESS) + { + callback_testHello_exception(msg->response->iRet); + + return msg->response->iRet; + } + tars::TarsInputStream _is; + + _is.setBuffer(msg->response->sBuffer); + try + { + tars::Int32 _ret; + _is.read(_ret, 0, true); + + std::string sRsp; + _is.read(sRsp, 2, true); + setResponseContext(msg->response->context); + + callback_testHello(_ret, sRsp); + + } + catch(std::exception &ex) + { + callback_testHello_exception(tars::TARSCLIENTDECODEERR); + + return tars::TARSCLIENTDECODEERR; + } + catch(...) + { + callback_testHello_exception(tars::TARSCLIENTDECODEERR); + + return tars::TARSCLIENTDECODEERR; + } + + return tars::TARSSERVERSUCCESS; + + } + } + return tars::TARSSERVERNOFUNCERR; + } + + protected: + map _mRspContext; + }; + typedef tars::TC_AutoPtr HelloCoroPrxCallbackPtr; + + /* proxy for client */ + class HelloProxy : public tars::ServantProxy + { + public: + typedef map TARS_CONTEXT; + tars::Int32 test(const map &context = TARS_CONTEXT(),map * pResponseContext = NULL) + { + tars::TarsOutputStream _os; + std::map _mStatus; + shared_ptr rep = tars_invoke(tars::TARSNORMAL,"test", _os, context, _mStatus); + if(pResponseContext) + { + pResponseContext->swap(rep->context); + } + + tars::TarsInputStream _is; + _is.setBuffer(rep->sBuffer); + tars::Int32 _ret; + _is.read(_ret, 0, true); + return _ret; + } + + void async_test(HelloPrxCallbackPtr callback,const map& context = TARS_CONTEXT()) + { + tars::TarsOutputStream _os; + std::map _mStatus; + tars_invoke_async(tars::TARSNORMAL,"test", _os, context, _mStatus, callback); + } + + void coro_test(HelloCoroPrxCallbackPtr callback,const map& context = TARS_CONTEXT()) + { + tars::TarsOutputStream _os; + std::map _mStatus; + tars_invoke_async(tars::TARSNORMAL,"test", _os, context, _mStatus, callback, true); + } + + tars::Int32 testHello(const std::string & sReq,std::string &sRsp,const map &context = TARS_CONTEXT(),map * pResponseContext = NULL) + { + tars::TarsOutputStream _os; + _os.write(sReq, 1); + _os.write(sRsp, 2); + std::map _mStatus; + shared_ptr rep = tars_invoke(tars::TARSNORMAL,"testHello", _os, context, _mStatus); + if(pResponseContext) + { + pResponseContext->swap(rep->context); + } + + tars::TarsInputStream _is; + _is.setBuffer(rep->sBuffer); + tars::Int32 _ret; + _is.read(_ret, 0, true); + _is.read(sRsp, 2, true); + return _ret; + } + + void async_testHello(HelloPrxCallbackPtr callback,const std::string &sReq,const map& context = TARS_CONTEXT()) + { + tars::TarsOutputStream _os; + _os.write(sReq, 1); + std::map _mStatus; + tars_invoke_async(tars::TARSNORMAL,"testHello", _os, context, _mStatus, callback); + } + + void coro_testHello(HelloCoroPrxCallbackPtr callback,const std::string &sReq,const map& context = TARS_CONTEXT()) + { + tars::TarsOutputStream _os; + _os.write(sReq, 1); + std::map _mStatus; + tars_invoke_async(tars::TARSNORMAL,"testHello", _os, context, _mStatus, callback, true); + } + + HelloProxy* tars_hash(int64_t key) + { + return (HelloProxy*)ServantProxy::tars_hash(key); + } + + HelloProxy* tars_consistent_hash(int64_t key) + { + return (HelloProxy*)ServantProxy::tars_consistent_hash(key); + } + + HelloProxy* tars_set_timeout(int msecond) + { + return (HelloProxy*)ServantProxy::tars_set_timeout(msecond); + } + + static const char* tars_prxname() { return "HelloProxy"; } + }; + typedef tars::TC_AutoPtr HelloPrx; + + /* servant for server */ + class Hello : public tars::Servant + { + public: + virtual ~Hello(){} + virtual tars::Int32 test(tars::TarsCurrentPtr current) = 0; + static void async_response_test(tars::TarsCurrentPtr current, tars::Int32 _ret) + { + if (current->getRequestVersion() == TUPVERSION ) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(current->getRequestVersion()); + tarsAttr.put("", _ret); + + vector sTupResponseBuffer; + tarsAttr.encode(sTupResponseBuffer); + current->sendResponse(tars::TARSSERVERSUCCESS, sTupResponseBuffer); + } + else + { + tars::TarsOutputStream _os; + _os.write(_ret, 0); + + current->sendResponse(tars::TARSSERVERSUCCESS, _os.getByteBuffer()); + } + } + + virtual tars::Int32 testHello(const std::string & sReq,std::string &sRsp,tars::TarsCurrentPtr current) = 0; + static void async_response_testHello(tars::TarsCurrentPtr current, tars::Int32 _ret, const std::string &sRsp) + { + if (current->getRequestVersion() == TUPVERSION ) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(current->getRequestVersion()); + tarsAttr.put("", _ret); + tarsAttr.put("sRsp", sRsp); + + vector sTupResponseBuffer; + tarsAttr.encode(sTupResponseBuffer); + current->sendResponse(tars::TARSSERVERSUCCESS, sTupResponseBuffer); + } + else + { + tars::TarsOutputStream _os; + _os.write(_ret, 0); + + _os.write(sRsp, 2); + + current->sendResponse(tars::TARSSERVERSUCCESS, _os.getByteBuffer()); + } + } + + public: + int onDispatch(tars::TarsCurrentPtr _current, vector &_sResponseBuffer) + { + static ::std::string __TestApp__Hello_all[]= + { + "test", + "testHello" + }; + + pair r = equal_range(__TestApp__Hello_all, __TestApp__Hello_all+2, _current->getFuncName()); + if(r.first == r.second) return tars::TARSSERVERNOFUNCERR; + switch(r.first - __TestApp__Hello_all) + { + case 0: + { + tars::TarsInputStream _is; + _is.setBuffer(_current->getRequestBuffer()); + if (_current->getRequestVersion() == TUPVERSION) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(_current->getRequestVersion()); + tarsAttr.decode(_current->getRequestBuffer()); + } + else + { + } + tars::Int32 _ret = test(_current); + if(_current->isResponse()) + { + if (_current->getRequestVersion() == TUPVERSION ) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(_current->getRequestVersion()); + tarsAttr.put("", _ret); + tarsAttr.encode(_sResponseBuffer); + } + else + { + tars::TarsOutputStream _os; + _os.write(_ret, 0); + _os.swap(_sResponseBuffer); + } + } + return tars::TARSSERVERSUCCESS; + + } + case 1: + { + tars::TarsInputStream _is; + _is.setBuffer(_current->getRequestBuffer()); + std::string sReq; + std::string sRsp; + if (_current->getRequestVersion() == TUPVERSION) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(_current->getRequestVersion()); + tarsAttr.decode(_current->getRequestBuffer()); + tarsAttr.get("sReq", sReq); + tarsAttr.getByDefault("sRsp", sRsp, sRsp); + } + else + { + _is.read(sReq, 1, true); + _is.read(sRsp, 2, false); + } + tars::Int32 _ret = testHello(sReq,sRsp, _current); + if(_current->isResponse()) + { + if (_current->getRequestVersion() == TUPVERSION ) + { + UniAttribute tarsAttr; + tarsAttr.setVersion(_current->getRequestVersion()); + tarsAttr.put("", _ret); + tarsAttr.put("sRsp", sRsp); + tarsAttr.encode(_sResponseBuffer); + } + else + { + tars::TarsOutputStream _os; + _os.write(_ret, 0); + _os.write(sRsp, 2); + _os.swap(_sResponseBuffer); + } + } + return tars::TARSSERVERSUCCESS; + + } + } + return tars::TARSSERVERNOFUNCERR; + } + }; + + +} + + + +#endif diff --git a/examples/SSLDemo/Server/ssl.tars b/examples/SSLDemo/Server/ssl.tars new file mode 100644 index 0000000..174c4f3 --- /dev/null +++ b/examples/SSLDemo/Server/ssl.tars @@ -0,0 +1,26 @@ +/** + * Tencent is pleased to support the open source community by making Tars available. + * + * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +module TestApp +{ + +interface Hello +{ + int test(); + int testHello(string sReq, out string sRsp); +}; + +}; diff --git a/examples/SSLDemo/certs/ca.crt b/examples/SSLDemo/certs/ca.crt new file mode 100644 index 0000000..a57ea14 --- /dev/null +++ b/examples/SSLDemo/certs/ca.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDCzCCAfOgAwIBAgIUfmd8TIa6hXXp/KibyRhjrYGhY+gwDQYJKoZIhvcNAQEL +BQAwFTETMBEGA1UEAwwKKi5kZW1vLmNvbTAeFw0yMDAyMTMxMjMwNDdaFw0zMzEw +MjIxMjMwNDdaMBUxEzARBgNVBAMMCiouZGVtby5jb20wggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDOV6uDon7+RDiCpHzOaAa5P1vtj1k0YEkWbLwsBBDT +wYdkXnnfYHxQfY9kh9Gp13Otx0xCdTVBDQAlAxqAK9zH7dgxxysvcQE2ZL9mnkFx +BksP6kHRM//HQM9ylaPCgyA5L2nsixLZ4ipkI1td+n/nL6mB4GIAhwSVJlN74CXE +FXPjMaS7dEdRfdVz6gD2h1L8jFF9f7S9ZawZ8kw+JWUKflzr0L9mRGbuhukCJ+3N +TZFKHSL1Yy0NsE0nM8X0ncmpQExQ0sqrKgmAHnju9jXvMbxMjFI2AwrLPtV8U2Hg +ziztJmdPqM8LIQZpmeynq9eP1+AD7PEu8C7LsV5wTWndAgMBAAGjUzBRMB0GA1Ud +DgQWBBQ4RfWqsDwlD00IhcvCY40gYJtTuDAfBgNVHSMEGDAWgBQ4RfWqsDwlD00I +hcvCY40gYJtTuDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCj +DbEL8nvVzyhW01O3/5oJSd8Z1g+7WupLmtF5OZuKN2XKDICLRxtow7XHiJLlkgZW +4K/kJeXvbPYRrKTm6PHJ63bWKl6YaD3/Vm9wgCLC48ikrOqiEL2w/mI/zFeEvZ3K +U50tLnllY2L0NZxgRZ7wZZqU6qKMxHn7UMYtfzSf7XzBBXi6qzf290DNminr9YgT +afsP+cjL74TchyZifFqI+sGhXO9IY8+lrRYoUXUwcE0DPWHe08UrAtT1E1b7SU2o +pvlUABuUbufvTwu1Cj6mDqOjQQUmWDqNgb2FeNWsmdkBqrhxkLorLiNb5o/YgCKJ +Patq2TfT09tiaeNAl/cF +-----END CERTIFICATE----- diff --git a/examples/SSLDemo/certs/ca.key b/examples/SSLDemo/certs/ca.key new file mode 100644 index 0000000..d91cf9c --- /dev/null +++ b/examples/SSLDemo/certs/ca.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAzlerg6J+/kQ4gqR8zmgGuT9b7Y9ZNGBJFmy8LAQQ08GHZF55 +32B8UH2PZIfRqddzrcdMQnU1QQ0AJQMagCvcx+3YMccrL3EBNmS/Zp5BcQZLD+pB +0TP/x0DPcpWjwoMgOS9p7IsS2eIqZCNbXfp/5y+pgeBiAIcElSZTe+AlxBVz4zGk +u3RHUX3Vc+oA9odS/IxRfX+0vWWsGfJMPiVlCn5c69C/ZkRm7obpAiftzU2RSh0i +9WMtDbBNJzPF9J3JqUBMUNLKqyoJgB547vY17zG8TIxSNgMKyz7VfFNh4M4s7SZn +T6jPCyEGaZnsp6vXj9fgA+zxLvAuy7FecE1p3QIDAQABAoIBAG5V6tzEs2t7R0x0 +cFhev9mmy51IHccoBWz8T9KpieXxglhlPH35tf/EZDy5c5+CGdU+0MRosEVMkls4 +QZ9v1OsDf6t+eNUxdBiF3uMclJm/Z7vm47LeP1NokIURBzQnsb9iXx2hcD8Z9Nj/ +Hwgtvt78WYOdXEoz6HtotxNyVD940uEg9U3dPKBAVJRFtLa4pBtSbj1ZpElFsR/l +f94+uwgESsgZF7OZZiKEklLpC2/xPi4m/IDxCBjy3GW7nou6T1Cy90DBX7OfhFur +fQjcAzC4AKvGdkT/0ocQw6jdtGVzDgYEO7pD7r6rpubwsbYXaXOgBvzELUSM+nj3 +Lpv+anECgYEA9VBUAAzcn3mCvf5Dh/VrK997Ll4+/0F0SRFBGW2x/ChRKaIXIMCb +VGIRTIhPACl98v8ctwML9sYQ+4bBYabwTxkCtHS1OoZlUUUzCusVaQ+6VmbWHadd +Ua+Gl0cfM6S5jNpbkoiAG7lRA76GH+QfOlCawhgbWWGD5iT2wHBVk88CgYEA11S+ +kHDcPzlHHfiobFlJimeeb4j5G2I26fZSlaO5gAkD8yzxov7zMSSemfAE8j/fS0+6 +EZkArsyro9lATlWejdssndKku7uykuvwIQvKCYd13lD0/Cpvb101MuM7CcYXsoDv +z7vaaV94Xe8TgL3BY7+QYD7mANC1XwUZS17eVpMCgYEAxd+QkiXNw/kgg55X3JAS +bWYrl0BAMmcapGF9kERSX+IpbZqoayvRXyRnbcM5bhkJ1fr/r4OOn/Qt+KU+0UT1 +6+dxrhvBnz6O9RoLTRBIyeD83fq/VVYNyPj7aITe3ypM3Re4656dLz+w4INK7uh0 +Y/Zmjo8haFxnJznDq4AxFzMCgYAMwGb8lMJmOBUfED+hEvSI7rPyNPFTjtBjsIOZ +evWcQGxsdSfmGCT8rwd5ZD5WvjOR+SmyqxXgRByR+maVfPqDugv9WKEKwQXFL5Wr +z0/qmov/W1n2qOiqdqGU3uH7JTD4ECyjZ6N6g/3TyjmkcRhHuOtq1661M6bZ9qpV +zUtrYwKBgQDoV7ra5JQ217LB49ZXqWMyA5CGMf6NxMwVzPy7H+Pk2F6FQw7lXPEy +XCYD94lhcFuZIUkfqjbG96C1z18ALF7XaxwidYJlkrhXrgZigsJtcUG+RDaavpfI +u5qVhzJbGexoo7hXJeDvgilu525eoysmnlTATqNkRWdP7T4w+uu86w== +-----END RSA PRIVATE KEY----- diff --git a/examples/SSLDemo/certs/ca.srl b/examples/SSLDemo/certs/ca.srl new file mode 100644 index 0000000..9bafb6c --- /dev/null +++ b/examples/SSLDemo/certs/ca.srl @@ -0,0 +1 @@ +5C1561567852EF51D268687494029145127A56C3 diff --git a/examples/SSLDemo/certs/client.crt b/examples/SSLDemo/certs/client.crt new file mode 100644 index 0000000..dde025d --- /dev/null +++ b/examples/SSLDemo/certs/client.crt @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICsTCCAZkCFFwVYVZ4Uu9R0mhodJQCkUUSelbDMA0GCSqGSIb3DQEBCwUAMBUx +EzARBgNVBAMMCiouZGVtby5jb20wHhcNMjAwMjEzMTIzMDQ3WhcNMzMxMDIyMTIz +MDQ3WjAVMRMwEQYDVQQDDAoqLmRlbW8uY29tMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEAqOp2R0JnTBeKjQmHDjIKHlT5RLfk/RTksrw88xdrQgOLbceB +rjZg82yfTJkFW4rTVjjSphNbPCynFwg+BxK9MXfJr9Rs9dsBSpmCViXiw6pmDSZz +on691cL4PYEEeom8y5egp/OU6IQRcNwpyffiVDPYSR8qH3PzTi7RXLGNGtdLFi0I +YeZ+FYlGjTlBQRyqNvOD3nEvIocNtyWP9+D17wtPENA2AbWbHV2CbKFoc6Zx98Fw +KtVkz94Z4duzjLUZOwjcTWK+zKxfRzVDZtxlMTOA261N8CUha8nl+c4uNgTC0h0J +PE5JTewwXdGftNiR2xWgVLvWfbFg73x0RemoyQIDAQABMA0GCSqGSIb3DQEBCwUA +A4IBAQBxnTndUG6zfHVz5t/2j6pppqY93lXaHoi8VD2dXgtzda8BqgulwZAe8x2v +BAP522Ch3AusIFZs9ejLZt97BHkf30uhnoKKGhHsKDxq4ll338+PEWkvUdQNl1Xi +RZyC4VXwji4DABlM5BKtr0vNbYW8hkZWzOCmM1qHx8FbGmb4Z5lO3t4e7tCiwX72 +yY7/5zqZSS8b5BDMQJtDXjV2yZDJLsfdRx8NRuwsSNPQTkm+MFHLV42mO5vH0Ugb +ULHNRXQsThwO4p1y0Nlo4/Ti0qIh4II0sIkW9chigaGuqxo2D27L2o1hkBbjiLIY +blrKSx8QEWyC7Etnm4KT9Cxs5xmg +-----END CERTIFICATE----- diff --git a/examples/SSLDemo/certs/client.csr b/examples/SSLDemo/certs/client.csr new file mode 100644 index 0000000..2d8bd62 --- /dev/null +++ b/examples/SSLDemo/certs/client.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICWjCCAUICAQAwFTETMBEGA1UEAwwKKi5kZW1vLmNvbTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAKjqdkdCZ0wXio0Jhw4yCh5U+US35P0U5LK8PPMX +a0IDi23Hga42YPNsn0yZBVuK01Y40qYTWzwspxcIPgcSvTF3ya/UbPXbAUqZglYl +4sOqZg0mc6J+vdXC+D2BBHqJvMuXoKfzlOiEEXDcKcn34lQz2EkfKh9z804u0Vyx +jRrXSxYtCGHmfhWJRo05QUEcqjbzg95xLyKHDbclj/fg9e8LTxDQNgG1mx1dgmyh +aHOmcffBcCrVZM/eGeHbs4y1GTsI3E1ivsysX0c1Q2bcZTEzgNutTfAlIWvJ5fnO +LjYEwtIdCTxOSU3sMF3Rn7TYkdsVoFS71n2xYO98dEXpqMkCAwEAAaAAMA0GCSqG +SIb3DQEBCwUAA4IBAQBxzQt4BuF7HIAReW0RAWpAXoJVJlLKoObIuRwT0dqcHbRs +uZKovoKjhLlI0Cg2ljLj+p87fbHAl256pnUa91B+Qzy+NwNxltXqKE5fYuH1hvP1 +SRJ/qaXPbWmX7ZQ0y3eBE17HOAP4GVpURbsOVQdaxJOjxIeFG6H+FmKNMzCo8e+B +KB3bYCHCPSI8VLWPbKF8fbu1JmBstjikHEEW85WiV/ZGqnYIT2CijyuKFEzYwkZg +sIW5xjzqaYKo+RzwYeYqvL6kvniWHaxwdnEz3t0yr4V51ouPvoimSPHsA8qklQil ++ZgYlvSmeNTlQy80UoY81IzHiADxBTzscBPUjILW +-----END CERTIFICATE REQUEST----- diff --git a/examples/SSLDemo/certs/client.key b/examples/SSLDemo/certs/client.key new file mode 100644 index 0000000..ff280b6 --- /dev/null +++ b/examples/SSLDemo/certs/client.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAqOp2R0JnTBeKjQmHDjIKHlT5RLfk/RTksrw88xdrQgOLbceB +rjZg82yfTJkFW4rTVjjSphNbPCynFwg+BxK9MXfJr9Rs9dsBSpmCViXiw6pmDSZz +on691cL4PYEEeom8y5egp/OU6IQRcNwpyffiVDPYSR8qH3PzTi7RXLGNGtdLFi0I +YeZ+FYlGjTlBQRyqNvOD3nEvIocNtyWP9+D17wtPENA2AbWbHV2CbKFoc6Zx98Fw +KtVkz94Z4duzjLUZOwjcTWK+zKxfRzVDZtxlMTOA261N8CUha8nl+c4uNgTC0h0J +PE5JTewwXdGftNiR2xWgVLvWfbFg73x0RemoyQIDAQABAoIBACJPfbb7xf+uyHXd +eZFomKWQnRFYSSsfE1U65yZ5m0/NaITkAXNhmE/ZwIHOk0gE6uiYojEZvW57o3UK +N484PzXNHyqX+4n08k404ESfbXBRLGl/Zf2bwPOqpsHXcxFw6Ohx5DA5SgXwzZof +Hl3n/BEedtBjhCrfYox+9gfeCMtqm1s/TkiTe5l8slzzx0V7nLugz2xzaqnI8zpO ++JZpMlnQUh2XJ6ORHyHCI7sEqu/k2AswB+PduDUk/F2HdVzHBMcE8ZC4DrBaO7mS +SKwNwtw+SlakTnMvMhcHG29qMyLQKtHzc6SLlDCRtOjRDVgxecEDAkqyfve9FN93 +F6siQAECgYEA0FNIZSr/nTStT3B1K3XHSKiKJN8cZktUFfC15Yo7cYuT7aqnYh6g +dlm3Po0T66viL/yTA+vhbTTOTn5m0Gx3Yq6lPC4UVBp4s39UCzxQfXOJyTB/1ht2 +6SDEnom83EW6S/FklOnG5NZSDODw8B4XopMFnx6+69p32kldcJ/Ysw0CgYEAz5Jh +YJnx4AN4C4rNPBPkuRv/T/kfar2XVUA9dMlN9srMsIQiksH9tQQ9i1ABrjsnzCJp +IgRiMlHiiODr6JU71kdHddwLWetC0sjXVIF/7RZBl0QgcnS5z47YADxEWRKwWyUP +uz7Z/mMuV0kSGxp3+WMzoi2Wk6vqg6Nt9DilDa0CgYEAvgwsEDcAx96FeOID0ij5 +K1yt4eM0GlIAHJ/ioMvRXM1Tn06+snF0O2OvGr5C/Q1qJBLL35jxptm0l8ESdHNv +GjRvAw6advtLP50aA8H7P+cGPOckyCN4AEdnd6X6CA0IXj2SX5NBYgPvCFaxFqyt +LR/o0fePfsRn8FhbiOIaI4UCgYBOfM4/ZdaU2xrwWlrChc8tw41l4xBjHy9y9+iF +GX1WfVaqxDwCfEH/yYuv+t+3zvx8buKMD1ZGKrpbAZmSh6Npoeg+g6bzKEdLRtBN +Tu5datYAaa1POh3sgtngNOmvOKbgwAHTzq9FRqGGNcYX44lMDpu+jjhqvE3f2tM/ +zo9yvQKBgAfobnvYbaehkUB0bWlw9oURMfI6fI8T9EGhM0PvWsn0KaPqzsm9pBwS +eQKD88t+DxGQCFszdGE51N3av3matPABiiz0xSDbC0ywSkbcgiF3F3V6Ss9pYnVQ +NzLekf3JFRbpknvTeHbyaSqodeU8NC9lgVTGr46xkvUmNW4ixmqA +-----END RSA PRIVATE KEY----- diff --git a/examples/SSLDemo/certs/create.sh b/examples/SSLDemo/certs/create.sh new file mode 100644 index 0000000..b1b2375 --- /dev/null +++ b/examples/SSLDemo/certs/create.sh @@ -0,0 +1,28 @@ + +#create ca key +openssl genrsa -out ca.key 2048 + +#create ca crt +openssl req -x509 -new -nodes -key ca.key -subj "/CN=*.demo.com" -days 5000 -out ca.crt + +######################################################################################### +#create server key +openssl genrsa -out server.key 2048 + +#create server csr +openssl req -new -key server.key -subj "/CN=*.demo.com" -out server.csr + +#ca sign server, create server crt +openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 5000 + +######################################################################################### +#create client key +openssl genrsa -out client.key 2048 + +#create clilent csr +openssl req -new -key client.key -subj "/CN=*.demo.com" -out client.csr + +#ca sign client, create client crt +openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 5000 + +######################################################################################### \ No newline at end of file diff --git a/examples/SSLDemo/certs/server.crt b/examples/SSLDemo/certs/server.crt new file mode 100644 index 0000000..be34e7e --- /dev/null +++ b/examples/SSLDemo/certs/server.crt @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICsTCCAZkCFFwVYVZ4Uu9R0mhodJQCkUUSelbCMA0GCSqGSIb3DQEBCwUAMBUx +EzARBgNVBAMMCiouZGVtby5jb20wHhcNMjAwMjEzMTIzMDQ3WhcNMzMxMDIyMTIz +MDQ3WjAVMRMwEQYDVQQDDAoqLmRlbW8uY29tMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEA74MHigfRUfFvvS0ZSMCRiuxtkBZtAk+EeTMTcjamwgV8fMWz +JbtTqxn4325CqvXIcSs2H+c09C7pBufWzkwFFcEpSMokGEyjeKxXMmxhUC+q28yq +WiYim8l7btJZhMa3tpSQaWu+Ul0SctSt0OpM2onxq9s8KN7B0zM9tCmyLZ++IXxx +3yGjRRk1VtVyVePNILdf7EZBZXHu2daxf2GusYfQmV+KAG/r+YbX+7GXh2wZ/lGV +Ur4B6Pzoi/zUGoA7i7Zs/Y2S/yXsRD8UG6jid0slO4uBuiHa9RIjxNoe1NAqirBj +wBVNAbzfKOC7f/qiu5JhIg0qHbb50tXUvLZzbwIDAQABMA0GCSqGSIb3DQEBCwUA +A4IBAQCtk9bOoKdoF3UpDLijhBrmL7a13xT+Q5U3SiZiYw2pdz2FtGzZooQejmm6 +tDCmAisIZMiYS+X6Y2OoWe9dzEE1Rnx0227XPjhQvHAKsBfwL03N1Hw1LSzU7czf +/0pYWSyCVfL6f8DOeH2rnhBPHAE/FzDtnCaIDUtGC3I4ZuYrPBqDmmYTentWsPK3 +2++ay1Hcu/k9vSWTVQZG2bA1XEAlvy5lNaGRop+HI5V3fZiQiZe0+HM65dt68N4W +T72XY35kP3XXyYZLZjhMZPMZHrOeApSmfvFJimAyp2Ax1xtlmyBxyxh7vH33vxna +TXcK3o3hbraYKFihReIdzouG/4rN +-----END CERTIFICATE----- diff --git a/examples/SSLDemo/certs/server.csr b/examples/SSLDemo/certs/server.csr new file mode 100644 index 0000000..b9df041 --- /dev/null +++ b/examples/SSLDemo/certs/server.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICWjCCAUICAQAwFTETMBEGA1UEAwwKKi5kZW1vLmNvbTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAO+DB4oH0VHxb70tGUjAkYrsbZAWbQJPhHkzE3I2 +psIFfHzFsyW7U6sZ+N9uQqr1yHErNh/nNPQu6Qbn1s5MBRXBKUjKJBhMo3isVzJs +YVAvqtvMqlomIpvJe27SWYTGt7aUkGlrvlJdEnLUrdDqTNqJ8avbPCjewdMzPbQp +si2fviF8cd8ho0UZNVbVclXjzSC3X+xGQWVx7tnWsX9hrrGH0JlfigBv6/mG1/ux +l4dsGf5RlVK+Aej86Iv81BqAO4u2bP2Nkv8l7EQ/FBuo4ndLJTuLgboh2vUSI8Ta +HtTQKoqwY8AVTQG83yjgu3/6oruSYSINKh22+dLV1Ly2c28CAwEAAaAAMA0GCSqG +SIb3DQEBCwUAA4IBAQCVy2KgCiuQWWgy735Ym9hHoDaUtLgU1MG62s+ECgYlzz6j +ft88gCqZxVIMFUNqowekh9wan9XlGKYBwdPXpkIRB1Zg4mFoPamD6AMZEfUT1ooK +XJ0K6LE7Q4XY+HR/tHDsAf71QyKFblcIuRcIMFbOcp8paQENjYJpqiXfvQbmV7lS +StkIX3A2BBvogCc4qPZ90QHyOaALuVuquCkh1ULJhNLq+6sVW+bhUs9fGTOuhnJU +zYohoIJznxr5xglsLA5VnjZkmbtdewoHrvY+tNaAVEXFMEF9oBr8jtVuUiQGk7mF +o+dC43546tSaiqNxZ13rHsMDucC9fAS/O8AdeGr7 +-----END CERTIFICATE REQUEST----- diff --git a/examples/SSLDemo/certs/server.key b/examples/SSLDemo/certs/server.key new file mode 100644 index 0000000..622c9b9 --- /dev/null +++ b/examples/SSLDemo/certs/server.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEA74MHigfRUfFvvS0ZSMCRiuxtkBZtAk+EeTMTcjamwgV8fMWz +JbtTqxn4325CqvXIcSs2H+c09C7pBufWzkwFFcEpSMokGEyjeKxXMmxhUC+q28yq +WiYim8l7btJZhMa3tpSQaWu+Ul0SctSt0OpM2onxq9s8KN7B0zM9tCmyLZ++IXxx +3yGjRRk1VtVyVePNILdf7EZBZXHu2daxf2GusYfQmV+KAG/r+YbX+7GXh2wZ/lGV +Ur4B6Pzoi/zUGoA7i7Zs/Y2S/yXsRD8UG6jid0slO4uBuiHa9RIjxNoe1NAqirBj +wBVNAbzfKOC7f/qiu5JhIg0qHbb50tXUvLZzbwIDAQABAoIBADt/OSg4uO66Ix/D +TDyeWYlBIhZg+8NPLYFOBs6gdNxNsJbuJYqB9k7SrNgT88u0Mo6qRU+3h5gA7zIf +9WRZzgmRakgCruS6ZQFdDmwgMCxTKwZe2RJ71q0MZ/Unm8U39/sK/LSzZxvesu6D +looHKgA/tCEU3OTqMQvd9r4CfZiHUxHMdVbaV4skgLxUVSrkwPEv1OyreRsr6iVF +o+NJIN+WdPz236vrooYI91H17j8Tl5acHluu7Dr/q696FUYmrnfyO6dVMjai99fW +1124BGBH7kefJIDuxaur8J2txR4OBEVVhSx2Ghpe2JfNjZvpmia2m9Wo4t3JUSL0 +mxRl54ECgYEA+5kMNi9zDPKuGmUPLFsQAfk4eqcF69paBnEMOTd2nvWz03p/ugTW +o2bFs9s4McYJvnvWLSDlKP6NVIuSLaEBYuIHvjwR245NDxu9p+u9PTHZxbApkxNj +C3H/aIm/k0wtzHf943ShvLspjFqw7+q/nCf0T0oMrJaWkZWVI4vn1GcCgYEA87PY +qNPKiii3JwIMcgV9b3rDG6ulIj0lKKx5T8Jd+dVgLqGk3aah/PEsnVnBeg5YEB8r +MfqJ2OKzZ3t7jvJTX4pY9Q1zxFZ5R+rCWN5JdVZbofkekK29EkXIscVBf6YFlgAt +PbdVxZtZSKMRJB8+c+P9ovK5B0xQGg0bfJdRQ7kCgYEA8coFiFVVVc4rL0aLrG7f +FWZytryo3h57gdFGk/4PS3iJFuWUtipMM8BioxQ8DulpF9xe2gPQ9vKa0/NFyf// +Gw5prpJ//uXkfG6Gd0gAFz0/MdK4QZXSC3/Emqw2pdIB+YwfPGYrwPqFVVMa05Zg +CiwDh+d8Aqi9jq+YIg8j/mUCgYEAqzxGUzIlkXhUYOtWlVN4NLmcmDe+G1W9Y1v1 +DW70G1SrdXiM4FVyYsmPYKytfrbPd9x+vGpfK273QhII2oM4w9vw75bZLi7Ynwi8 +MDdYhEL+tcvWhzActtcj0o1YnXmpWSGcqE3Gzcd/L8OsiqYNet7K3BESo6cibXui +QaQNLLkCgYEA+tUOLkaJZlOuiEE5H5RDmFyC46G6R3Ukd5CQ/Dp4U75NLTIlEuGw +lIV/vcA0vy6WPL6rX2Gdm30oYq+xb+m9bDDCaXnkOxdPr5+1Zg4n3ibcFbBz/wmF +MjcYzC/D6dGK4r6h3tZeX7byNDVM26+qMJlgYd31FhoiFjlPLGuqFrs= +-----END RSA PRIVATE KEY----- diff --git a/examples/scripts/run-auth.bat b/examples/scripts/run-auth.bat new file mode 100644 index 0000000..7540eee --- /dev/null +++ b/examples/scripts/run-auth.bat @@ -0,0 +1,22 @@ + +echo "run-auth.bat" + +killall -9 AuthServer.exe +sleep 1 + +echo "start server: .\\bin\\Release\\AuthServer.exe --config=..\\examples\\AuthDemo\\Server\\config.conf &" + +.\\bin\\Release\\AuthServer.exe --config=..\\examples\\AuthDemo\\Server\\config.conf & + +sleep 3 + +echo "client: .\\bin\\Release\\SSLClient.exe" + +.\\bin\\Release\\SSLClient.exe --count=10000 --thread=2 --call=sync --buffersize=1000 --netthread=1 +.\\bin\\Release\\SSLClient.exe --count=10000 --thread=2 --call=async --buffersize=1000 --netthread=1 + +sleep 1 + +killall -9 AuthServer.exe + + diff --git a/examples/scripts/run-auth.sh b/examples/scripts/run-auth.sh new file mode 100644 index 0000000..d85affd --- /dev/null +++ b/examples/scripts/run-auth.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +echo "run-auth.sh" + +killall -2 AuthServer + +sleep 1 +echo "start server: ./bin/AuthServer --config=../examples/AuthDemo/Server/config.conf &" + +./bin/AuthServer --config=../examples/AuthDemo/Server/config.conf & + +sleep 1 + +echo "client: ./bin/AuthClient" + +./bin/AuthClient --config=../examples/AuthDemo/Client/config.conf --count=10000 --thread=2 --call=sync --buffersize=1000 --netthread=1 +./bin/AuthClient --config=../examples/AuthDemo/Client/config.conf --count=10000 --thread=2 --call=async --buffersize=1000 --netthread=1 + +sleep 1 + +killall -2 AuthServer + + diff --git a/examples/scripts/run-http2.sh b/examples/scripts/run-http2.sh new file mode 100644 index 0000000..b348b2c --- /dev/null +++ b/examples/scripts/run-http2.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +echo "run-http2.sh" + +killall -2 Http2Server + +sleep 1 +echo "start server: ./bin/Http2Server --config=../examples/HttpDemo/Http2Server/config.conf &" + +./bin/Http2Server --config=../examples/HttpDemo/Http2Server/config.conf & + +sleep 1 + +echo "client: ./bin/Http2Client" + +./bin/Http2Client --count=10000 --thread=2 --call=asynchttp +./bin/Http2Client --count=10000 --thread=2 --call=synchttp + +sleep 1 + +killall -2 Http2Server + + diff --git a/examples/scripts/run-kill.bat b/examples/scripts/run-kill.bat new file mode 100644 index 0000000..49762b3 --- /dev/null +++ b/examples/scripts/run-kill.bat @@ -0,0 +1,17 @@ +#!/bin/bash + +echo "run-kill.bat" + +taskkill /im SSLServer.exe /f +taskkill /im AuthServer.exe /f +taskkill /im CoroutineDemoAServer.exe /f +taskkill /im CoroutineDemoBServer.exe /f +taskkill /im CustomServer.exe /f +taskkill /im HttpServer.exe /f +taskkill /im Http2Server.exe /f +taskkill /im PushServer.exe /f +taskkill /im QuickStartDemo.exe /f +taskkill /im ProxyServer.exe /f +taskkill /im busybox.exe /f + + diff --git a/examples/scripts/run-kill.sh b/examples/scripts/run-kill.sh new file mode 100644 index 0000000..44ac185 --- /dev/null +++ b/examples/scripts/run-kill.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +echo "run-kill.sh" + +killall -9 SSLServer +killall -9 AuthServer +killall -9 CoroutineDemoAServer +killall -9 CoroutineDemoBServer +killall -9 CustomServer +killall -9 HttpServer +killall -9 Http2Server +killall -9 PushServer +killall -9 QuickStartDemo +killall -9 ProxyServer + diff --git a/examples/scripts/run-ssl.bat b/examples/scripts/run-ssl.bat new file mode 100644 index 0000000..b5a2306 --- /dev/null +++ b/examples/scripts/run-ssl.bat @@ -0,0 +1,22 @@ + +echo "run-ssl.bat" + +killall -9 SSLServer.exe +sleep 1 + +echo "start server: .\\bin\\Release\\SSLServer.exe --config=..\\examples\\SSLDemo\\Server\\config.conf &" + +.\\bin\\Release\\SSLServer.exe --config=..\\examples\\SSLDemo\\Server\\config.conf & + +sleep 3 + +echo "client: .\\bin\\Release\\SSLClient.exe" + +.\\bin\\Release\\SSLClient.exe --count=10000 --thread=2 --call=sync --buffersize=1000 --netthread=1 +.\\bin\\Release\\SSLClient.exe --count=10000 --thread=2 --call=async --buffersize=1000 --netthread=1 + +sleep 1 + +killall -9 SSLServer.exe + + diff --git a/examples/scripts/run-ssl.sh b/examples/scripts/run-ssl.sh new file mode 100644 index 0000000..6ae529f --- /dev/null +++ b/examples/scripts/run-ssl.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +echo "run-ssl.sh" + +killall -2 SSLServer + +sleep 1 +echo "start server: ./bin/SSLServer --config=../examples/SSLDemo/Server/config.conf &" + +./bin/SSLServer --config=../examples/SSLDemo/Server/config.conf & + +sleep 1 + +echo "client: ./bin/SSLClient" + +./bin/SSLClient --config=../examples/SSLDemo/Client/config.conf --count=10000 --thread=2 --call=sync --buffersize=1000 --netthread=1 +./bin/SSLClient --config=../examples/SSLDemo/Client/config.conf --count=10000 --thread=2 --call=async --buffersize=1000 --netthread=1 + +sleep 1 + +killall -2 SSLServer + + diff --git a/servant/libservant/AdapterProxy.cpp b/servant/libservant/AdapterProxy.cpp index 07d781d..c1dd16d 100755 --- a/servant/libservant/AdapterProxy.cpp +++ b/servant/libservant/AdapterProxy.cpp @@ -238,14 +238,13 @@ void AdapterProxy::doInvoke() int iRet = _trans->sendRequest(msg->sReqData); - TLOGTARS("[TARS][AdapterProxy::doInvoke sendRequest objname:" << _objectProxy->name() << ",desc:" << _endpoint.desc() << ",id:" << msg->request.iRequestId << ",ret:" << iRet << endl); - //发送失败 返回 if(iRet == Transceiver::eRetError) { - TLOGTARS("[TARS][AdapterProxy::doInvoke fail,errono:" << iRet << endl); + TLOGTARS("[TARS][AdapterProxy::doInvoke sendRequest failed, obj:" << _objectProxy->name() << ",desc:" << _endpoint.desc() << ",id:" << msg->request.iRequestId << ", ret:" << iRet << endl); return; } + TLOGTARS("[TARS][AdapterProxy::doInvoke sendRequest obj:" << _objectProxy->name() << ",desc:" << _endpoint.desc() << ",id:" << msg->request.iRequestId << ",ret:" << iRet << endl); //请求发送成功了 处理采样 //... diff --git a/servant/libservant/Application.cpp b/servant/libservant/Application.cpp index 3cadbc6..b7964be 100644 --- a/servant/libservant/Application.cpp +++ b/servant/libservant/Application.cpp @@ -85,10 +85,18 @@ size_t ServerConfig::CoroutineMemSize; //协程占用内存空间的最大 uint32_t ServerConfig::CoroutineStackSize; //每个协程的栈大小(默认128k) bool ServerConfig::ManualListen = false; //手工启动监听端口 bool ServerConfig::MergeNetImp = false; //合并网络和处理线程 -bool ServerConfig::OpenSSL = false; +int ServerConfig::NetThread = 1; //servernet thread +bool ServerConfig::CloseCout = true; -#define OUT_LINE (TC_Common::outfill("", '-', 50)) -#define OUT_LINE_LONG (TC_Common::outfill("", '=', 50)) +#if TARS_SSL +std::string ServerConfig::CA; +std::string ServerConfig::Cert; +std::string ServerConfig::Key; +bool ServerConfig::VerifyClient = false; +#endif + +#define OUT_LINE (TC_Common::outfill("", '-', 80)) +#define OUT_LINE_LONG (TC_Common::outfill("", '=', 80)) /////////////////////////////////////////////////////////////////////////////////////////// TC_Config Application::_conf; @@ -611,9 +619,6 @@ void Application::main(const TC_Option &option) { try { -#if TARS_SSL - TC_SSLManager::GlobalInit(); -#endif #if TARGET_PLATFORM_LINUX || TARGET_PLATFORM_IOS TC_Common::ignorePipe(); #endif @@ -759,13 +764,8 @@ void Application::main(const TC_Option &option) TarsRollLogger::getInstance()->sync(false); } -// void Application::parseConfig(int argc, char *argv[]) void Application::parseConfig(const TC_Option &op) { - // TC_Option op; - - // op.decode(argc, argv); - //直接输出编译的TARS版本 if(op.hasParam("version")) { @@ -824,34 +824,12 @@ void Application::initializeClient() //输出 outClient(cout); -#if TARS_SSL - if(_conf.hasDomainVector("/tars/application/clientssl")) - { - string path = _conf.get("/tars/application/clientssl/", "./"); - if (path.empty() || path[path.length() - 1] != '/') - path += "/"; - - string ca = path + _conf.get("/tars/application/clientssl/"); - string cert = path + _conf.get("/tars/application/clientssl/"); - if (cert == path) cert.clear(); - string key = path + _conf.get("/tars/application/clientssl/"); - if (key == path) key.clear(); - - if (!TC_SSLManager::getInstance()->addCtx("client", ca, cert, key, false)) { - cout << "failed add client cert " << ca << endl; - exit(-1); - } - else - { - cout << TC_Common::outfill("CA") << ca << endl; - cout << "succ add client cert " << ca << endl; - } - } -#endif } void Application::outClient(ostream &os) { + cout << OUT_LINE << "\n" << TC_Common::outfill("[load client]:") << endl; + os << TC_Common::outfill("locator") << _communicator->getProperty("locator") << endl; os << TC_Common::outfill("sync-invoke-timeout") << _communicator->getProperty("sync-invoke-timeout") << endl; os << TC_Common::outfill("async-invoke-timeout") << _communicator->getProperty("async-invoke-timeout") << endl; @@ -859,10 +837,9 @@ void Application::outClient(ostream &os) os << TC_Common::outfill("stat") << _communicator->getProperty("stat") << endl; os << TC_Common::outfill("property") << _communicator->getProperty("property") << endl; os << TC_Common::outfill("report-interval") << _communicator->getProperty("report-interval") << endl; - os << TC_Common::outfill("sample-rate") << _communicator->getProperty("sample-rate") << endl; +// os << TC_Common::outfill("sample-rate") << _communicator->getProperty("sample-rate") << endl; os << TC_Common::outfill("max-sample-count") << _communicator->getProperty("max-sample-count") << endl; os << TC_Common::outfill("netthread") << _communicator->getProperty("netthread") << endl; - // os << outfill("recvthread") << _communicator->getProperty("recvthread") << endl; os << TC_Common::outfill("asyncthread") << _communicator->getProperty("asyncthread") << endl; os << TC_Common::outfill("modulename") << _communicator->getProperty("modulename") << endl; os << TC_Common::outfill("enableset") << _communicator->getProperty("enableset") << endl; @@ -896,18 +873,6 @@ void Application::addServantProtocol(const string& servant, const TC_NetWorkBuff getEpollServer()->getBindAdapter(adapterName)->setProtocol(protocol); } -// void Application::addServantConnProtocol(const string& servant, const TC_NetWorkBuffer::protocol_functor& protocol) -// { -// string adapterName = ServantHelperManager::getInstance()->getServantAdapter(servant); - -// if (adapterName.empty()) -// { -// throw runtime_error("[TARS]addServantConnProtocol fail, no found adapter for servant:" + servant); -// } - -// getEpollServer()->getBindAdapter(adapterName)->setConnProtocol(protocol); -// } - void Application::addServantOnClose(const string& servant, const TC_EpollServer::close_functor& cf) { string adapterName = ServantHelperManager::getInstance()->getServantAdapter(servant); @@ -967,9 +932,6 @@ void Application::initializeServer() ServerConfig::TarsPath = TC_File::simplifyDirectory(ServerConfig::LogPath + FILE_SEP + ".." + FILE_SEP) + FILE_SEP; ServerConfig::ServerName = toDefault(_conf.get("/tars/application/server"), exe); - // ServerConfig::BasePath = toDefault(_conf.get("/tars/application/server"), ".") + "/"; - // ServerConfig::DataPath = toDefault(_conf.get("/tars/application/server"), ".") + "/"; - // ServerConfig::LogPath = toDefault(_conf.get("/tars/application/server"), ".") + "/"; ServerConfig::LogSize = TC_Common::toSize(toDefault(_conf.get("/tars/application/server"), "52428800"), 52428800); ServerConfig::LogNum = TC_Common::strto(toDefault(_conf.get("/tars/application/server"), "10")); ServerConfig::LocalIp = _conf.get("/tars/application/server"); @@ -985,6 +947,23 @@ void Application::initializeServer() ServerConfig::CoroutineStackSize = TC_Common::toSize(toDefault(_conf.get("/tars/application/server"), "131072"), 131072); ServerConfig::ManualListen = _conf.get("/tars/application/server", "0") == "0" ? false : true; ServerConfig::MergeNetImp = _conf.get("/tars/application/server", "0") == "0" ? false : true; + ServerConfig::NetThread = TC_Common::strto(toDefault(_conf.get("/tars/application/server"), "1")); + ServerConfig::CloseCout = _conf.get("/tars/application/server","1")=="0"?0:1; + +#if TARS_SSL + ServerConfig::CA = _conf.get("/tars/application/server"); + ServerConfig::Cert = _conf.get("/tars/application/server"); + ServerConfig::Key = _conf.get("/tars/application/server"); + ServerConfig::VerifyClient = _conf.get("/tars/application/server","0")=="0"?false:true; + + bool flag = TC_SSLManager::getInstance()->addCtx("server", ServerConfig::CA, ServerConfig::Cert, ServerConfig::Key, ServerConfig::VerifyClient); + + if(!flag) + { + TLOGERROR("[TARS]load server ssl error, ca:" << ServerConfig::CA << endl); + exit(-1); + } +#endif if(ServerConfig::LocalIp.empty()) { @@ -1025,15 +1004,6 @@ void Application::initializeServer() _epollServer = new TC_EpollServer(iNetThreadNum); - // //网络线程的内存池配置 - // { - // size_t minBlockSize = TC_Common::strto(toDefault(_conf.get("/tars/application/server"), "1024")); // 1KB - // size_t maxBlockSize = TC_Common::strto(toDefault(_conf.get("/tars/application/server"), "8388608")); // 8MB - // size_t maxBytes = TC_Common::strto(toDefault(_conf.get("/tars/application/server"), "67108864")); // 64MB - // _epollServer->setNetThreadBufferPoolInfo(minBlockSize, maxBlockSize, maxBytes); - // } - - //初始化服务是否对空链接进行超时检查 bool bEnable = (_conf.get("/tars/application/server","0")=="1")?true:false; @@ -1064,9 +1034,9 @@ void Application::initializeServer() level = _conf.get("/tars/application/server","DEBUG"); } - TarsRollLogger::getInstance()->logger()->setLogLevel(TC_Common::upper(level)); + ServerConfig::LogLevel = TC_Common::upper(level); - ServerConfig::LogLevel = TC_Common::upper(level); + TarsRollLogger::getInstance()->logger()->setLogLevel(ServerConfig::LogLevel); /////////////////////////////////////////////////////////////////////////////////////////////////// //初始化到LogServer代理 @@ -1130,74 +1100,41 @@ void Application::initializeServer() sRspQueue += ".sendrspqueue"; g_pReportRspQueue = _communicator->getStatReport()->createPropertyReport(sRspQueue, PropertyReport::avg()); - - // PropertyReportPtr p; - // p = _communicator->getStatReport()->createPropertyReport(sRspQueue, PropertyReport::avg()); - - // _epollServer->_pReportRspQueue = p.get(); } -#if TARS_SSL - if(_conf.hasDomainVector("/tars/application/serverssl")) - { - string path = _conf.get("/tars/application/serverssl/", "./"); - if (path.empty() || path[path.length() - 1] != '/') - path += "/"; - - string ca = path + _conf.get("/tars/application/serverssl/"); - if (ca == path) ca.clear(); - string cert = path + _conf.get("/tars/application/serverssl/"); - string key = path + _conf.get("/tars/application/serverssl/"); - bool verifyClient = (_conf.get("/tars/application/serverssl/", "0") == "0") ? false : true; - - if (!TC_SSLManager::getInstance()->addCtx("server", ca, cert, key, verifyClient)) { - cout << "failed parse cert " << cert << endl; - exit(-1); - } - else { - cout << TC_Common::outfill("CA") << ca << endl; - cout << TC_Common::outfill("CERT") << cert << endl; - cout << TC_Common::outfill("KEY") << key << endl; - cout << TC_Common::outfill("verifyClient") << verifyClient << endl; - - cout << "succ add server cert " << ca << ", verifyClient " << verifyClient << endl; - } - } -#endif } void Application::outServer(ostream &os) { - os << TC_Common::outfill("Application") << ServerConfig::Application << endl; - os << TC_Common::outfill("ServerName") << ServerConfig::ServerName << endl; - os << TC_Common::outfill("BasePath") << ServerConfig::BasePath << endl; - os << TC_Common::outfill("DataPath") << ServerConfig::DataPath << endl; - os << TC_Common::outfill("LocalIp") << ServerConfig::LocalIp << endl; - os << TC_Common::outfill("Local") << ServerConfig::Local << endl; - os << TC_Common::outfill("LogPath") << ServerConfig::LogPath << endl; - os << TC_Common::outfill("LogSize") << ServerConfig::LogSize << endl; - os << TC_Common::outfill("LogNum") << ServerConfig::LogNum << endl; - os << TC_Common::outfill("Log") << ServerConfig::Log << endl; - os << TC_Common::outfill("Node") << ServerConfig::Node << endl; - os << TC_Common::outfill("Config") << ServerConfig::Config << endl; - os << TC_Common::outfill("Notify") << ServerConfig::Notify << endl; - os << TC_Common::outfill("OpenCoroutine") << ServerConfig::OpenCoroutine << endl; - os << TC_Common::outfill("CoroutineMemSize") << ServerConfig::CoroutineMemSize << endl; - os << TC_Common::outfill("CoroutineStackSize") << ServerConfig::CoroutineStackSize << endl; - os << TC_Common::outfill("CloseCout") << TC_Common::tostr(_conf.get("/tars/application/server",AppCache::getInstance()->get("closeCout")) == "0"?0:1)<< endl; - os << TC_Common::outfill("netthread") << TC_Common::tostr(_conf.get("/tars/application/server","1")) << endl; - // os << TC_Common::outfill("BackPacketBffLimit") << TC_Common::strto(toDefault(_conf.get("/tars/application/server", "0"), "0")) << endl; - os << TC_Common::outfill("manuallisten") << ServerConfig::ManualListen << endl; - os << TC_Common::outfill("mergenetimp") << ServerConfig::MergeNetImp << endl; + os << TC_Common::outfill("Application(app)") << ServerConfig::Application << endl; + os << TC_Common::outfill("ServerName(server)") << ServerConfig::ServerName << endl; + os << TC_Common::outfill("BasePath(basepath)") << ServerConfig::BasePath << endl; + os << TC_Common::outfill("DataPath(datapath)") << ServerConfig::DataPath << endl; + os << TC_Common::outfill("LocalIp(localip)") << ServerConfig::LocalIp << endl; + os << TC_Common::outfill("Local(local)") << ServerConfig::Local << endl; + os << TC_Common::outfill("LogPath(logpath)") << ServerConfig::LogPath << endl; + os << TC_Common::outfill("LogSize(logsize)") << ServerConfig::LogSize << endl; + os << TC_Common::outfill("LogNum(lognum)") << ServerConfig::LogNum << endl; + os << TC_Common::outfill("LogLevel(loglevel)") << ServerConfig::LogLevel << endl; + os << TC_Common::outfill("Log(log)") << ServerConfig::Log << endl; + os << TC_Common::outfill("Node(node)") << ServerConfig::Node << endl; + os << TC_Common::outfill("Config(config)") << ServerConfig::Config << endl; + os << TC_Common::outfill("Notify(notify)") << ServerConfig::Notify << endl; + os << TC_Common::outfill("OpenCoroutine(opencoroutine)") << ServerConfig::OpenCoroutine << endl; + os << TC_Common::outfill("CoroutineMemSize(coroutinememsize)") << ServerConfig::CoroutineMemSize << endl; + os << TC_Common::outfill("CoroutineStackSize(coroutinestack)") << ServerConfig::CoroutineStackSize << endl; + os << TC_Common::outfill("CloseCout(closecout)") << ServerConfig::CloseCout << endl; + os << TC_Common::outfill("NetThread(netthread)") << ServerConfig::NetThread << endl; + os << TC_Common::outfill("ManualListen(manuallisten)") << ServerConfig::ManualListen << endl; + os << TC_Common::outfill("MergeNetImp(mergenetimp)") << ServerConfig::MergeNetImp << endl; + os << TC_Common::outfill("ReportFlow") << ServerConfig::ReportFlow<< endl; +#if TARS_SSL + cout << TC_Common::outfill("Ca") << ServerConfig::CA << endl; + cout << TC_Common::outfill("Cert") << ServerConfig::Cert << endl; + cout << TC_Common::outfill("Key") << ServerConfig::Key << endl; + cout << TC_Common::outfill("VerifyClient") << ServerConfig::VerifyClient << endl; +#endif - string level = AppCache::getInstance()->get("logLevel"); - if(level.empty()) - { - level = _conf.get("/tars/application/server","DEBUG"); - } - os << TC_Common::outfill("logLevel") << level<< endl; - - os << TC_Common::outfill("ReportFlow") << ServerConfig::ReportFlow<< endl; } void Application::bindAdapter(vector& adapters) @@ -1264,9 +1201,7 @@ void Application::bindAdapter(vector& adapters) bindAdapter->setProtocol(AppProtocol::parse); } - // bindAdapter->setHandleGroupName(_conf.get(sLastPath + "", adapterName[i])); bindAdapter->setHandle(TC_Common::strto(_conf.get(sLastPath + "", "0"))); - // bindAdapter->setHandleNum(TC_Common::strto(_conf.get(sLastPath + "", "0"))); // bindAdapter->setBackPacketBuffLimit(iBackPacketBuffLimit); if(ServerConfig::ManualListen) { @@ -1308,7 +1243,6 @@ void Application::checkServantNameValid(const string& servant, const string& sPr cout << os.str() << endl; exit(-1); - // terminate(); } } diff --git a/servant/libservant/Communicator.cpp b/servant/libservant/Communicator.cpp index ec87e2c..1f10c10 100644 --- a/servant/libservant/Communicator.cpp +++ b/servant/libservant/Communicator.cpp @@ -15,6 +15,10 @@ */ #include "util/tc_file.h" +#if TARS_SSL +#include "util/tc_sslmgr.h" +#endif + #include "servant/Communicator.h" #include "servant/StatReport.h" #include "servant/TarsLogger.h" @@ -80,8 +84,7 @@ void Communicator::setProperty(TC_Config& conf, const string& domain/* = CONFIG_ conf.getDomainMap(domain, _properties); string defaultValue = "dft"; - if ((defaultValue == getProperty("enableset", defaultValue)) - || (defaultValue == getProperty("setdivision", defaultValue))) + if ((defaultValue == getProperty("enableset", defaultValue)) || (defaultValue == getProperty("setdivision", defaultValue))) { _properties["enableset"] = conf.get("/tars/application", "n"); _properties["setdivision"] = conf.get("/tars/application", "NULL"); @@ -159,6 +162,7 @@ void Communicator::initClientConfig() assert(_traceManager != NULL); } #endif + } void Communicator::setProperty(const map& properties) @@ -258,6 +262,24 @@ void Communicator::initialize() _initialized = true; + +#if TARS_SSL + + string ca = getProperty("ca"); + string cert = getProperty("cert"); + string key = getProperty("key"); + + if(!ca.empty()) { + bool flag = TC_SSLManager::getInstance()->addCtx("client", ca, cert, key, false); + + if(!flag) + { + TLOGERROR("[TARS]load client ssl error, ca:" << ca << endl); + exit(-1); + } + } +#endif + _servantProxyFactory = new ServantProxyFactory(this); _clientThreadNum = TC_Common::strto(getProperty("netthread","1")); @@ -383,12 +405,6 @@ void Communicator::pushAsyncThreadQueue(ReqMessage * msg) { //先不考虑每个线程队列数目不一致的情况 _asyncThread[(++_asyncSeq)%_asyncThreadNum]->push_back(msg); - // _asyncSeq ++; - - // if(_asyncSeq == _asyncThreadNum) - // { - // _asyncSeq = 0; - // } } void Communicator::terminate() diff --git a/servant/libservant/Transceiver.cpp b/servant/libservant/Transceiver.cpp index 290be13..3d4a3f8 100755 --- a/servant/libservant/Transceiver.cpp +++ b/servant/libservant/Transceiver.cpp @@ -24,6 +24,7 @@ #if TARS_SSL #include "util/tc_openssl.h" +#include "util/tc_sslmgr.h" #endif #if TARS_HTTP2 @@ -151,8 +152,6 @@ void Transceiver::connect() <<" ]"<< endl); } } - - // _adapterProxy->getObjProxy()->getCommunicatorEpoll()->addFd(fd, &_fdInfo, EPOLLIN|EPOLLOUT); } void Transceiver::setConnected() @@ -161,10 +160,9 @@ void Transceiver::setConnected() _adapterProxy->setConTimeout(false); _adapterProxy->addConnExc(false); - onConnect(); - - TLOGTARS("[TARS][tcp setConnected, " << _adapterProxy->getObjProxy()->name() << ",fd:" << _fd << "]" << endl); + + onConnect(); } void Transceiver::onConnect() @@ -173,18 +171,17 @@ void Transceiver::onConnect() if (isSSL()) { // 分配ssl对象 - SSL* ssl = TC_SSLManager::getInstance()->newSSL("client"); - if (!ssl) + _openssl = TC_SSLManager::getInstance()->newSSL("client"); + if (!_openssl) { ObjectProxy* obj = _adapterProxy->getObjProxy(); - TLOGERROR("[TARS][_onConnect:" << obj->name() << " can't find client SSL_CTX " << endl); + TLOGERROR("[TARS][onConnect:" << obj->name() << " can't find client SSL_CTX " << endl); this->close(); return; } - _openssl.reset(new TC_OpenSSL()); - _openssl->Init(ssl, false); - int ret = _openssl->DoHandshake(_sendBuffer); + _openssl->init(false); + int ret = _openssl->doHandshake(_sendBuffer); if (ret != 0) { TLOGERROR("[TARS] SSL_connect failed " << endl); @@ -192,13 +189,12 @@ void Transceiver::onConnect() return; } -// _sendBuffer.addBuffer(out); - // send the encrypt data from write buffer if (!_sendBuffer.empty()) { - this->doRequest(); -// this->sendRequest(_sendBuffer); + TLOGTARS("[TARS][Transceiver::onConnect doRequest handshake:" << _openssl->isHandshaked() << ", length:" << _sendBuffer.getBufferLength() << endl); + + doRequest(); } return; } @@ -231,7 +227,6 @@ void Transceiver::doAuthReq() void Transceiver::finishInvoke(shared_ptr &rsp) { - if (_authState != AUTH_SUCC) { std::string ret(rsp->sBuffer.begin(), rsp->sBuffer.end()); @@ -300,7 +295,7 @@ void Transceiver::close() #if TARS_SSL if (_openssl) { - _openssl->Release(); + _openssl->release(); _openssl.reset(); } #endif @@ -325,10 +320,6 @@ void Transceiver::close() _recvBuffer.clearBuffers(); - // _sendBuffer.Clear(); - - // _recvBuffer.Clear(); - _authState = AUTH_INIT; TLOGTARS("[TARS][trans close:"<< _adapterProxy->getObjProxy()->name()<< "," << _ep.desc() << "]" << endl); @@ -367,7 +358,6 @@ int Transceiver::doRequest() } _sendBuffer.moveHeader(iRet); -// _sendBuffer->add(iRet); } //取adapter里面积攒的数据 @@ -393,14 +383,14 @@ int Transceiver::sendRequest(const shared_ptr &buff, b return eRetError; } - if (!forceSend && _authState != AUTH_SUCC) + if (!forceSend && _authState != AUTH_SUCC && !isSSL()) { -#if TARS_SSL - if (isSSL() && !_openssl) - return eRetError; -#endif +//#if TARS_SSL +// if (isSSL() && !_openssl) +// return eRetError; +//#endif ObjectProxy* obj = _adapterProxy->getObjProxy(); - TLOGTARS("[TARS][Transceiver::sendRequest temporary failed because need auth for " << obj->name() << endl); + TLOGTARS("[TARS][Transceiver::sendRequest failed, need auth for " << obj->name() << endl); return eRetError; // 需要鉴权但还没通过,不能发送非认证消息 } @@ -410,7 +400,48 @@ int Transceiver::sendRequest(const shared_ptr &buff, b return eRetError; } - int iRet = this->send(buff->buffer(), (uint32_t)buff->length(), 0); +#if TARS_SSL + // 握手数据已加密,直接发送,会话数据需加密 + if (isSSL()) + { + if(!_openssl->isHandshaked()) { + return eRetError; + } + + _openssl->write(buff->buffer(), (uint32_t) buff->length(), _sendBuffer); + + size_t length = _sendBuffer.getBufferLength(); + + do + { + auto data = _sendBuffer.getBufferPointer(); + + int iRet = this->send(data.first, (uint32_t) data.second, 0); + + //失败, 且任何数据都没有发送出去, socket写满了! + if (iRet < 0 && _sendBuffer.getBufferLength() == length) { + //clear data, data will send again! + _sendBuffer.clearBuffers(); + return eRetError; + } + else if(iRet < 0) + { + //之前发送了部分数据, socket写满了 + return eRetFull; + } + + _sendBuffer.moveHeader(iRet); + + } + while (!_sendBuffer.empty()); + + return eRetOk; + } +#endif + +// TLOGTARS("[TARS][Transceiver::sendRequest handshake:" << _openssl->isHandshaked() << ", origin length:" << buff->length() << endl); + + int iRet = this->send(buff->buffer(), (uint32_t)buff->length(), 0); //失败,直接返回 if(iRet<0) { @@ -422,22 +453,15 @@ int Transceiver::sendRequest(const shared_ptr &buff, b { buff->add(iRet); _sendBuffer.addBuffer(buff); -// _sendBuffer = buff; -// _sendBuffer->add(iRet); return eRetFull; } -// else -// { -// //全部发送完毕了 -// _sendBuffer.reset(); -// } return eRetOk; // #if TARS_SSL // // 握手数据已加密,直接发送,会话数据需加密 // std::string out; -// if (isSSL() && _openssl->IsHandshaked()) +// if (isSSL() && _openssl->isHandshaked()) // { // out = _openssl->Write(pData, iSize); // pData = out.data(); @@ -484,8 +508,34 @@ int TcpTransceiver::doResponse() if ((iRet = this->recv(buff, BUFFER_SIZE, 0)) > 0) { - _recvBuffer.addBuffer(buff, iRet); + TC_NetWorkBuffer *rbuf = &_recvBuffer; +#if TARS_SSL + if (isSSL()) + { + const bool preNotHandshake = !_openssl->isHandshaked(); + int ret = _openssl->read(buff, iRet, _sendBuffer); + if (ret != 0) + { + TLOGERROR("[TARS][SSL_connect handshake failed: " << _adapterProxy->getObjProxy()->name() << ", info:" << _openssl->getErrMsg() << endl); + close(); + return -1; + } + else + { + doRequest(); + } + if (!_openssl->isHandshaked()) + return 0; + + if (preNotHandshake) + doAuthReq(); + + rbuf = _openssl->recvBuffer(); + } +#else + rbuf->addBuffer(buff, iRet); +#endif ++recvCount; try @@ -495,7 +545,7 @@ int TcpTransceiver::doResponse() { shared_ptr rsp = std::make_shared(); - ret = _adapterProxy->getObjProxy()->getProxyProtocol().responseFunc(_recvBuffer, *rsp.get()); + ret = _adapterProxy->getObjProxy()->getProxyProtocol().responseFunc(*rbuf, *rsp.get()); if (ret == TC_NetWorkBuffer::PACKET_ERR) { TLOGERROR( "[TARS][tcp doResponse," << _adapterProxy->getObjProxy()->name() << ",fd:" << _fd << "," << _ep.desc() << ",tcp recv decode error" << endl); @@ -510,7 +560,7 @@ int TcpTransceiver::doResponse() } } - while (ret == TC_NetWorkBuffer::PACKET_FULL && !_recvBuffer.empty()); + while (ret == TC_NetWorkBuffer::PACKET_FULL && !rbuf->empty()); //接收的数据小于buffer大小, 内核会再次通知你 if(iRet < BUFFER_SIZE) @@ -595,7 +645,7 @@ int TcpTransceiver::doResponse() // #if TARS_SSL // if (isSSL()) // { -// const bool preNotHandshake = !_openssl->IsHandshaked(); +// const bool preNotHandshake = !_openssl->isHandshaked(); // std::string out; // if (!_openssl->Read(_recvBuffer.ReadAddr(), _recvBuffer.ReadableSize(), out)) // { @@ -610,13 +660,13 @@ int TcpTransceiver::doResponse() // _recvBuffer.Clear(); -// if (!_openssl->IsHandshaked()) +// if (!_openssl->isHandshaked()) // return 0; // if (preNotHandshake) // doAuthReq(); -// std::string* plainBuf = _openssl->RecvBuffer(); +// std::string* plainBuf = _openssl->recvBuffer(); // data = plainBuf->data(); // len = plainBuf->size(); // } @@ -639,7 +689,7 @@ int TcpTransceiver::doResponse() // #if TARS_SSL // if (isSSL()) // { -// std::string* plainBuf = _openssl->RecvBuffer(); +// std::string* plainBuf = _openssl->recvBuffer(); // plainBuf->erase(0, pos); // } // else @@ -676,7 +726,8 @@ int TcpTransceiver::send(const void* buf, uint32_t len, uint32_t flag) if(eConnected != _connStatus) return -1; - int iRet = ::send(_fd, (const char*)buf, len, flag); + + int iRet = ::send(_fd, (const char*)buf, len, flag); if (iRet < 0 && !TC_Socket::isPending()) { diff --git a/servant/servant/Application.h b/servant/servant/Application.h index bd8144c..0e71c74 100644 --- a/servant/servant/Application.h +++ b/servant/servant/Application.h @@ -114,15 +114,21 @@ struct ServerConfig static std::string Config; //配置中心地址 static std::string Notify; //信息通知中心 static std::string ConfigFile; //框架配置文件路径 + static bool CloseCout; static int ReportFlow; //是否服务端上报所有接口stat流量 0不上报 1上报(用于非tars协议服务流量统计) static int IsCheckSet; //是否对按照set规则调用进行合法性检查 0,不检查,1检查 static bool OpenCoroutine; //是否启用协程处理方式 static size_t CoroutineMemSize; //协程占用内存空间的最大大小 static uint32_t CoroutineStackSize; //每个协程的栈大小(默认128k) - static bool ManualListen; //是否启用手工端口监听 + static int NetThread; //servernet thread + static bool ManualListen; //是否启用手工端口监听 static bool MergeNetImp; //网络线程和IMP线程合并(以网络线程个数为准) - static bool OpenSSL; //is open ssl - +#if TARS_SSL + static std::string CA; + static std::string Cert; + static std::string Key; + static bool VerifyClient; +#endif }; class PropertyReport; diff --git a/servant/servant/Communicator.h b/servant/servant/Communicator.h index 931c0de..d59c2f7 100644 --- a/servant/servant/Communicator.h +++ b/servant/servant/Communicator.h @@ -34,6 +34,9 @@ #endif #define CONFIG_ROOT_PATH "/tars/application/client" +// +//struct ssl_ctx_st; +//typedef struct ssl_ctx_st SSL_CTX; namespace tars { @@ -341,6 +344,9 @@ protected: */ size_t _asyncSeq; +//#if TARS_SSL +// shared_ptr _ctx; +//#endif #ifdef _USE_OPENTRACKING public: struct TraceManager:public TC_HandleBase{ diff --git a/servant/servant/Transceiver.h b/servant/servant/Transceiver.h index 2f4a168..1597abf 100755 --- a/servant/servant/Transceiver.h +++ b/servant/servant/Transceiver.h @@ -278,7 +278,7 @@ protected: protected: #if TARS_SSL - std::unique_ptr _openssl; + std::shared_ptr _openssl; #endif #if TARS_HTTP2 @@ -287,8 +287,6 @@ protected: /* * 发送buffer */ -// shared_ptr _sendBuffer; - TC_NetWorkBuffer _sendBuffer; /* diff --git a/util/include/util/tc_epoll_server.h b/util/include/util/tc_epoll_server.h index f6edb75..0425a52 100644 --- a/util/include/util/tc_epoll_server.h +++ b/util/include/util/tc_epoll_server.h @@ -28,15 +28,8 @@ #include "util/tc_thread.h" #include "util/tc_clientsocket.h" #include "util/tc_logger.h" -// #include "util/tc_shm.h" #include "util/tc_common.h" -// #include "util/tc_mem_queue.h" -// #include "util/tc_squeue.h" -// #include "util/tc_mmap.h" -// #include "util/tc_fifo.h" #include "util/tc_network_buffer.h" -// #include "util/tc_buffer.h" -// #include "util/tc_buffer_pool.h" #include "util/tc_cas_queue.h" using namespace std; @@ -71,13 +64,6 @@ public: /** * 定义协议解析的返回值 */ - // enum - // { - // PACKET_LESS = 0, - // PACKET_FULL = 1, - // PACKET_ERR = -1, - // }; - enum EM_CLOSE_T { EM_CLIENT_CLOSE = 0, //客户端主动关闭 @@ -85,14 +71,6 @@ public: EM_SERVER_TIMEOUT_CLOSE = 2 //连接超时了,服务端主动关闭 }; - //定义事件类型 - // enum - // { - // ET_LISTEN = 1, - // ET_CLOSE = 2, - // ET_NOTIFY = 3, - // ET_NET = 0, - // }; enum { MIN_EMPTY_CONN_TIMEOUT = 2*1000, /*空链接超时时间(ms)*/ @@ -482,13 +460,6 @@ public: TC_ThreadLock _monitor; }; - // BindAdapter() - // { - // _pReportQueue = NULL; - // _pReportConRate = NULL; - // _pReportTimeoutNum = NULL; - // } - /** * 构造函数 */ @@ -877,16 +848,6 @@ public: */ void setOnClose(const close_functor& f) { _closeFunc = f; } - /** - * 注册协议解析器 - */ - // void setConnProtocol(const TC_NetWorkBuffer::protocol_functor& cpf, int iHeaderLen = 0, const header_filter_functor& hf = echo_header_filter); - - /** - * 获取协议解析器 - * @return protocol_functor& - */ - // const TC_NetWorkBuffer::protocol_functor& getConnProtocol() { return _cpf; } /** * 注册鉴权包裹函数 * @param apwf @@ -915,7 +876,6 @@ public: protected: friend class TC_EpollServer; - // friend class NetThread; /** * 服务 @@ -927,11 +887,6 @@ public: */ mutable std::mutex _mutex; - /** - * Adapter所用的HandleGroup - */ - // HandleGroupPtr _handleGroup; - /** * Adapter所用的HandleGroup */ @@ -1003,11 +958,6 @@ public: */ atomic _iBufferSize{0}; - /** - * 接收的数据队列 - */ - // recv_queue _rbuffer; - /** * 队列最大容量 */ @@ -1056,8 +1006,6 @@ public: //连接关闭的回调函数 close_functor _closeFunc; - // 协议解析 - // TC_NetWorkBuffer::protocol_functor _cpf; }; //////////////////////////////////////////////////////////////////////////// @@ -1233,7 +1181,7 @@ public: * @param o * @return int: <0:协议错误, 0:没有一个完整的包, 1:收到至少一个包 */ - int parseProtocol(); + int parseProtocol(TC_NetWorkBuffer &rbuf); /** * 增加数据到队列中 @@ -1340,7 +1288,7 @@ public: */ bool _authInit; #if TARS_SSL - std::unique_ptr _openssl; + std::shared_ptr _openssl; #endif }; //////////////////////////////////////////////////////////////////////////// diff --git a/util/include/util/tc_openssl.h b/util/include/util/tc_openssl.h index 62256f9..65f896f 100644 --- a/util/include/util/tc_openssl.h +++ b/util/include/util/tc_openssl.h @@ -22,45 +22,46 @@ #include #include #include "util/tc_network_buffer.h" -#include "util/tc_sslmgr.h" struct ssl_st; typedef struct ssl_st SSL; +struct bio_st; +typedef struct bio_st BIO; + namespace tars { ///////////////////////////////////////////////// /** *@file tc_openssl.h - *@brief OpenSsl封装 + *@brief OpenSsl wrapper * */ ///////////////////////////////////////////////// /** - *@brief OpenSsl封装 + *@brief OpenSsl wrapper */ class TC_OpenSSL { public: - /** - * @brief 构造函数. - */ - TC_OpenSSL(); /** - * @brief 析构函数. + * @brief constructor. + */ + TC_OpenSSL(SSL* ssl); + + /** + * @brief deconstructor. */ ~TC_OpenSSL(); -// static SSL* newSSL(const std::string& ctxName); static void getMemData(BIO* bio, TC_NetWorkBuffer& buf); -// static void getSSLHead(const char* data, char& type, unsigned short& ver, unsigned short& len) static int doSSLRead(SSL* ssl, TC_NetWorkBuffer& out); private: /** - * @brief 禁止复制 + * @brief deny */ TC_OpenSSL(const TC_OpenSSL& ); void operator=(const TC_OpenSSL& ); @@ -68,69 +69,84 @@ private: public: /** - * @brief 释放SSL + * @brief release SSL */ - void Release(); + void release(); /** - * @brief 初始化SSL + * @brief init SSL */ - void Init(SSL* ssl, bool isServer); + void init(bool isServer); /** - * @brief 握手是否完成 - * @return 握手是否完成 + * @brief is handshake finish + * @return true: is handshake finish */ - bool IsHandshaked() const; + bool isHandshaked() const; /** - * @brief 当前接收缓冲区 + * get error message + * @return */ - TC_NetWorkBuffer * RecvBuffer() { return &_plainBuf; } + string getErrMsg() const; + + /** + * @brief get recv buffer + */ + TC_NetWorkBuffer * recvBuffer() { return &_plainBuf; } /** - * @brief 握手 - * @return 需要发送的握手数据 + * @brief handshake + * @return 0: succ, !=0: fail */ - int DoHandshake(TC_NetWorkBuffer &out, const void* data = NULL, size_t size = 0); + int doHandshake(TC_NetWorkBuffer &out, const void* data = NULL, size_t size = 0); /** - * @brief 发送数据前加密 - * @param data 数据的指针 - * @param size 数据的大小 - * @return 加密后的数据 + * @brief encode data before send + * @param data, data pointer + * @param size, data size + * @param out, out buffer + * @return 0: succ, !=0: fail */ - int Write(const char* data, size_t size, TC_NetWorkBuffer &out); + int write(const char* data, size_t size, TC_NetWorkBuffer &out); /** - * @brief 接收数据后解密 - * @param data 数据的指针 - * @param size 数据的大小 - * @param out 需要发送的数据 - * @return 解密后的数据 + * @brief decode data before parse protocol + * @param data data pointer + * @param size data size + * @param out out buffer + * @return 0: succ, !=0: fail */ - int Read(const void* data, size_t size, TC_NetWorkBuffer &out); + int read(const void* data, size_t size, TC_NetWorkBuffer &out); + friend class TC_SSLManager; private: + /** * ssl handle */ SSL* _ssl; /** - * 是否握手完成了 + * is handeshake succ */ bool _bHandshaked; /** - * 是否服务端 + * server/client */ bool _isServer; + /** + * ssl error code + */ + int _err; + /** - * 收到的数据解密后 + * recv buff */ TC_NetWorkBuffer _plainBuf; + }; } // end namespace tars diff --git a/util/include/util/tc_sslmgr.h b/util/include/util/tc_sslmgr.h index d64dbc2..2a40457 100644 --- a/util/include/util/tc_sslmgr.h +++ b/util/include/util/tc_sslmgr.h @@ -21,64 +21,68 @@ #include #include -// #include "util/tc_buffer.h" #include "util/tc_network_buffer.h" #include "util/tc_singleton.h" -struct bio_st; -typedef struct bio_st BIO; - -struct ssl_st; +struct ssl_st; typedef struct ssl_st SSL; struct ssl_ctx_st; typedef struct ssl_ctx_st SSL_CTX; -struct ssl_method_st; -typedef struct ssl_method_st SSL_METHOD; - namespace tars { ///////////////////////////////////////////////// /** *@file tc_sslmgr.h - *@brief SSL_CTX集合 + *@brief manager ssl, not thread safe!! */ ///////////////////////////////////////////////// -static const size_t kSSLHeadSize = 5; - - // new ssl conn - // fetch data from mem bio -// void GetMemData(BIO* bio, TC_NetWorkBuffer& buf); - // fetch ssl head info -// void GetSSLHead(const char* data, char& type, unsigned short& ver, unsigned short& len); - // read from ssl -// bool DoSSLRead(SSL*, std::string& out); +class TC_OpenSSL; class TC_SSLManager : public TC_Singleton { public: - static void GlobalInit(); - + /** + * @brief constructor. + */ TC_SSLManager(); + /** + * @brief deconstructor. + */ ~TC_SSLManager(); - SSL* newSSL(const std::string& ctxName); + /** + * @brief new ssl + */ + shared_ptr newSSL(const std::string& ctxName); - bool addCtx(const std::string& name, + /** + * @brief add ctx + * @param name: ctx name + * @param cafile: peer cafile + * @param certfile: cert cafile + * @param keyfile: key file + * @param verifyClient: if verfy client + */ + bool addCtx(const std::string& name, const std::string& cafile, const std::string& certfile, const std::string& keyfile, bool verifyClient); - SSL_CTX* getCtx(const std::string& name) const; +protected: + SSL_CTX* getCtx(const std::string& name) const; + SSL* newSSL(SSL_CTX *ctx); + SSL_CTX *newCtx(const std::string& cafile, const std::string& certfile, const std::string& keyfile, bool verifyClient); private: typedef std::map CTX_MAP; + CTX_MAP _ctxSet; }; diff --git a/util/src/tc_epoll_server.cpp b/util/src/tc_epoll_server.cpp index 9c64d51..06d50f4 100644 --- a/util/src/tc_epoll_server.cpp +++ b/util/src/tc_epoll_server.cpp @@ -19,6 +19,8 @@ #include "util/tc_common.h" #include "util/tc_network_buffer.h" #include "util/tc_timeprovider.h" +#include "util/tc_sslmgr.h" + #include #include @@ -359,7 +361,6 @@ bool TC_EpollServer::BindAdapter::isIpAllow(const string& ip) const return _vtAllow.size() == 0; } - void TC_EpollServer::BindAdapter::manualListen() { this->getEpollServer()->_epoller.mod(getSocket().getfd(), getSocket().getfd(), EPOLLIN|EPOLLOUT); @@ -763,7 +764,7 @@ void TC_EpollServer::Connection::close() #if TARS_SSL if (_openssl) { - _openssl->Release(); + _openssl->release(); _openssl.reset(); } #endif @@ -804,67 +805,36 @@ void TC_EpollServer::Connection::insertRecvQueue(const shared_ptr 0) { - if(_recvBuffer.getBufferLength() >= (unsigned) _iHeaderLen) + if(rbuf.getBufferLength() >= (unsigned) _iHeaderLen) { vector header; - _recvBuffer.getHeader(_iHeaderLen, header); + rbuf.getHeader(_iHeaderLen, header); _pBindAdapter->getHeaderFilterFunctor()(TC_NetWorkBuffer::PACKET_FULL, header); - _recvBuffer.moveHeader(_iHeaderLen); + rbuf.moveHeader(_iHeaderLen); _iHeaderLen = 0; } else { - vector header = _recvBuffer.getBuffers(); + vector header = rbuf.getBuffers(); _pBindAdapter->getHeaderFilterFunctor()(TC_NetWorkBuffer::PACKET_LESS, header); - _iHeaderLen -= (int)_recvBuffer.getBufferLength(); - _recvBuffer.clearBuffers(); + _iHeaderLen -= (int)rbuf.getBufferLength(); + rbuf.clearBuffers(); break; } } - TC_NetWorkBuffer *rbuf = &_recvBuffer; -#if TARS_SSL - // ssl connection - if (_pBindAdapter->getEndpoint().isSSL()) - { - const char * data = _recvBuffer.mergeBuffers(); - -// std::string out; - int ret = _openssl->Read(data, _recvBuffer.getBufferLength(), _sendBuffer); - if (ret != 0) - // if (!_openssl->Read(buffer, BUFFER_SIZE, out)) - { - _pBindAdapter->getEpollServer()->error("[TARS][SSL_read failed"); - return -1; - } - else - { - if (!_sendBuffer.empty()) - { - this->sendBuffer(); - } - - rbuf = _openssl->RecvBuffer(); - } - - _recvBuffer.clearBuffers(); - // _recvBuffer.clear(); - } -#endif - - // string ro; vector ro; - TC_NetWorkBuffer::PACKET_TYPE b = _pBindAdapter->getProtocol()(*rbuf, ro); + TC_NetWorkBuffer::PACKET_TYPE b = _pBindAdapter->getProtocol()(rbuf, ro); if(b == TC_NetWorkBuffer::PACKET_LESS) { //包不完全 @@ -910,6 +880,8 @@ int TC_EpollServer::Connection::recvTcp() { int recvCount = 0; + TC_NetWorkBuffer *rbuf = &_recvBuffer; + while (true) { char buffer[BUFFER_SIZE] = {0x00}; @@ -938,12 +910,36 @@ int TC_EpollServer::Connection::recvTcp() } else { -// totalRecv += iBytesReceived; - _recvBuffer.addBuffer(buffer, iBytesReceived); + +#if TARS_SSL + if (_pBindAdapter->getEndpoint().isSSL()) + { +// const char * data = _recvBuffer.mergeBuffers(); +// cout << "parseProtocol:" << _recvBuffer.getBufferLength() << endl; + + int ret = _openssl->read(buffer, iBytesReceived, _sendBuffer); + if (ret != 0) + { + _pBindAdapter->getEpollServer()->error("[TARS][SSL_read failed: " + _openssl->getErrMsg()); + return -1; + } + else + { + if (!_sendBuffer.empty()) + { + sendBuffer(); + } + + rbuf = _openssl->recvBuffer(); + } + } +#else + rbuf->addBuffer(buffer, iBytesReceived); +#endif //字符串太长时, 强制解析协议 - if (_recvBuffer.getBufferLength() > 8192) { - parseProtocol(); + if (rbuf->getBufferLength() > 8192) { + parseProtocol(*rbuf); } //接收到数据不超过buffer,没有数据了(如果有数据,内核会再通知你) @@ -960,7 +956,7 @@ int TC_EpollServer::Connection::recvTcp() } } - return parseProtocol(); + return parseProtocol(*rbuf); } int TC_EpollServer::Connection::recvUdp() @@ -1000,7 +996,7 @@ int TC_EpollServer::Connection::recvUdp() //保存接收到数据 _recvBuffer.addBuffer(_pRecvBuffer, iBytesReceived); - parseProtocol(); + parseProtocol(_recvBuffer); } else { @@ -1472,27 +1468,24 @@ void TC_EpollServer::NetThread::addTcpConnection(TC_EpollServer::Connection *cPt cPtr->getBindAdapter()->getEpollServer()->info("[TARS][addTcpConnection ssl connection"); // 分配ssl对象, ctxName 放在obj proxy里 - SSL* ssl = TC_SSLManager::getInstance()->newSSL("server"); - if (!ssl) + cPtr->_openssl = TC_SSLManager::getInstance()->newSSL("server"); + if (!cPtr->_openssl) { cPtr->getBindAdapter()->getEpollServer()->error("[TARS][SSL_accept not find server cert"); cPtr->close(); -// this->close(uid); return; } - cPtr->_openssl.reset(new TC_OpenSSL()); - cPtr->_openssl->Init(ssl, true); + cPtr->_openssl->init(true); - int ret = cPtr->_openssl->DoHandshake(cPtr->_sendBuffer); + int ret = cPtr->_openssl->doHandshake(cPtr->_sendBuffer); if (ret != 0) { - cPtr->getBindAdapter()->getEpollServer()->error("[TARS][SSL_accept error: " + cPtr->getBindAdapter()->getEndpoint().toString()); + cPtr->getBindAdapter()->getEpollServer()->error("[TARS][SSL_accept " + cPtr->getBindAdapter()->getEndpoint().toString() + " error: " + cPtr->_openssl->getErrMsg()); cPtr->close(); -// this->close(uid); return; } - + // send the encrypt data from write buffer if (!cPtr->_sendBuffer.empty()) { @@ -1628,7 +1621,7 @@ void TC_EpollServer::NetThread::processPipe() { int ret = 0; #if TARS_SSL - if (cPtr->getBindAdapter()->getEndpoint().isSSL() && cPtr->_openssl->IsHandshaked()) + if (cPtr->getBindAdapter()->getEndpoint().isSSL() && cPtr->_openssl->isHandshaked()) { // std::string out = cPtr->_openssl->Write((*it)->buffer.data(), (*it)->buffer.size()); // if (cPtr->_openssl->HasError()) @@ -1636,7 +1629,7 @@ void TC_EpollServer::NetThread::processPipe() // // (*it)->buffer = out; - ret = cPtr->_openssl->Write(sc->buffer()->buffer(), sc->buffer()->length(), cPtr->_sendBuffer); + ret = cPtr->_openssl->write(sc->buffer()->buffer(), sc->buffer()->length(), cPtr->_sendBuffer); if (ret != 0) break; // should not happen diff --git a/util/src/tc_openssl.cpp b/util/src/tc_openssl.cpp index de6daa0..51e3b12 100644 --- a/util/src/tc_openssl.cpp +++ b/util/src/tc_openssl.cpp @@ -20,26 +20,29 @@ #include #include "util/tc_openssl.h" -//#include "util/tc_buffer.h" namespace tars { -TC_OpenSSL::TC_OpenSSL() -: _ssl(NULL) + +////////////////////////////////////////////////////////////////////////////////////////// + +TC_OpenSSL::TC_OpenSSL(SSL* ssl) +: _ssl(ssl) , _bHandshaked(false) , _isServer(false) +, _err(0) , _plainBuf(NULL) { } TC_OpenSSL::~TC_OpenSSL() { - Release(); + release(); } -void TC_OpenSSL::Release() +void TC_OpenSSL::release() { if (_ssl) { @@ -47,29 +50,51 @@ void TC_OpenSSL::Release() _ssl = NULL; } _bHandshaked = false; -// _err = 0; + _err = 0; } -void TC_OpenSSL::Init(SSL* ssl, bool isServer) +void TC_OpenSSL::init(bool isServer) { - assert (_ssl == NULL); - _ssl = ssl; _bHandshaked = false; _isServer = isServer; -// _err = 0; + _err = 0; } -bool TC_OpenSSL::IsHandshaked() const +std::string TC_OpenSSL::getErrMsg() const +{ + std::shared_ptr bio( BIO_new( BIO_s_mem() ), BIO_free ); + ERR_print_errors(bio.get()); + string buffer; + buffer.resize(255); + + unsigned int startPos = 0; + unsigned int bytesRead = 0; + while (true) + { + int ret = BIO_read(bio.get(), &buffer[startPos], static_cast(buffer.size()-startPos)); + if (ret > 0) + { + bytesRead += ret; + } + if (bytesRead < buffer.size()) + { + break; + } + startPos = static_cast(buffer.size()); + buffer.resize( 2*buffer.size() ); + } + + buffer.resize(bytesRead); + return buffer; +} + +bool TC_OpenSSL::isHandshaked() const { return _bHandshaked; } -//bool TC_OpenSSL::HasError() const -//{ -// return _err != 0; -//} -int TC_OpenSSL::DoHandshake(TC_NetWorkBuffer &out, const void* data, size_t size) +int TC_OpenSSL::doHandshake(TC_NetWorkBuffer &out, const void* data, size_t size) { assert (!_bHandshaked); assert (_ssl); @@ -83,14 +108,15 @@ int TC_OpenSSL::DoHandshake(TC_NetWorkBuffer &out, const void* data, size_t size ERR_clear_error(); int ret = _isServer ? SSL_accept(_ssl) : SSL_connect(_ssl); - int err = 0; + _err = 0; if (ret <= 0) { - err = SSL_get_error(_ssl, ret); - if (err != SSL_ERROR_WANT_READ) + _err = SSL_get_error(_ssl, ret); + + if (_err != SSL_ERROR_WANT_READ) { - return err; + return _err; } } @@ -99,21 +125,12 @@ int TC_OpenSSL::DoHandshake(TC_NetWorkBuffer &out, const void* data, size_t size _bHandshaked = true; } - // the encrypted data from write buffer -// vector out; -// TC_Buffer outdata; getMemData(SSL_get_wbio(_ssl), out); -// if (!outdata.IsEmpty()) -// { -// out.assign(outdata.ReadAddr(), outdata.ReadableSize()); -// } - -// return out; return 0; } -int TC_OpenSSL::Write(const char* data, size_t size, TC_NetWorkBuffer &out) +int TC_OpenSSL::write(const char* data, size_t size, TC_NetWorkBuffer &out) { if (!_bHandshaked) { @@ -127,29 +144,28 @@ int TC_OpenSSL::Write(const char* data, size_t size, TC_NetWorkBuffer &out) int ret = SSL_write(_ssl, data, size); if (ret <= 0) { - return SSL_get_error(_ssl, ret); + _err = SSL_get_error(_ssl, ret); + return _err; } -// _err = 0; + _err = 0; -// TC_Buffer toSend; getMemData(SSL_get_wbio(_ssl), out); - return 0; -// return std::string(toSend.ReadAddr(), toSend.ReadableSize()); + return _err; } -int TC_OpenSSL::Read(const void* data, size_t size, TC_NetWorkBuffer &out) +int TC_OpenSSL::read(const void* data, size_t size, TC_NetWorkBuffer &out) { bool usedData = false; if (!_bHandshaked) { usedData = true; _plainBuf.clearBuffers(); - int ret = DoHandshake(out, data, size); + int ret = doHandshake(out, data, size); if (ret != 0) - return false; + return ret; - if (_bHandshaked) +// if (_bHandshaked) ; // TODO onHandshake } @@ -162,7 +178,8 @@ int TC_OpenSSL::Read(const void* data, size_t size, TC_NetWorkBuffer &out) BIO_write(SSL_get_rbio(_ssl), data, size); } - if (!doSSLRead(_ssl, _plainBuf)) + _err = doSSLRead(_ssl, _plainBuf); + if(_err != 0) { return SSL_ERROR_SSL; } @@ -170,23 +187,6 @@ int TC_OpenSSL::Read(const void* data, size_t size, TC_NetWorkBuffer &out) return 0; } -// -//SSL* TC_OpenSSL::newSSL(const std::string& ctxName) -//{ -// SSL_CTX* ctx = TC_SSLManager::getInstance()->GetCtx(ctxName); -// if (!ctx) -// return NULL; -// -// SSL* ssl = SSL_new(ctx); -// -// SSL_set_mode(ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); // allow retry ssl-write with different args -// SSL_set_bio(ssl, BIO_new(BIO_s_mem()), BIO_new(BIO_s_mem())); -// -// BIO_set_mem_eof_return(SSL_get_rbio(ssl), -1); -// BIO_set_mem_eof_return(SSL_get_wbio(ssl), -1); -// -// return ssl; -//} void TC_OpenSSL::getMemData(BIO* bio, TC_NetWorkBuffer& buf) { @@ -200,16 +200,6 @@ void TC_OpenSSL::getMemData(BIO* bio, TC_NetWorkBuffer& buf) buf.addBuffer(data, bytes); } } -// -//void TC_OpenSSL::getSSLHead(const char* data, char& type, unsigned short& ver, unsigned short& len) -//{ -// type = data[0]; -// ver = *(unsigned short*)(data + 1); -// len = *(unsigned short*)(data + 3); -// -// ver = ntohs(ver); -// len = ntohs(len); -//} int TC_OpenSSL::doSSLRead(SSL* ssl, TC_NetWorkBuffer& out) { diff --git a/util/src/tc_sslmgr.cpp b/util/src/tc_sslmgr.cpp index 4091e56..dcbb788 100644 --- a/util/src/tc_sslmgr.cpp +++ b/util/src/tc_sslmgr.cpp @@ -17,8 +17,7 @@ #if TARS_SSL #include "util/tc_sslmgr.h" -// #include "util/tc_buffer.h" -// #include +#include "util/tc_openssl.h" #include #include @@ -27,23 +26,17 @@ namespace tars TC_SSLManager::TC_SSLManager() { + + (void)SSL_library_init(); + OpenSSL_add_all_algorithms(); + + ERR_load_ERR_strings(); + SSL_load_error_strings(); } -void TC_SSLManager::GlobalInit() -{ - (void)SSL_library_init(); - OpenSSL_add_all_algorithms(); - - ERR_load_ERR_strings(); - SSL_load_error_strings(); -} - - TC_SSLManager::~TC_SSLManager() { - for (CTX_MAP::iterator it(_ctxSet.begin()); - it != _ctxSet.end(); - ++ it) + for (CTX_MAP::iterator it(_ctxSet.begin()); it != _ctxSet.end(); ++ it) { SSL_CTX_free(it->second); } @@ -52,46 +45,69 @@ TC_SSLManager::~TC_SSLManager() EVP_cleanup(); } -bool TC_SSLManager::addCtx(const std::string& name, const std::string& cafile, const std::string& certfile, const std::string& keyfile, bool verifyClient) +SSL* TC_SSLManager::newSSL(SSL_CTX *ctx) { - if (_ctxSet.count(name)) - return false; - - SSL_CTX* ctx = SSL_CTX_new(SSLv23_method()); - if (!ctx) - return false; + SSL* ssl = SSL_new(ctx); + + SSL_set_mode(ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); // allow retry ssl-write with different args + SSL_set_bio(ssl, BIO_new(BIO_s_mem()), BIO_new(BIO_s_mem())); + + BIO_set_mem_eof_return(SSL_get_rbio(ssl), -1); + BIO_set_mem_eof_return(SSL_get_wbio(ssl), -1); + + return ssl; +} + +SSL_CTX *TC_SSLManager::newCtx(const std::string& cafile, const std::string& certfile, const std::string& keyfile, bool verifyClient) +{ + SSL_CTX* ctx = SSL_CTX_new(SSLv23_method()); + if (!ctx) + return NULL; #define RETURN_IF_FAIL(call) \ if ((call) <= 0) { \ ERR_print_errors_fp(stderr); \ - return false;\ + return NULL;\ } - if (verifyClient) - SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); - else - SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); + if (verifyClient) + SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); + else + SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); - SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); - SSL_CTX_clear_options(ctx, SSL_OP_LEGACY_SERVER_CONNECT); - SSL_CTX_clear_options(ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); + SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); + SSL_CTX_clear_options(ctx, SSL_OP_LEGACY_SERVER_CONNECT); + SSL_CTX_clear_options(ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); - RETURN_IF_FAIL (SSL_CTX_set_session_id_context(ctx, (const unsigned char*)ctx, sizeof ctx)); - if (!cafile.empty()) - RETURN_IF_FAIL (SSL_CTX_load_verify_locations(ctx, cafile.data(), NULL)); + RETURN_IF_FAIL (SSL_CTX_set_session_id_context(ctx, (const unsigned char*)ctx, sizeof ctx)); + if (!cafile.empty()) + RETURN_IF_FAIL (SSL_CTX_load_verify_locations(ctx, cafile.data(), NULL)); - // 客户端可以不提供证书的 - if (!certfile.empty()) - RETURN_IF_FAIL (SSL_CTX_use_certificate_file(ctx, certfile.data(), SSL_FILETYPE_PEM)); + // 客户端可以不提供证书的 + if (!certfile.empty()) + RETURN_IF_FAIL (SSL_CTX_use_certificate_file(ctx, certfile.data(), SSL_FILETYPE_PEM)); - if (!keyfile.empty()) - { - RETURN_IF_FAIL (SSL_CTX_use_PrivateKey_file(ctx, keyfile.data(), SSL_FILETYPE_PEM)); - RETURN_IF_FAIL (SSL_CTX_check_private_key(ctx)); - } + if (!keyfile.empty()) + { + RETURN_IF_FAIL (SSL_CTX_use_PrivateKey_file(ctx, keyfile.data(), SSL_FILETYPE_PEM)); + RETURN_IF_FAIL (SSL_CTX_check_private_key(ctx)); + } #undef RETURN_IF_FAIL + return ctx; +} + +bool TC_SSLManager::addCtx(const std::string& name, const std::string& cafile, const std::string& certfile, const std::string& keyfile, bool verifyClient) +{ + if (_ctxSet.count(name)) + return false; + + SSL_CTX* ctx = newCtx(cafile, certfile, keyfile, verifyClient); + + if (!ctx) + return false; + return _ctxSet.insert(std::make_pair(name, ctx)).second; } @@ -101,78 +117,16 @@ SSL_CTX* TC_SSLManager::getCtx(const std::string& name) const return it == _ctxSet.end() ? NULL: it->second; } -SSL* TC_SSLManager::newSSL(const std::string& ctxName) +shared_ptr TC_SSLManager::newSSL(const std::string& ctxName) { - SSL_CTX* ctx = TC_SSLManager::getInstance()->getCtx(ctxName); + SSL_CTX* ctx = getCtx(ctxName); if (!ctx) - return NULL; + return shared_ptr(); - SSL* ssl = SSL_new(ctx); + SSL *p = newSSL(ctx); - SSL_set_mode(ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); // allow retry ssl-write with different args - SSL_set_bio(ssl, BIO_new(BIO_s_mem()), BIO_new(BIO_s_mem())); - - BIO_set_mem_eof_return(SSL_get_rbio(ssl), -1); - BIO_set_mem_eof_return(SSL_get_wbio(ssl), -1); - - return ssl; + return std::make_shared(p); } -// -//void GetMemData(BIO* bio, TC_NetWorkBuffer& buf) -//{ -// while (true) -// { -// char data[8*1024]; -// int bytes = BIO_read(bio, data, sizeof(data)); -// if (bytes <= 0) -// return; -// -// buf.addBuffer(data, bytes); -// } -//} -// -//void GetSSLHead(const char* data, char& type, unsigned short& ver, unsigned short& len) -//{ -// type = data[0]; -// ver = *(unsigned short*)(data + 1); -// len = *(unsigned short*)(data + 3); -// -// ver = ntohs(ver); -// len = ntohs(len); -//} -// -//bool DoSSLRead(SSL* ssl, std::string& out) -//{ -// while (true) -// { -// char plainBuf[32 * 1024]; -// -// ERR_clear_error(); -// int bytes = SSL_read(ssl, plainBuf, sizeof plainBuf); -// if (bytes > 0) -// { -// out.append(plainBuf, bytes); -// } -// else -// { -// int err = SSL_get_error(ssl, bytes); -// -// // when peer issued renegotiation, here will demand us to send handshake data. -// // write to mem bio will always success, only need to check whether has data to send. -// //assert (err != SSL_ERROR_WANT_WRITE); -// -// if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_ZERO_RETURN) -// { -// printf("DoSSLRead err %d\n", err); -// return false; -// } -// -// break; -// } -// } -// -// return true; -//} } // end namespace tars