File: logviewerservice.cpp

package info (click to toggle)
deepin-log-viewer 6.5.8%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 14,752 kB
  • sloc: cpp: 61,723; ansic: 1,732; xml: 81; sh: 59; makefile: 12
file content (1169 lines) | stat: -rw-r--r-- 36,729 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
// SPDX-FileCopyrightText: 2019 - 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "logviewerservice.h"
#include "qtcompat.h"

#include <pwd.h>
#include <unistd.h>
#include <fstream>

#include <dgiofile.h>
#include <dgiovolume.h>
#include <dgiovolumemanager.h>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include <polkit-qt5-1/PolkitQt1/Authority>
#else
#include <polkit-qt6-1/PolkitQt1/Authority>
#endif
using namespace PolkitQt1;

#include <QMutex>
#include <QUrl>
#include <QRegularExpression>
#include <QCoreApplication>
#include <QDebug>
#include <QStringList>
#include <QCryptographicHash>
#include <QTextStream>
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusConnectionInterface>
#include <QStandardPaths>
#include <QLoggingCategory>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTemporaryFile>

#ifdef QT_DEBUG
Q_LOGGING_CATEGORY(logService, "org.deepin.log.viewer.service")
#else
Q_LOGGING_CATEGORY(logService, "org.deepin.log.viewer.service", QtInfoMsg)
#endif

// 读取崩溃应用maps信息最大行数
#define COREDUMP_MAPS_MAX_LINES 200

const QString s_Action_View = "com.deepin.pkexec.logViewerAuth";
const QString s_Action_Export = "com.deepin.pkexec.logViewerAuth.exportLogs";

/**
   @brief 移除路径 \a dirPath 下的文件,注意,不会递归删除文件夹
 */
void removeDirFiles(const QString &dirPath)
{
    QDir dir(dirPath);
    dir.setFilter(QDir::NoDotAndDotDot | QDir::Files);
    foreach(QString dirItem, dir.entryList()) {
        if (!dir.remove(dirItem)) {
            qCWarning(logService) << QString("Remove temporary dir file [%1] failed").arg(dirItem);
        }
    }
}

/**
   @brief 将压缩源文件 \a sourceFile 解压到临时文件,临时文件由模板 \a tempFileTemplate 生成,
        若文件创建异常,将返回空路径;正常解压返回临时文件路径。
 */
QString unzipToTempFile(const QString &sourceFile, const QString &tempFileTemplate)
{
    QProcess m_process;

    // 每次创建临时文件,销毁由 QTemporaryDir 处理
    QTemporaryFile tmpFile;
    tmpFile.setAutoRemove(false);
    tmpFile.setFileTemplate(tempFileTemplate);
    tmpFile.open();
    if (!tmpFile.open()) {
        qCWarning(logService) << QString("Create temporary file [%1](FileTemplate:%2) failed: %3")
                                 .arg(tmpFile.fileName()).arg(tempFileTemplate).arg(tmpFile.errorString());
        return QString();
    }

    QString command = "gunzip";
    QStringList args;
    args.append("-c");
    args.append(sourceFile);
    m_process.setStandardOutputFile(tmpFile.fileName());
    m_process.start(command, args);
    m_process.waitForFinished(-1);

    return tmpFile.fileName();
}

LogViewerService::LogViewerService(QObject *parent)
    : QObject(parent)
{
    m_commands.insert("dmesg", "dmesg -r");
    m_commands.insert("last", "last -x");
    m_commands.insert("journalctl_system", "journalctl -r");
    m_commands.insert("journalctl_boot", "journalctl -b -r");
    m_commands.insert("journalctl_app", "journalctl");

    m_actionId = s_Action_View;
}

LogViewerService::~LogViewerService()
{
    if(!m_logMap.isEmpty()) {
        for(auto eachPair : m_logMap) {
            delete eachPair.second;
        }
    }

    clearTempFiles();
}

/*!
 * \~chinese \brief LogViewerService::readLog 读取日志文件
 * \~chinese \param fd 文件句柄
 * \~chinese \return 读取的日志
 */
