main.cpp 15.4 KB
Newer Older
xiongziliang committed
1 2
/*
 * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
3
 *
4
 * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit).
5
 *
xiongziliang committed
6 7 8
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 */

#include <signal.h>
#include <iostream>
#include "Util/File.h"
#include "Util/logger.h"
#include "Util/SSLBox.h"
#include "Util/onceToken.h"
#include "Util/CMD.h"
#include "Network/TcpServer.h"
#include "Poller/EventPoller.h"
#include "Common/config.h"
#include "Rtsp/RtspSession.h"
#include "Rtmp/RtmpSession.h"
#include "Shell/ShellSession.h"
#include "Http/WebSocketSession.h"
25
#include "Rtp/RtpServer.h"
26
#include "WebApi.h"
27
#include "WebHook.h"
28 29 30 31 32

#if defined(ENABLE_WEBRTC)
#include "../webrtc/WebRtcTransport.h"
#include "../webrtc/WebRtcSession.h"
#endif
33

34 35 36 37
#if defined(ENABLE_VERSION)
#include "Version.h"
#endif

xiongziliang committed
38 39 40 41
#if !defined(_WIN32)
#include "System.h"
#endif//!defined(_WIN32)

42 43 44 45 46 47 48 49
using namespace std;
using namespace toolkit;
using namespace mediakit;

namespace mediakit {
////////////HTTP配置///////////
namespace Http {
#define HTTP_FIELD "http."
50 51
const string kPort = HTTP_FIELD"port";
const string kSSLPort = HTTP_FIELD"sslport";
52
onceToken token1([](){
53 54
    mINI::Instance()[kPort] = 80;
    mINI::Instance()[kSSLPort] = 443;
55 56 57 58 59 60
},nullptr);
}//namespace Http

////////////SHELL配置///////////
namespace Shell {
#define SHELL_FIELD "shell."
61
const string kPort = SHELL_FIELD"port";
62
onceToken token1([](){
63
    mINI::Instance()[kPort] = 9000;
64 65 66 67 68 69
},nullptr);
} //namespace Shell

////////////RTSP服务器配置///////////
namespace Rtsp {
#define RTSP_FIELD "rtsp."
70 71
const string kPort = RTSP_FIELD"port";
const string kSSLPort = RTSP_FIELD"sslport";
72
onceToken token1([](){
73 74
    mINI::Instance()[kPort] = 554;
    mINI::Instance()[kSSLPort] = 332;
75 76 77 78 79 80 81
},nullptr);

} //namespace Rtsp

////////////RTMP服务器配置///////////
namespace Rtmp {
#define RTMP_FIELD "rtmp."
82
const string kPort = RTMP_FIELD"port";
xiongziliang committed
83
const string kSSLPort = RTMP_FIELD"sslport";
84
onceToken token1([](){
85
    mINI::Instance()[kPort] = 1935;
xiongziliang committed
86
    mINI::Instance()[kSSLPort] = 19350;
87 88
},nullptr);
} //namespace RTMP
89 90 91 92 93 94 95 96 97 98

////////////Rtp代理相关配置///////////
namespace RtpProxy {
#define RTP_PROXY_FIELD "rtp_proxy."
const string kPort = RTP_PROXY_FIELD"port";
onceToken token1([](){
    mINI::Instance()[kPort] = 10000;
},nullptr);
} //namespace RtpProxy

99 100 101 102 103 104 105 106
}  // namespace mediakit


class CMD_main : public CMD {
public:
    CMD_main() {
        _parser.reset(new OptionParser(nullptr));

xiongziliang committed
107
#if !defined(_WIN32)
108 109 110 111 112 113 114
        (*_parser) << Option('d',/*该选项简称,如果是\x00则说明无简称*/
                             "daemon",/*该选项全称,每个选项必须有全称;不得为null或空字符串*/
                             Option::ArgNone,/*该选项后面必须跟值*/
                             nullptr,/*该选项默认值*/
                             false,/*该选项是否必须赋值,如果没有默认值且为ArgRequired时用户必须提供该参数否则将抛异常*/
                             "是否以Daemon方式启动",/*该选项说明文字*/
                             nullptr);
xiongziliang committed
115
#endif//!defined(_WIN32)
116 117 118 119 120 121 122 123 124

        (*_parser) << Option('l',/*该选项简称,如果是\x00则说明无简称*/
                             "level",/*该选项全称,每个选项必须有全称;不得为null或空字符串*/
                             Option::ArgRequired,/*该选项后面必须跟值*/
                             to_string(LTrace).data(),/*该选项默认值*/
                             false,/*该选项是否必须赋值,如果没有默认值且为ArgRequired时用户必须提供该参数否则将抛异常*/
                             "日志等级,LTrace~LError(0~4)",/*该选项说明文字*/
                             nullptr);

125 126 127 128 129
        (*_parser) << Option('m',/*该选项简称,如果是\x00则说明无简称*/
                             "max_day",/*该选项全称,每个选项必须有全称;不得为null或空字符串*/
                             Option::ArgRequired,/*该选项后面必须跟值*/
                             "7",/*该选项默认值*/
                             false,/*该选项是否必须赋值,如果没有默认值且为ArgRequired时用户必须提供该参数否则将抛异常*/
xiongziliang committed
130
                             "日志最多保存天数",/*该选项说明文字*/
131 132
                             nullptr);

133 134 135 136 137 138 139 140 141 142 143
        (*_parser) << Option('c',/*该选项简称,如果是\x00则说明无简称*/
                             "config",/*该选项全称,每个选项必须有全称;不得为null或空字符串*/
                             Option::ArgRequired,/*该选项后面必须跟值*/
                             (exeDir() + "config.ini").data(),/*该选项默认值*/
                             false,/*该选项是否必须赋值,如果没有默认值且为ArgRequired时用户必须提供该参数否则将抛异常*/
                             "配置文件路径",/*该选项说明文字*/
                             nullptr);

        (*_parser) << Option('s',/*该选项简称,如果是\x00则说明无简称*/
                             "ssl",/*该选项全称,每个选项必须有全称;不得为null或空字符串*/
                             Option::ArgRequired,/*该选项后面必须跟值*/
monktan committed
144
                             (exeDir() + "default.pem").data(),/*该选项默认值*/
145
                             false,/*该选项是否必须赋值,如果没有默认值且为ArgRequired时用户必须提供该参数否则将抛异常*/
146
                             "ssl证书文件或文件夹,支持p12/pem类型",/*该选项说明文字*/
147 148 149 150 151 152 153 154 155
                             nullptr);

        (*_parser) << Option('t',/*该选项简称,如果是\x00则说明无简称*/
                             "threads",/*该选项全称,每个选项必须有全称;不得为null或空字符串*/
                             Option::ArgRequired,/*该选项后面必须跟值*/
                             to_string(thread::hardware_concurrency()).data(),/*该选项默认值*/
                             false,/*该选项是否必须赋值,如果没有默认值且为ArgRequired时用户必须提供该参数否则将抛异常*/
                             "启动事件触发线程数",/*该选项说明文字*/
                             nullptr);
156 157 158 159 160

#if defined(ENABLE_VERSION)
        (*_parser) << Option('v', "version", Option::ArgNone, nullptr, false, "显示版本号",
                             [](const std::shared_ptr<ostream> &stream, const string &arg) -> bool {
                                 //版本信息
161 162 163
                                 *stream << "编译日期: " << BUILD_TIME << std::endl;
                                 *stream << "当前git分支: " << BRANCH_TIME << std::endl;
                                 *stream << "当前git hash值: " << COMMIT_HASH << std::endl;
164 165 166
                                 throw ExitException();
                             });
#endif
167 168
    }

169 170
    ~CMD_main() override{}
    const char *description() const override{
171 172 173 174
        return "主程序命令参数";
    }
};

xiongziliang committed
175
#if !defined(_WIN32)
176 177 178
static void inline listen_shell_input(){
    cout << "> 欢迎进入命令模式,你可以输入\"help\"命令获取帮助" << endl;
    cout << "> " << std::flush;
xiongziliang committed
179 180 181

    signal(SIGTTOU,SIG_IGN);
    signal(SIGTTIN,SIG_IGN);
xiongziliang committed
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    SockUtil::setNoBlocked(STDIN_FILENO);
    auto oninput = [](int event) {
        if (event & Event_Read) {
            char buf[1024];
            int n = read(STDIN_FILENO, buf, sizeof(buf));
            if (n > 0) {
                buf[n] = '\0';
                try {
                    CMDRegister::Instance()(buf);
                    cout << "> " << std::flush;
                } catch (ExitException &ex) {
                    InfoL << "ExitException";
                    kill(getpid(), SIGINT);
                } catch (std::exception &ex) {
                    cout << ex.what() << endl;
                }
            } else {
                DebugL << get_uv_errmsg();
                EventPollerPool::Instance().getFirstPoller()->delEvent(STDIN_FILENO);
            }
        }

        if (event & Event_Error) {
            WarnL << "Event_Error";
            EventPollerPool::Instance().getFirstPoller()->delEvent(STDIN_FILENO);
        }
    };
    EventPollerPool::Instance().getFirstPoller()->addEvent(STDIN_FILENO, Event_Read | Event_Error | Event_LT,oninput);
}
xiongziliang committed
212 213
#endif//!defined(_WIN32)