QString LogViewerService::readLog(const QDBusUnixFileDescriptor &fd)
{
    if(!checkAuth(s_Action_View)) {
        return " ";
    }

    QString log("");
    // fd转文件
    int fdi = fd.fileDescriptor();
    if (fdi <= 0) {
        return log;
    }

    QFile file;
    if (!file.open(fdi, QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to open file path cache file descriptor.";
        return log;
    }

    QTextStream in(&file);
    QString targetFilePath = in.readAll();

    if (!targetFilePath.isEmpty())
        log = readLog(targetFilePath);
    else
        qWarning() << "target log file path is empty.";

    file.close();

    return log;
}

QByteArray LogViewerService::processCatFile(const QString &filePath)
{
    m_process.start("cat", QStringList() << filePath);
    m_process.waitForFinished(-1);
    QByteArray byte = m_process.readAllStandardOutput();
    return byte;
}

static QByteArray processCmdWithArgs(const QString &cmdStr, const QStringList &args)
{
    QProcess process;
    process.start(cmdStr, args);
    process.waitForFinished(-1);
    QByteArray outByte = process.readAllStandardOutput();
    return outByte;
}

/*!
 * \~chinese \brief LogViewerService::readLog 读取日志文件
 * \~chinese \param filePath 文件路径
 * \~chinese \return 读取的日志
 */
QString LogViewerService::readLog(const QString &filePath)
{
    if(!checkAuth(s_Action_View)) {
        return " ";
    }

    //增加服务黑名单,只允许通过提权接口读取/var/log下,家目录下和临时目录下的文件
    //部分设备是直接从root账户进入,因此还需要监控/root目录
    if ((!filePath.startsWith("/var/log/") &&
         !filePath.startsWith("/tmp") &&
         !filePath.startsWith("/home") &&
         !filePath.startsWith("/root")) ||
         filePath.contains(".."))  {
        return " ";
    }

    QByteArray byte = processCatFile(filePath);

    //QByteArray -> QString 如果遇到0x00,会导致转换终止
    //replace("\x00", "")和replace("\u0000", "")无效
    //使用remove操作,性能损耗过大,因此遇到0x00 替换为 0x20(空格符)
    int replaceTimes = 0;
    for (int i = 0; i != byte.size(); ++i) {
        if (byte.at(i) == 0x00) {
            byte[i] = 0x20;
            replaceTimes++;
        }
    }
    return QString::fromUtf8(byte);
}

qint64 LogViewerService::readFileAndReturnIndex(const QString &filePath, qint64 startLine, QList<uint64_t>& lineIndexes, bool reverseOrder) {
    std::ifstream file(filePath.toStdString());
    if (!file.is_open()) {
        // 文件不存在,返回错误
        return -1;
    }

    std::string line;
    uint64_t lineNumber = 0;
    uint64_t startIndex = 0;

    // TODO(pengfeixxx): If the index storage takes up too much memory, you can use differential
    // encoding to encode the array where the index is stored, and if it is still large,
    // you can continue to use Huffman encoding for the encoded array.
    if (lineIndexes.empty()) {
        // 从文件开头开始读取
        while (std::getline(file, line)) {
            lineNumber++;
            lineIndexes.push_back(startIndex);
            startIndex = file.tellg();
            if (lineNumber > startLine && !reverseOrder) {
                break;
            }
        }
    } else {
        if (startLine < lineIndexes.size() && !reverseOrder) {
            return lineIndexes[startLine];
        } else {
            file.seekg(lineIndexes.last());
            lineNumber = lineIndexes.size();
            while (std::getline(file, line)) {
                lineNumber++;
                startIndex = file.tellg();
                lineIndexes.push_back(startIndex);
                if (lineNumber > startLine && !reverseOrder) {
                    break;
                }
            }
            if (reverseOrder)
                lineIndexes.removeLast();
        }
    }

    file.close();

    if (reverseOrder) {
        startLine = lineIndexes.size() - startLine - 1;
        if (startLine < 0)
            return -1;
        else
            return lineIndexes.at(startLine);
    }

    return lineIndexes.at(startLine); // 返回给定起始行的索引
}

/**
   @brief Polkit action authorization check.
        Use com.deepin.pkexec.logViewerAuth.policy config file.
        Default action id: "com.deepin.pkexec.logViewerAuth"
   @note Available on linux/unix/macos platform.
   @return check passed.
 */
bool LogViewerService::checkAuthorization(const QString &actionId, qint64 applicationPid)
{
#if defined (Q_OS_LINUX) || defined (Q_OS_UNIX) ||  defined (Q_OS_MAC)
            PolkitQt1::Authority::Result ret = PolkitQt1::Authority::instance()->checkAuthorizationSync(
                actionId, PolkitQt1::UnixProcessSubject(applicationPid), PolkitQt1::Authority::AllowUserInteraction);
    if (PolkitQt1::Authority::Yes == ret) {
        return true;
    } else {
        qWarning() << qPrintable("Policy authorization check failed!");
        return false;
    }
#else
    return true;
#endif
}

/*!
 * \~chinese \brief LogViewerService::readLogLinesInRange 分段读取日志文件
 * \~chinese \param fd 文件句柄
 * \~chinese \return 读取的日志
 */
QStringList LogViewerService::readLogLinesInRange(const QDBusUnixFileDescriptor &fd, qint64 startLine, qint64 lineCount, bool bReverse)
{
    if(!checkAuth(s_Action_View)) {
        return QStringList();
    }

    QStringList lines;
    // fd转文件
    int fdi = fd.fileDescriptor();
    if (fdi <= 0) {
        return lines;
    }

    QFile file;
    if (!file.open(fdi, QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to open file path cache file descriptor.";
        return lines;
    }

    QTextStream in(&file);
    QString targetFilePath = in.readAll();

    if (!targetFilePath.isEmpty())
        lines = readLogLinesInRange(targetFilePath, startLine, lineCount, bReverse);
    else
        qWarning() << "target log file path is empty.";

    file.close();

    return lines;
}

QStringList LogViewerService::readLogLinesInRange(const QString &filePath, qint64 startLine, qint64 lineCount, bool bReverse)
{
    QStringList lines;

    // 开启鉴权
    if (!checkAuth(s_Action_View))
        return lines;

    //增加服务黑名单,只允许通过提权接口读取/var/log下,家目录下和临时目录下的文件
    //部分设备是直接从root账户进入,因此还需要监控/root目录
    if ((!filePath.startsWith("/var/log/") &&
         !filePath.startsWith("/tmp") &&
         !filePath.startsWith("/home") &&
         !filePath.startsWith("/root")) ||
         filePath.contains("..")) {
        return lines;
    }

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        QString token = QCryptographicHash::hash(filePath.toUtf8(), QCryptographicHash::Md5).toHex();
        if (m_logLineIndex.contains(token))
            m_logLineIndex.remove(token);
        return lines;
    }

    qint64 startLineIndex = 0;
    QString token = QCryptographicHash::hash(filePath.toUtf8(), QCryptographicHash::Md5).toHex();
    if (m_logLineIndex.contains(token)) {
        startLineIndex = readFileAndReturnIndex(filePath, startLine, m_logLineIndex[token], bReverse);
    } else {
        QList<uint64_t> indexList;
        startLineIndex = readFileAndReturnIndex(filePath, startLine, indexList, bReverse);
        m_logLineIndex.insert(token, indexList);
    }

    if (bReverse) {
        int startLineCount = m_logLineIndex[token].size() - lineCount;
        startLineIndex = startLineCount > 0 ? startLineCount : 0;
    }

    if (startLineIndex < 0)
        return lines;

    if (!file.seek(m_logLineIndex[token].at(startLineIndex))) {
        file.close();
        return lines;
    }

    QTextStream in(&file);
    while (!in.atEnd() && lines.size() < lineCount) {
        QString line = in.readLine();
        if (line.contains('\x00'))
            lines.append(line.replace(QChar('\x00'), ""));
        else
            lines.append(line);
    }

    file.close();

    return lines;
}

qint64 LogViewerService::findLineStartOffsetWithCaching(const QString &filePath, qint64 targetLine) {

    const int blockSize = 4096; // 设置块大小,可以根据实际情况调整
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        return -1; // 无法打开文件
    }

    QByteArray block;
    qint64 offset = 0;
    qint64 currentLine = 0;
    char *blockData = nullptr;
    int blockPosition = 0;
    int lineLength = 0;

    while (currentLine <= targetLine) {
        block = file.read(blockSize);
        if (block.isEmpty()) {
            break; // 到达文件末尾
        }

        blockData = block.data();
        blockPosition = 0;
        while (blockPosition < block.size()) {
            char c = blockData[blockPosition++];
            lineLength++;
            if (c == '\n') { // 检测到换行符,增加行数
                if (currentLine == targetLine) {
                    // 如果找到目标行,返回当前偏移量减去换行符的字节数
                    return offset + blockPosition - lineLength;
                }
                currentLine++;
                lineLength = 0;
            }
        }

        offset += block.size(); // 更新总偏移量
    }

    // 处理目标行为文本最后一行的情况
    if (currentLine >= targetLine) {
        if (offset > 0 && lineLength > 0)
            return offset - lineLength;
    }

    file.close();

    return -1; // 没有找到目标行
}