214 215
//全局变量,在WebApi中用于保存配置文件用
string g_ini_file;
216 217

int start_main(int argc,char *argv[]) {
xiongziliang committed
218 219 220 221
    {
        CMD_main cmd_main;
        try {
            cmd_main.operator()(argc, argv);
222
        } catch (ExitException &) {
223
            return 0;
xiongziliang committed
224 225 226 227
        } catch (std::exception &ex) {
            cout << ex.what() << endl;
            return -1;
        }
228

xiongziliang committed
229 230 231
        bool bDaemon = cmd_main.hasKey("daemon");
        LogLevel logLevel = (LogLevel) cmd_main["level"].as<int>();
        logLevel = MIN(MAX(logLevel, LTrace), LError);
232
        g_ini_file = cmd_main["config"];
xiongziliang committed
233 234
        string ssl_file = cmd_main["ssl"];
        int threads = cmd_main["threads"];
235

236 237
        setThreadName("main thread");

xiongziliang committed
238 239
        //设置日志
        Logger::Instance().add(std::make_shared<ConsoleChannel>("ConsoleChannel", logLevel));
240
#ifndef ANDROID
241 242 243 244
        auto fileChannel = std::make_shared<FileChannel>("FileChannel", exeDir() + "log/", logLevel);
        //日志最多保存天数
        fileChannel->setMaxDay(cmd_main["max_day"]);
        Logger::Instance().add(fileChannel);
245
#endif//
246

xiongziliang committed
247
#if !defined(_WIN32)
248
        pid_t pid = getpid();
xiongziliang committed
249 250 251 252
        if (bDaemon) {
            //启动守护进程
            System::startDaemon();
        }
xiongziliang committed
253 254
        //开启崩溃捕获等
        System::systemSetup();
xiongziliang committed
255
#endif//!defined(_WIN32)
xiongziliang committed
256

xiongziliang committed
257 258 259
        //启动异步日志线程
        Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
        //加载配置文件,如果配置文件不存在就创建一个
260
        loadIniConfig(g_ini_file.data());
xiongziliang committed
261

262
        if (!File::is_dir(ssl_file.data())) {
263 264
            //不是文件夹,加载证书,证书包含公钥和私钥
            SSL_Initor::Instance().loadCertificate(ssl_file.data());
265
        } else {
266
            //加载文件夹下的所有证书
267 268
            File::scanDir(ssl_file, [](const string &path, bool isDir) {
                if (!isDir) {
xiongziliang committed
269
                    //最后的一个证书会当做默认证书(客户端ssl握手时未指定主机)
270 271 272 273 274
                    SSL_Initor::Instance().loadCertificate(path.data());
                }
                return true;
            });
        }
xiongziliang committed
275 276 277 278 279

        uint16_t shellPort = mINI::Instance()[Shell::kPort];
        uint16_t rtspPort = mINI::Instance()[Rtsp::kPort];
        uint16_t rtspsPort = mINI::Instance()[Rtsp::kSSLPort];
        uint16_t rtmpPort = mINI::Instance()[Rtmp::kPort];
xiongziliang committed
280
        uint16_t rtmpsPort = mINI::Instance()[Rtmp::kSSLPort];
xiongziliang committed
281 282
        uint16_t httpPort = mINI::Instance()[Http::kPort];
        uint16_t httpsPort = mINI::Instance()[Http::kSSLPort];
xiongziliang committed
283
        uint16_t rtpPort = mINI::Instance()[RtpProxy::kPort];
xiongziliang committed
284

xiongziliang committed
285
        //设置poller线程数,该函数必须在使用ZLToolKit网络相关对象之前调用才能生效
xiongziliang committed
286 287 288 289
        EventPollerPool::setPoolSize(threads);

        //简单的telnet服务器,可用于服务器调试,但是不能使用23端口,否则telnet上了莫名其妙的现象
        //测试方法:telnet 127.0.0.1 9000
290
        TcpServer::Ptr shellSrv = std::make_shared<TcpServer>();
xiongziliang committed
291 292

        //rtsp[s]服务器, 可用于诸如亚马逊echo show这样的设备访问
293 294
        TcpServer::Ptr rtspSrv = std::make_shared<TcpServer>();;
        TcpServer::Ptr rtspSSLSrv = std::make_shared<TcpServer>();;
xiongziliang committed
295 296

        //rtmp[s]服务器
297 298
        TcpServer::Ptr rtmpSrv = std::make_shared<TcpServer>();;
        TcpServer::Ptr rtmpsSrv = std::make_shared<TcpServer>();;
xiongziliang committed
299 300

        //http[s]服务器
301 302
        TcpServer::Ptr httpSrv = std::make_shared<TcpServer>();;
        TcpServer::Ptr httpsSrv = std::make_shared<TcpServer>();;
303

304
#if defined(ENABLE_RTPPROXY)
xiongziliang committed
305
        //GB28181 rtp推流端口,支持UDP/TCP
306
        RtpServer::Ptr rtpServer = std::make_shared<RtpServer>();
307 308
#endif//defined(ENABLE_RTPPROXY)

309 310 311
#if defined(ENABLE_WEBRTC)
        //webrtc udp服务器
        UdpServer::Ptr rtcSrv = std::make_shared<UdpServer>();
312 313 314 315 316 317 318 319 320 321 322
        rtcSrv->setOnCreateSocket([](const EventPoller::Ptr &poller, const Buffer::Ptr &buf, struct sockaddr *, int) {
            if (!buf) {
                return Socket::createSocket(poller, false);
            }
            auto new_poller = WebRtcSession::getPoller(buf);
            if (!new_poller) {
                //该数据对应的webrtc对象未找到,丢弃之
                return Socket::Ptr();
            }
            return Socket::createSocket(new_poller, false);
        });
323 324 325
        uint16_t rtcPort = mINI::Instance()[RTC::kPort];
#endif//defined(ENABLE_WEBRTC)

326 327
        try {
            //rtsp服务器,端口默认554
328
            if (rtspPort) { rtspSrv->start<RtspSession>(rtspPort); }
329
            //rtsps服务器,端口默认322
330
            if (rtspsPort) { rtspSSLSrv->start<RtspSessionWithSSL>(rtspsPort); }
xiongziliang committed
331

332
            //rtmp服务器,端口默认1935
333
            if (rtmpPort) { rtmpSrv->start<RtmpSession>(rtmpPort); }
xiongziliang committed
334
            //rtmps服务器,端口默认19350
335
            if (rtmpsPort) { rtmpsSrv->start<RtmpSessionWithSSL>(rtmpsPort); }
xiongziliang committed
336

337
            //http服务器,端口默认80
338
            if (httpPort) { httpSrv->start<HttpSession>(httpPort); }
339
            //https服务器,端口默认443
340
            if (httpsPort) { httpsSrv->start<HttpsSession>(httpsPort); }
xiongziliang committed
341

342
            //telnet远程调试服务器
343
            if (shellPort) { shellSrv->start<ShellSession>(shellPort); }
344 345

#if defined(ENABLE_RTPPROXY)
346
            //创建rtp服务器
347
            if (rtpPort) { rtpServer->start(rtpPort); }
348 349
#endif//defined(ENABLE_RTPPROXY)

350 351 352 353 354 355
#if defined(ENABLE_WEBRTC)
            //webrtc udp服务器
            if (rtcPort) { rtcSrv->start<WebRtcSession>(rtcPort); }
#endif//defined(ENABLE_WEBRTC)

        } catch (std::exception &ex) {
356 357 358 359
            WarnL << "端口占用或无权限:" << ex.what() << endl;
            ErrorL << "程序启动失败,请修改配置文件中端口号后重试!" << endl;
            sleep(1);
#if !defined(_WIN32)
360 361
            if (pid != getpid()) {
                kill(pid, SIGINT);
362 363 364 365
            }
#endif
            return -1;
        }
xiongziliang committed
366 367 368 369 370 371

        installWebApi();
        InfoL << "已启动http api 接口";
        installWebHook();
        InfoL << "已启动http hook 接口";

372
#if !defined(_WIN32) && !defined(ANDROID)
xiongziliang committed
373 374 375 376
        if (!bDaemon) {
            //交互式shell输入
            listen_shell_input();
        }
xiongziliang committed
377
#endif
378

xiongziliang committed
379 380 381 382
        //设置退出信号处理函数
        static semaphore sem;
        signal(SIGINT, [](int) {
            InfoL << "SIGINT:exit";
383
            signal(SIGINT, SIG_IGN);// 设置退出信号
xiongziliang committed
384 385
            sem.post();
        });// 设置退出信号
xiongziliang committed
386 387

#if !defined(_WIN32)
388
        signal(SIGHUP, [](int) { mediakit::loadIniConfig(g_ini_file.data()); });
xiongziliang committed
389
#endif
xiongziliang committed
390 391
        sem.wait();
    }
392 393
    unInstallWebApi();
    unInstallWebHook();
xiongziliang committed
394
    //休眠1秒再退出,防止资源释放顺序错误
395
    InfoL << "程序退出中,请等待...";
xiongziliang committed
396
    sleep(1);
397
    InfoL << "程序退出完毕!";
398
    return 0;
399 400
}

401 402 403 404 405 406 407
#ifndef DISABLE_MAIN
int main(int argc,char *argv[]) {
    return start_main(argc,argv);
}
#endif //DISABLE_MAIN