qint64 LogViewerService::getLineCount(const QString &filePath)
{
    if (!isValidInvoker())
        return -1;

    //增加服务黑名单,只允许通过提权接口读取/var/log下,家目录下和临时目录下的文件
    //部分设备是直接从root账户进入,因此还需要监控/root目录
    if ((!filePath.startsWith("/var/log/") &&
         !filePath.startsWith("/tmp") &&
         !filePath.startsWith("/home") &&
         !filePath.startsWith("/root")) ||
            filePath.contains("..")) {
        return -1;
    }

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        // 文件打开失败处理
        return -1;
    }

    qint64 lineCount = -1;
    QString result = processCmdWithArgs("wc", QStringList() << "-l" << filePath);
    QStringList splitResult = result.split(' ');
    if (splitResult.size() > 0)
        lineCount = splitResult.first().toLongLong();

    return lineCount;
}

void LogViewerService::processCmdArgs(const QString &cmdStr, const QStringList &args)
{
    m_process.start(cmdStr, args);
}

QString LogViewerService::executeCmd(const QString &cmd)
{
    QString result("");

    if (!isValidInvoker())
        return result;

    QString cmdStr;
    QStringList args;
    if (cmd.startsWith("coredumpctl-list")) {
        // 通过后端服务,读取系统下所有账户的崩溃日志信息
        cmdStr = "coredumpctl";
        args << "list" << "--no-pager";
    } else if (cmd.startsWith("coredumpctl info")) {
        // 通过后端服务,按进程号获取崩溃信息
        cmdStr = "coredumpctl";
        args = cmd.mid(QString("coredumpctl").size() + 1).split(' ');
    } else if (cmd.startsWith("coredumpctl dump")) {
        // 截取对应pid的dump文件到指定目录
        cmdStr = "coredumpctl";
        args = cmd.mid(QString("coredumpctl").size() + 1).split(' ');
    } else if (cmd.startsWith("readelf")) {
        // 获取dump文件偏移地址信息
        cmdStr = "readelf";
        args = cmd.mid(QString("readelf").size() + 1).split(' ');
    }

    if (!cmdStr.isEmpty()) {
        processCmdArgs(cmdStr, args);

        if (!m_process.waitForFinished(-1)) {
            qCWarning(logService()) << "invalid command:" << QString("%1 %2").arg(cmdStr).arg(args.join(' '));
            return "";
        }

        if (cmd == "coredumpctl-list-count") {
            result = m_process.readAllStandardOutput();
            QStringList rows = result.split('\n');
            int nCnt = rows.size();
            // 去掉表头和表尾行
            if (nCnt > 2)
                nCnt -= 2;
            else
                nCnt = 0;
            result = QString::number(nCnt);
        } else if (cmd.startsWith("readelf")) {
            // 因原始maps信息过大,基本几百KB,埋点平台并不需要全量数据,仅取前200行maps信息即可
            QTextStream in(m_process.readAllStandardOutput());
            QStringList lines;
            QString str;
            while (!in.atEnd()) {
                str  = in.readLine();

                if (!str.isEmpty())
                    lines.push_back(str);
                if (lines.count() >= COREDUMP_MAPS_MAX_LINES)
                    break;
            }

            result = lines.join('\n').toUtf8();
        } else {
            result = m_process.readAllStandardOutput();
        }
    }

    return result;
}

/*!
 * \~chinese \brief LogViewerService::openLogStream 打开一个日志文件的流式读取通道
 * \~chinese \param filePath 文件路径
 * \~chinese \return 通道token,返回空时表示文件路径无效
 */
QString LogViewerService::openLogStream(const QString &filePath)
{
    QString result = readLog(filePath);
    if(result == " ") {
        return "";
    }

    QString token = QCryptographicHash::hash(filePath.toUtf8(), QCryptographicHash::Md5).toHex();

    auto stream = new QTextStream;

    m_logMap[token] = std::make_pair(result, stream);
    stream->setString(&(m_logMap[token].first), QIODevice::ReadOnly);

    return token;
}

/*!
 * \~chinese \brief LogViewerService::readLogInStream 从刚刚打开的传输通道中读取日志数据
 * \~chinese \param token 通道token
 * \~chinese \return 读取的日志,返回为空的时候表示读取结束或token无效
 */
QString LogViewerService::readLogInStream(const QString &token)
{
    if(!m_logMap.contains(token)) {
        return "";
    }

    auto stream = m_logMap[token].second;

    QString result;
    constexpr int maxReadSize = 10 * 1024 * 1024;
    while (1) {
        auto data = stream->readLine();
        if(data.isEmpty()) {
            break;
        }

        result += data + '\n';

        if(result.size() > maxReadSize) {
            break;
        }
    }

    if(result.isEmpty()) {
        delete m_logMap[token].second;
        m_logMap.remove(token);
    }

    return result;
}

QString LogViewerService::isFileExist(const QString &filePath)
{
    if (!checkAuth(s_Action_View))
        return QString("");

    if (QFile::exists(filePath))
        return QString("exist");

    return QString("");
}

quint64 LogViewerService::getFileSize(const QString &filePath)
{
    QFileInfo fi(filePath);
    if (fi.exists())
        return static_cast<quint64>(fi.size());

    return 0;
}

// 获取白名单导出路径
QStringList LogViewerService::whiteListOutPaths()
{
    QStringList paths;
    // 获取用户家目录
    QStringList homeList = getHomePaths();
    if (!homeList.isEmpty())
        paths << homeList;
    // 获取外设挂载可写路径(包括smb路径)
    paths << getExternalDevPaths();
    // 获取临时目录
    paths.push_back("/tmp");
    return paths;
}

// 获取用户家目录
QStringList LogViewerService::getHomePaths()
{
    QStringList homeList;

    if (!calledFromDBus()) {
        return homeList;
    }

    QFileInfoList infoList = QDir("/home").entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    for (auto info : infoList) {
        if (info.isDir())
            homeList.push_back(info.absoluteFilePath());
    }

    return homeList;
}

// 获取外设挂载路径
QStringList LogViewerService::getExternalDevPaths()
{
    QStringList devPaths;
    const QList<QExplicitlySharedDataPointer<DGioMount> > mounts = getMounts_safe();
    for (auto mount : mounts) {
        QString uri = mount->getRootFile()->uri();
        QString scheme = QUrl(uri).scheme();

        // sbm路径判断,分为gvfs挂载和cifs挂载两种
        QRegularExpression recifs("^file:///media/(.*)/smbmounts");
        QRegularExpression regvfs("^file:///run/user/(.*)/gvfs|^/root/.gvfs");
        if (recifs.match(uri).hasMatch() || regvfs.match(uri).hasMatch()) {
            QString path = QUrl(uri).toLocalFile();
            QFlags <QFileDevice::Permission> power = QFile::permissions(path);
            if (power.testFlag(QFile::WriteUser))
                devPaths.push_back(path);
        }

        // 外设路径判断
        if ((scheme == "file") ||  //usb device
                (scheme == "gphoto2") ||        //phone photo
                (scheme == "mtp")) {            //android file
            QExplicitlySharedDataPointer<DGioFile> locationFile = mount->getDefaultLocationFile();
            QString path = locationFile->path();
            if (path.startsWith("/media/")) {
                QFlags <QFileDevice::Permission> power = QFile::permissions(path);
                if (power.testFlag(QFile::WriteUser)) {
                    devPaths.push_back(path);
                }
            }
        }
    }

    return devPaths;
}

//可重入版本的getMounts
QList<QExplicitlySharedDataPointer<DGioMount> > LogViewerService::getMounts_safe()
{
    static QMutex mutex;
    mutex.lock();
    auto result = DGioVolumeManager::getMounts();
    mutex.unlock();
    return result;
}

void LogViewerService::clearTempFiles()
{
    // 清除/tmp目录下lz4.dump文件
    QDir dirTemp(QDir::tempPath());
    dirTemp.setFilter(QDir::Files);
    dirTemp.setNameFilters(QStringList() << "*.lz4.dump");
    QFileInfoList fiList = dirTemp.entryInfoList();
    for (auto fi : fiList) {
        QFile::remove(fi.absoluteFilePath());
    }
}

/*!
 * \~chinese \brief LogViewerService::exitCode 返回进程状态
 * \~chinese \return 进程返回值
 */
int LogViewerService::exitCode()
{
    return m_process.exitCode();
}

/*!
 * \~chinese \brief LogViewerService::quit 退出服务端程序
 */
void LogViewerService::quit()
{
    qCDebug(logService) << "LogViewService::Quit called";
    QCoreApplication::exit(0);
}

/*!
 * \~chinese \brief LogViewerService::getFileInfo 获取想到读取日志文件的路径
 * \~chinese \param file 日志文件的类型
 * \~chinese \return 所有日志文件路径列表
 */
QStringList LogViewerService::getFileInfo(const QString &file, bool unzip)
{
    // 判断非法调用
    if(!isValidInvoker()) {
        return {};
    }

    if (tmpDir.isValid()) {
        m_tmpDirPath = tmpDir.path();
        // 每次解压前移除旧有的文件
        if (unzip) {
            removeDirFiles(m_tmpDirPath);
        }
    }

    QStringList fileNamePath;
    QString nameFilter;
    QDir dir;
    if (file.contains("deepin", Qt::CaseInsensitive) || file.contains("uos", Qt::CaseInsensitive)) {
        QFileInfo appFileInfo(file);
        QString appDir;
        if (appFileInfo.isFile()) {
            appDir = appFileInfo.absolutePath();
        } else if (appFileInfo.isDir()) {
            appDir = appFileInfo.absoluteFilePath();
        } else {
            return QStringList();
        }

        nameFilter = appDir.mid(appDir.lastIndexOf("/") + 1, appDir.size() - 1);
        dir.setPath(appDir);
        dir.setFilter(QDir::Files | QDir::NoSymLinks); //实现对文件的过滤
        dir.setNameFilters(QStringList() << nameFilter + ".*"); //设置过滤
        dir.setSorting(QDir::Time);

        // 若该路径下未找到日志,则按日志文件名称来检索相关日志文件
        QFileInfoList fileList = dir.entryInfoList();
        if (fileList.size() == 0)
            nameFilter = appFileInfo.completeBaseName();
    } else if (file == "audit"){
        dir.setPath("/var/log/audit");
        nameFilter = file;
    } else if (file == "coredump") {
        QByteArray outByte = processCmdWithArgs("coredumpctl", QStringList() << "list");
        QStringList strList = QString(outByte.replace('\u0000', "").replace("\x01", "")).split('\n', SKIP_EMPTY_PARTS);

        REG_EXP re("(Storage: )\\S+");
        for (int i = strList.size() - 1; i >= 0; --i) {
            QString str = strList.at(i);
            if (str.trimmed().isEmpty())
                continue;

            QStringList tmpList = str.split(" ", SKIP_EMPTY_PARTS);
            if (tmpList.count() < 10)
                continue;

            QString coreFile = tmpList[8];
            QString pid = tmpList[4];
            QString storagePath = "";
            // 解析coredump文件保存位置
            if (coreFile != "missing") {
                QByteArray outInfoByte = processCmdWithArgs("coredumpctl", QStringList() << "info" << pid);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
                re.indexIn(outInfoByte);
                storagePath = re.cap(0).replace("Storage: ", "");
#else
                QRegularExpressionMatch match = re.match(outInfoByte);
                if (match.hasMatch()) {
                    storagePath = match.captured(0).replace("Storage: ", "");
                }
#endif
            }

            if (!storagePath.isEmpty()) {
                fileNamePath.append(storagePath);
            }
        }

        return fileNamePath;
    } else {
        dir.setPath("/var/log");
        nameFilter = file;
    }
    //要判断路径是否存在
    if (!dir.exists()) {
        qCWarning(logService) << "it is not true path";
        return QStringList() << "";
    }

    dir.setFilter(QDir::Files | QDir::NoSymLinks); //实现对文件的过滤
    dir.setNameFilters(QStringList() << nameFilter + ".*"); //设置过滤
    dir.setSorting(QDir::Time);
    QFileInfoList fileList = dir.entryInfoList();
    QString tempFileTemplate = m_tmpDirPath + QDir::separator() + "Log_extract_XXXXXX.txt";

    for (int i = 0; i < fileList.count(); i++) {
        if (QString::compare(fileList[i].suffix(), "gz", Qt::CaseInsensitive) == 0 && unzip) {
            QString unzipFile = unzipToTempFile(fileList[i].absoluteFilePath(), tempFileTemplate);
            if (!unzipFile.isEmpty()) {
                fileNamePath.append(unzipFile);
            }
        }
        else {
            fileNamePath.append(fileList[i].absoluteFilePath());
        }
    }
    return fileNamePath;
}

/*!
 * \~chinese \brief LogViewerService::getOtherFileInfo 获取其他日志文件的路径
 * \~chinese \param file 日志文件的类型
 * \~chinese \return 所有日志文件路径列表
 */
QStringList LogViewerService::getOtherFileInfo(const QString &file, bool unzip)
{
    // 判断非法调用
    if(!isValidInvoker()) {
        return {};
    }

    if (tmpDir.isValid()) {
        m_tmpDirPath = tmpDir.path();
        // 每次解压前移除旧有的文件
        if (unzip) {
            removeDirFiles(m_tmpDirPath);
        }
    }

    QStringList fileNamePath;
    QString nameFilter;
    QDir dir;
    QFileInfo appFileInfo(file);
    QFileInfoList fileList;
    //判断路径是否存在
    if (!appFileInfo.exists()) {
        qCWarning(logService) << QString("path:[%1] it is not true path").arg(file);
        return QStringList();
    }
    //如果是文件
    if (appFileInfo.isFile()) {
        QString appDir = appFileInfo.absolutePath();
        nameFilter = appFileInfo.fileName();
        dir.setPath(appDir);
        dir.setNameFilters(QStringList() << nameFilter + "*"); //设置过滤
    } else if (appFileInfo.isDir()) {
        //如果是目录
        dir.setPath(file);
    }

    dir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::Hidden); //实现对文件的过滤
    dir.setSorting(QDir::Time);
    fileList = dir.entryInfoList();
    QString tempFileTemplate = m_tmpDirPath + QDir::separator() + "Log_extract_XXXXXX.txt";

    for (int i = 0; i < fileList.count(); i++) {
        if (QString::compare(fileList[i].suffix(), "gz", Qt::CaseInsensitive) == 0 && unzip) {
            QString unzipFile = unzipToTempFile(fileList[i].absoluteFilePath(), tempFileTemplate);
            if (!unzipFile.isEmpty()) {
                fileNamePath.append(unzipFile);
            }
        }
        else {
            fileNamePath.append(fileList[i].absoluteFilePath());
        }
    }
    return fileNamePath;
}

static bool processExportLog(const QString &cmdStr, const QString &outFullPath,const QStringList &args)
{
    QProcess process;
    if (cmdStr != "cp") {
        process.setStandardOutputFile(outFullPath, QIODevice::WriteOnly);
    }

    process.start(cmdStr, args);
    if (!process.waitForFinished(-1)) {
        return false;
    }
    return true;
}

bool LogViewerService::exportLog(const QString &outDir, const QString &in, bool isFile)
{
    if(!checkAuth(s_Action_Export)) { //非法调用
        return false;
    }

    QFileInfo outDirInfo;
    if(!outDir.endsWith("/")) {
        outDirInfo.setFile(outDir + "/");
    } else {
        outDirInfo.setFile(outDir);
    }

    if (!outDirInfo.isDir() || in.isEmpty()) {
        return false;
    }

    // 导出路径白名单检查
    QString outPath = outDirInfo.absoluteFilePath();
    QStringList availablePaths = whiteListOutPaths();
    bool bAvailable = false;
    for (auto path : availablePaths) {
        if (outPath.startsWith(path)) {
            bAvailable = true;
            break;
        }
    }
    if (!bAvailable) {
        return false;
    }

    QString outFullPath = "";
    QString cmdExec = "";
    if (isFile) {
        //增加服务黑名单,只允许通过提权接口读取/var/log、/var/lib/systemd/coredump下,家目录下和临时目录下的文件
        if ((!in.startsWith("/var/log/") && !in.startsWith("/tmp") && !in.startsWith("/home") && !in.startsWith("/var/lib/systemd/coredump"))
                || in.contains("..")) {
            return false;
        }
        QFileInfo filein(in);
        if (!filein.isFile()) {
            qCWarning(logService) << "in not file:" << in;
            return false;
        }

        outFullPath = outDirInfo.absoluteFilePath() + filein.fileName();
        //复制文件
        cmdExec = QString("cp %1 %2").arg(in, outDirInfo.absoluteFilePath());
    } else {
        QString cmd;

        // 判断输入是否为json字串
        QJsonParseError parseError;
        QJsonDocument document = QJsonDocument::fromJson(in.toUtf8(), &parseError);
        if (parseError.error == QJsonParseError::NoError) {
            if (document.isObject()) {
                QJsonObject object = document.object();

                QString submoduleName;
                QString filter;
                QString execPath;

                if (object.contains("name"))
                    submoduleName = object.value("name").toString();
                if (object.contains("filter"))
                    filter = object.value("filter").toString();
                if (object.contains("execPath"))
                    execPath = object.value("execPath").toString();

                QString condition;
                if (!execPath.isEmpty())
                    condition += QString(" _EXE=%1").arg(execPath);
                if (!filter.isEmpty())
                    condition += QString(" CODE_CATEGORY=%1").arg(filter);
                if (execPath.isEmpty() && filter.isEmpty())
                    condition += QString(" SYSLOG_IDENTIFIER=%1").arg(submoduleName);

                if (!condition.isEmpty()) {
                    cmd = "journalctl" + condition;
                    cmd += " -r";
                    outFullPath = outDirInfo.absoluteFilePath() + submoduleName + ".log";
                }
            }
        }

        // 判断输入是否为cmd命令
        if (cmd.isEmpty()) {
            auto it = m_commands.find(in);
            if (it != m_commands.end()) {
                cmd = it.value();
                outFullPath = outDirInfo.absoluteFilePath() + in + ".log";
            }
        }

        // 未解析出有效命令,返回
        if (cmd.isEmpty()) {
            qCWarning(logService) << "unknown command:" << in;
            return false;
        }

        cmdExec = cmd;
    }

    QString cmdStr = cmdExec.mid(0, cmdExec.indexOf(' '));
    QStringList args;
    args << cmdExec.mid(cmdExec.indexOf(' ') + 1).split(' ');

    if (cmdStr != "cp") {
        if (!QFile::exists(outFullPath)) {
            qInfo() << "outFullPath:" << outFullPath << "not exist;";
            QFile file(outFullPath);
        }
    }

    if (!processExportLog(cmdStr,outFullPath, args)) {
        qCWarning(logService) << "command error:" << cmdExec;
        return false;
    }

    //设置文件权限
    QProcess newProcess;
    newProcess.start("chmod", QStringList() << "777" << outFullPath);
    if (!newProcess.waitForFinished()) {
        qCWarning(logService) << QString("chmod 777 %1 failed.").arg(outFullPath);
        return false;
    }
    return true;
}

bool LogViewerService::isValidInvoker(bool checkAuth/* = true*/)
{
   if (!calledFromDBus()) {
       return false;
   }

    bool valid = false;
    QDBusConnection conn = connection();
    QDBusMessage msg = message();

    //判断是否存在执行路径
    uint pid = conn.interface()->servicePid(msg.service()).value();

    // 判断是否存在执行路径且是否存在于可调用者名单中
    QFile initNsMntFile("/proc/1/ns/mnt");
    QFile senderNsMntFile(QString("/proc/%1/ns/mnt").arg(pid));
    auto initNsMnt = initNsMntFile.symLinkTarget().trimmed().remove(0, QString("/proc/1/ns/mnt").length());
    auto senderNsMnt = senderNsMntFile.symLinkTarget().trimmed().remove(0, QString("/proc/%1/ns/mnt").arg(pid).length());
    if (initNsMnt != senderNsMnt) {
        sendErrorReply(QDBusError::ErrorType::Failed, "Illegal calls!!!!!");
        return false;
    }

    //进制使用环境变量导入.so动态调用dbus接口
    QProcess proc;
    proc.start(QString("cat /proc/%1/maps").arg(pid));
    proc.waitForStarted();
    proc.waitForFinished();
    QString maps = QString::fromLocal8Bit(proc.readAllStandardOutput()).trimmed();
    proc.close();
    QStringList libMaps = maps.split("\n", SKIP_EMPTY_PARTS);
    QStringList allParts;
    for (const QString &part : libMaps) {
        QStringList subParts = part.split(' ');
        for (const QString &subPart : subParts) {
            if (!subPart.isEmpty()) {
                allParts.append(subPart);
            }
        }
    }
    for (int j = 0; j < allParts.count(); ++j) {
        QString libStr = allParts.at(j);
        QFileInfo info(libStr);
        if (info.isFile()) {
            QString fileName = info.fileName();
            if (fileName.contains(".so")) {
                QStringList libpath = libStr.split("/", SKIP_EMPTY_PARTS);
                if (libpath.count() > 2) {
                    QString libhead = QString("/%1/%2").arg(libpath.at(0)).arg(libpath.at(1));
                    if (libhead != "/usr/lib") {
                        sendErrorReply(QDBusError::ErrorType::Failed, "Illegal calls!");
                        return false;
                    }
                }
            }
        }
    }

    QFileInfo f(QString("/proc/%1/exe").arg(pid));
    if (!f.exists()) {
        valid = false;
    } else {
        valid = true;
    }

    //是否存在于可调用者名单中
    QStringList ValidInvokerExePathList;
    QString invokerPath = f.canonicalFilePath();
    QStringList findPaths;//合法调用者查找目录列表
    findPaths << "/usr/bin";
    ValidInvokerExePathList << QStandardPaths::findExecutable("deepin-log-viewer", findPaths);

    if (valid)
        valid = ValidInvokerExePathList.contains(invokerPath);

    // pokit前端进程鉴权
    bool bAuthValid = true;
    QString strCheckAuthTip;
    if (valid && checkAuth) {
        bAuthValid = checkAuthorization(m_actionId, pid);
        valid = bAuthValid;
        if (!bAuthValid) {
            strCheckAuthTip = "checkAuthorization failed.";
            qWarning() << strCheckAuthTip;
        }
    }
    //非法调用
    if (!valid) {
        sendErrorReply(QDBusError::ErrorType::Failed,
                       QString("(pid: %1)[%2] is not allowed to configrate firewall. %3")
                       .arg(pid)
                       .arg((invokerPath))
                       .arg(strCheckAuthTip));
        return false;
    }
    return true;
}

bool LogViewerService::checkAuth(const QString &actionId)
{
    if (!calledFromDBus()) {
        qWarning() << "called not from dbus.";
        return false;
    }

    bool isRoot = connection().interface()->serviceUid(message().service()).value() == 0;
    if (isRoot) {
        qInfo() << "dbus caller is root progress.";
        return  true;
    }

    uint pid = connection().interface()->servicePid(message().service()).value();

    bool bAuthVaild = false;
    bAuthVaild = checkAuthorization(actionId, pid);
    if (!bAuthVaild) {
        qWarning() << "checkAuthorization failed.";
        sendErrorReply(QDBusError::ErrorType::Failed,
                       QString("(pid: %1) is not allowed to configrate firewall. %3")
                       .arg(pid)
                       .arg("checkAuthorization failed."));
    }

    return  bAuthVaild;
}