Skip to content

fix: submit journal fields via iovec to avoid printf parsing - #303

Merged
deepin-bot[bot] merged 1 commit into
linuxdeepin:develop/snipefrom
Johnson-zs:develop/snipe
Nov 30, 2026
Merged

deepin-bot[bot] merged 1 commit into
linuxdeepin:develop/snipefrom
Johnson-zs:develop/snipe

Conversation

@Johnson-zs

@Johnson-zs Johnson-zs commented Nov 30, 2026 •

Copy link
Copy Markdown
  1. Root cause: the previous fix escaped '%' in the message before it
    reached sd_journal_send_with_location, whose 4th parameter is a
    printf-style format string. Escaping is a per-character workaround:
    the handler still routes log text through printf parsing, so any
    future field added to the same call can reintroduce the same
    out-of-bounds read. The handler was also a static function inside
    main.cpp, which made it unreachable from the unit test suite - the
    reason this crash class went unnoticed despite 1100+ tests
  2. Fix: move the handler into utils/journallogger.{h,cpp} and submit
    through sd_journal_sendv_with_location, which takes explicit
    (pointer, length) pairs and never parses the text. Message bytes are
    carried verbatim, embedded NULs are no longer truncated, and the
    CODE_FUNC field passes the bare function name instead of the
    previously duplicated "CODE_FUNC=CODE_FUNC=..." prefix
  3. Impact: journal output is unchanged for existing messages; the
    '%' escaping is no longer needed and is removed. Adds
    autotests/index/test_journallogger.cpp (8 cases) covering
    URL-encoded paths, printf conversion payloads and field formatting

fix: 日志字段改用 iovec 提交,避免 printf 解析

  1. 根因:此前的修复在消息进入 sd_journal_send_with_location 之前把
    '%' 转义,而该函数第 4 参数是 printf 格式串。转义是逐字符修补:
    handler 仍把日志正文交给 printf 解析,后续往同一调用里新增字段
    就会重新引入同一个越界读取。此外该 handler 原是 main.cpp 内的
    static 函数,单测无法触及——这是此类崩溃在 1100+ 用例下仍未被
    发现的原因
  2. 方案:将 handler 移入 utils/journallogger.{h,cpp},改用
    sd_journal_sendv_with_location 提交。该接口接收显式的
    (指针, 长度) 对,完全不做格式解析:消息字节逐字保真,内嵌 NUL
    不再被截断,同时修正 CODE_FUNC 字段此前重复的
    "CODE_FUNC=CODE_FUNC=..." 前缀
  3. 影响:既有消息的 journal 输出不变;不再需要 '%' 转义,已移除。
    新增 autotests/index/test_journallogger.cpp(8 个用例),覆盖
    URL 编码路径、printf 转换符载荷与字段格式

Log: Fixed deepin-anything-index crash caused by format-string parsing of log text
Influence:

  • Test indexing files with URL-encoded names containing % characters
  • Test paths containing bare %d/%s/%n sequences no longer crash the service
  • Verify journal entries keep the original message text and correct CODE_FUNC
  • Verify normal file indexing and journal logging show no regression
    Log: 修复 deepin-anything-index 因日志正文被当作格式串解析导致的崩溃
    Influence:
  • 测试索引含 URL 编码百分号字符的文件名
  • 测试含裸 %d/%s/%n 序列的路径不再使服务崩溃
  • 验证 journal 中消息正文保持原样、CODE_FUNC 字段正确
  • 验证普通文件索引和日志记录无回归
    PMS: BUG-384803

Summary by Sourcery

Submit journal fields as explicit byte ranges to eliminate format-string parsing from index logging.

Bug Fixes:

  • Prevent deepin-anything-index crashes when journal messages contain percent sequences or other printf-like payloads.
  • Preserve journal message contents, including embedded NUL bytes, and correct the CODE_FUNC field.

Enhancements:

  • Extract journal logging into a reusable, testable utility and submit structured fields without format-string interpretation.

Build:

  • Add libsystemd as a dependency for the index test target.

Tests:

  • Add regression coverage for percent-containing messages, printf conversion payloads, embedded NULs, journal fields, and end-to-end submission.

1. Root cause: the previous fix escaped '%' in the message before it
   reached sd_journal_send_with_location, whose 4th parameter is a
   printf-style format string. Escaping is a per-character workaround:
   the handler still routes log text through printf parsing, so any
   future field added to the same call can reintroduce the same
   out-of-bounds read. The handler was also a static function inside
   main.cpp, which made it unreachable from the unit test suite - the
   reason this crash class went unnoticed despite 1100+ tests
2. Fix: move the handler into utils/journallogger.{h,cpp} and submit
   through sd_journal_sendv_with_location, which takes explicit
   (pointer, length) pairs and never parses the text. Message bytes are
   carried verbatim, embedded NULs are no longer truncated, and the
   CODE_FUNC field passes the bare function name instead of the
   previously duplicated "CODE_FUNC=CODE_FUNC=..." prefix
3. Impact: journal output is unchanged for existing messages; the
   '%' escaping is no longer needed and is removed. Adds
   autotests/index/test_journallogger.cpp (8 cases) covering
   URL-encoded paths, printf conversion payloads and field formatting

fix: 日志字段改用 iovec 提交,避免 printf 解析

1. 根因:此前的修复在消息进入 sd_journal_send_with_location 之前把
   '%' 转义,而该函数第 4 参数是 printf 格式串。转义是逐字符修补:
   handler 仍把日志正文交给 printf 解析,后续往同一调用里新增字段
   就会重新引入同一个越界读取。此外该 handler 原是 main.cpp 内的
   static 函数,单测无法触及——这是此类崩溃在 1100+ 用例下仍未被
   发现的原因
2. 方案:将 handler 移入 utils/journallogger.{h,cpp},改用
   sd_journal_sendv_with_location 提交。该接口接收显式的
   (指针, 长度) 对,完全不做格式解析:消息字节逐字保真,内嵌 NUL
   不再被截断,同时修正 CODE_FUNC 字段此前重复的
   "CODE_FUNC=CODE_FUNC=..." 前缀
3. 影响:既有消息的 journal 输出不变;不再需要 '%' 转义,已移除。
   新增 autotests/index/test_journallogger.cpp(8 个用例),覆盖
   URL 编码路径、printf 转换符载荷与字段格式

Log: Fixed deepin-anything-index crash caused by format-string parsing of log text
Influence:
  - Test indexing files with URL-encoded names containing % characters
  - Test paths containing bare %d/%s/%n sequences no longer crash the service
  - Verify journal entries keep the original message text and correct CODE_FUNC
  - Verify normal file indexing and journal logging show no regression
Log: 修复 deepin-anything-index 因日志正文被当作格式串解析导致的崩溃
Influence:
  - 测试索引含 URL 编码百分号字符的文件名
  - 测试含裸 %d/%s/%n 序列的路径不再使服务崩溃
  - 验证 journal 中消息正文保持原样、CODE_FUNC 字段正确
  - 验证普通文件索引和日志记录无回归
PMS: BUG-384803
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: Johnson-zs

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@sourcery-ai

sourcery-ai Bot commented Nov 30, 2026

Copy link
Copy Markdown

Reviewer's Guide

API

Introduce the journal entry type and logger function declarations that the service and tests use.

  • src/index/utils/journallogger.h L1-61

Uses of the API

Replace the in-file handler with the logger API and install the extracted handler in the service.

  • src/index/main.cpp L7-60 (4 small edits)

Implementation

Build structured journal fields and submit them through the length-aware iovec API to avoid format parsing.

  • src/index/utils/journallogger.cpp L1-94

Configuration

Compile the extracted logger into the service and link the journal library into the index tests.

  • autotests/index/CMakeLists.txt L19, L34
  • src/index/CMakeLists.txt L60

Tests

Add regression coverage for opaque message bytes, structured fields, missing context, embedded NULs, and submission of dangerous payloads.

  • autotests/index/test_journallogger.cpp L1-164

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 7 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/index/utils/journallogger.cpp" line_range="77-78" />
<code_context>
+          static_cast<size_t>(entry.identifier.size()) },
+    };
+
+    return sd_journal_sendv_with_location(entry.file.constData(), entry.line.constData(),
+                                          entry.funcName.constData(), iov,
+                                          static_cast<int>(sizeof(iov) / sizeof(iov[0])));
+}
</code_context>
<issue_to_address>
**Journal logger fails to build**

`entry.line.constData()` passes a `const char *` where libsystemd’s `sd_journal_sendv_with_location` expects an integer line number, so the C++ compiler rejects the call and the index target cannot build.

Pass the raw source file path and integer line number to `sd_journal_sendv_with_location`, keeping any `CODE_FILE=` or `CODE_LINE=` prefixes only in fields submitted through the iovec.
</issue_to_address>

### Comment 2
<location path="src/index/utils/journallogger.cpp" line_range="50-51" />
<code_context>
+    // their length via QByteArray::size().
+    entry.message = prefixed("MESSAGE=", msg.toUtf8());
+    entry.priority = prefixed("PRIORITY=", QByteArray::number(qtMsgTypeToJournalPriority(type)));
+    entry.file = prefixed("CODE_FILE=", context.file ? QByteArray(context.file) : QByteArray());
+    entry.line = prefixed("CODE_LINE=", QByteArray::number(context.line));
+    // Bare function name only: libsystemd prepends "CODE_FUNC=" itself.
+    entry.funcName = context.function ? QByteArray(context.function) : QByteArray();
</code_context>
<issue_to_address>
**Journal source locations are malformed**

When a Qt log message with source context is submitted to the journal, `buildJournalEntry` stores `CODE_FILE=` and `CODE_LINE=` in the location values, then `sendJournalEntry` passes them to libsystemd, which adds those field names again. Journal records therefore contain duplicated prefixes instead of usable source locations.

Pass the raw file path and line value as location arguments, leaving libsystemd to add the field names.

Also at `src/index/utils/journallogger.cpp:77-78`.
</issue_to_address>

### Comment 3
<location path="src/index/utils/journallogger.cpp" line_range="88-89" />
<code_context>
+    const JournalEntry entry = buildJournalEntry(type, context, msg);
+    if (sendJournalEntry(entry) < 0) {
+        // Fallback for non-systemd environments (manual runs, tests).
+        fprintf(stderr, "deepin-anything-index[%d]: %s\n",
+                qtMsgTypeToJournalPriority(type), msg.toUtf8().constData());
+        fflush(stderr);
+    }
</code_context>
<issue_to_address>
**Fallback truncates NUL messages**

When journal submission fails and the message contains an embedded NUL, `fprintf` treats the UTF-8 message as a C string, so an embedded NUL truncates the stderr fallback even though the journal submission preserves the message length; callers see only the text before the NUL when journal submission fails.

Write the fallback message using its explicit UTF-8 byte length, or otherwise define and test a binary-safe fallback representation.
</issue_to_address>

### Comment 4
<location path="src/index/utils/journallogger.h" line_range="27" />
<code_context>
+    QByteArray file;         // "CODE_FILE=<path>"
+    QByteArray line;         // "CODE_LINE=<n>"
+    QByteArray funcName;     // bare function name (libsystemd adds CODE_FUNC=)
+    QByteArray identifier;   // "SYSLOG_IDENTIFIER=<name>"
+};
+
</code_context>
<issue_to_address>
**Mixed-case variables remain**

The new `funcName` member, `debugEntry` local, and `emptyContext` local use mixed-case names rather than snake_case, violating the repository's variable naming rule.

Rename the member and locals using snake_case.

Also at `autotests/index/test_journallogger.cpp:113`, `autotests/index/test_journallogger.cpp:132`.
</issue_to_address>

### Comment 5
<location path="src/index/utils/journallogger.cpp" line_range="18" />
<code_context>
+
+namespace {
+
+constexpr char kIdentifierField[] = "SYSLOG_IDENTIFIER=deepin-anything-index";
+
+QByteArray prefixed(const char *prefix, const QByteArray &value)
</code_context>
<issue_to_address>
**Constants use mixed-case names**

The new constants `kIdentifierField`, `kSampleFile`, `kSampleFunc`, and `kSampleLine` use k-prefixed mixed-case names instead of UPPER_CASE, violating the repository's constant naming rule.

Rename the constants using UPPER_CASE.

Also at `autotests/index/test_journallogger.cpp:53-55`.
</issue_to_address>

### Comment 6
<location path="autotests/index/test_journallogger.cpp" line_range="35" />
<code_context>
+
+namespace {
+
+QStringList crashPayloads()
+{
+    return {
</code_context>
<issue_to_address>
**Test uses nonstandard collection type**

`crashPayloads` returns a `QStringList` rather than a `std::vector`, contrary to the repository's collection-type rule.

Return a `std::vector<QString>` and include its standard header.
</issue_to_address>

### Comment 7
<location path="src/index/utils/journallogger.cpp" line_range="1" />
<code_context>
+// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd.
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
</code_context>
<issue_to_address>
**New files use different copyright header**

These new files identify `UnionTech Software Technology Co., Ltd.` in their SPDX copyright lines instead of the required `UOS Technology Co., Ltd.` header, so they do not follow the repository's copyright-header rule.

Use the copyright header required by the repository guidance in each new file.

Also at `src/index/utils/journallogger.h:1`, `autotests/index/test_journallogger.cpp:1`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment on lines +77 to +78
return sd_journal_sendv_with_location(entry.file.constData(), entry.line.constData(),
entry.funcName.constData(), iov,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Critical · Journal logger fails to build

entry.line.constData() passes a const char * where libsystemd’s sd_journal_sendv_with_location expects an integer line number, so the C++ compiler rejects the call and the index target cannot build.

Pass the raw source file path and integer line number to sd_journal_sendv_with_location, keeping any CODE_FILE= or CODE_LINE= prefixes only in fields submitted through the iovec.

Prompt for AI agents
In `src/index/utils/journallogger.cpp` at lines 77-78:

**Journal logger fails to build**

`entry.line.constData()` passes a `const char *` where libsystemd’s `sd_journal_sendv_with_location` expects an integer line number, so the C++ compiler rejects the call and the index target cannot build.

Pass the raw source file path and integer line number to `sd_journal_sendv_with_location`, keeping any `CODE_FILE=` or `CODE_LINE=` prefixes only in fields submitted through the iovec.

Comment on lines +50 to +51
entry.file = prefixed("CODE_FILE=", context.file ? QByteArray(context.file) : QByteArray());
entry.line = prefixed("CODE_LINE=", QByteArray::number(context.line));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Journal source locations are malformed

When a Qt log message with source context is submitted to the journal, buildJournalEntry stores CODE_FILE= and CODE_LINE= in the location values, then sendJournalEntry passes them to libsystemd, which adds those field names again. Journal records therefore contain duplicated prefixes instead of usable source locations.

Pass the raw file path and line value as location arguments, leaving libsystemd to add the field names.

Also at src/index/utils/journallogger.cpp:77-78.

Prompt for AI agents
In `src/index/utils/journallogger.cpp` at lines 50-51:

**Journal source locations are malformed**

When a Qt log message with source context is submitted to the journal, `buildJournalEntry` stores `CODE_FILE=` and `CODE_LINE=` in the location values, then `sendJournalEntry` passes them to libsystemd, which adds those field names again. Journal records therefore contain duplicated prefixes instead of usable source locations.

Pass the raw file path and line value as location arguments, leaving libsystemd to add the field names.

Also at `src/index/utils/journallogger.cpp:77-78`.

Comment on lines +88 to +89
fprintf(stderr, "deepin-anything-index[%d]: %s\n",
qtMsgTypeToJournalPriority(type), msg.toUtf8().constData());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Fallback truncates NUL messages

When journal submission fails and the message contains an embedded NUL, fprintf treats the UTF-8 message as a C string, so an embedded NUL truncates the stderr fallback even though the journal submission preserves the message length; callers see only the text before the NUL when journal submission fails.

Write the fallback message using its explicit UTF-8 byte length, or otherwise define and test a binary-safe fallback representation.

Prompt for AI agents
In `src/index/utils/journallogger.cpp` at lines 88-89:

**Fallback truncates NUL messages**

When journal submission fails and the message contains an embedded NUL, `fprintf` treats the UTF-8 message as a C string, so an embedded NUL truncates the stderr fallback even though the journal submission preserves the message length; callers see only the text before the NUL when journal submission fails.

Write the fallback message using its explicit UTF-8 byte length, or otherwise define and test a binary-safe fallback representation.

QByteArray file; // "CODE_FILE=<path>"
QByteArray line; // "CODE_LINE=<n>"
QByteArray funcName; // bare function name (libsystemd adds CODE_FUNC=)
QByteArray identifier; // "SYSLOG_IDENTIFIER=<name>"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Mixed-case variables remain

The new funcName member, debugEntry local, and emptyContext local use mixed-case names rather than snake_case, violating the repository's variable naming rule.

Rename the member and locals using snake_case.

Also at autotests/index/test_journallogger.cpp:113, autotests/index/test_journallogger.cpp:132.

Prompt for AI agents
In `src/index/utils/journallogger.h` at line 27:

**Mixed-case variables remain**

The new `funcName` member, `debugEntry` local, and `emptyContext` local use mixed-case names rather than snake_case, violating the repository's variable naming rule.

Rename the member and locals using snake_case.

Also at `autotests/index/test_journallogger.cpp:113`, `autotests/index/test_journallogger.cpp:132`.

From AGENTS.md L59:

- Variables: `snake_case` (e.g., `config_ptr`, `event_handler`)


namespace {

constexpr char kIdentifierField[] = "SYSLOG_IDENTIFIER=deepin-anything-index";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Constants use mixed-case names

The new constants kIdentifierField, kSampleFile, kSampleFunc, and kSampleLine use k-prefixed mixed-case names instead of UPPER_CASE, violating the repository's constant naming rule.

Rename the constants using UPPER_CASE.

Also at autotests/index/test_journallogger.cpp:53-55.

Prompt for AI agents
In `src/index/utils/journallogger.cpp` at line 18:

**Constants use mixed-case names**

The new constants `kIdentifierField`, `kSampleFile`, `kSampleFunc`, and `kSampleLine` use k-prefixed mixed-case names instead of UPPER_CASE, violating the repository's constant naming rule.

Rename the constants using UPPER_CASE.

Also at `autotests/index/test_journallogger.cpp:53-55`.

From AGENTS.md L60:

- Constants: `UPPER_CASE` (e.g., `MAX_INPUT_MINOR`, `INFO_LEVELS`)


namespace {

QStringList crashPayloads()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Test uses nonstandard collection type

crashPayloads returns a QStringList rather than a std::vector, contrary to the repository's collection-type rule.

Return a std::vector<QString> and include its standard header.

Prompt for AI agents
In `autotests/index/test_journallogger.cpp` at line 35:

**Test uses nonstandard collection type**

`crashPayloads` returns a `QStringList` rather than a `std::vector`, contrary to the repository's collection-type rule.

Return a `std::vector<QString>` and include its standard header.

From AGENTS.md L77, AGENTS.md L80:

### C++ Style (C++17/20)

@@ -0,0 +1,94 @@
// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · New files use different copyright header

These new files identify UnionTech Software Technology Co., Ltd. in their SPDX copyright lines instead of the required UOS Technology Co., Ltd. header, so they do not follow the repository's copyright-header rule.

Use the copyright header required by the repository guidance in each new file.

Also at src/index/utils/journallogger.h:1, autotests/index/test_journallogger.cpp:1.

Prompt for AI agents
In `src/index/utils/journallogger.cpp` at line 1:

**New files use different copyright header**

These new files identify `UnionTech Software Technology Co., Ltd.` in their SPDX copyright lines instead of the required `UOS Technology Co., Ltd.` header, so they do not follow the repository's copyright-header rule.

Use the copyright header required by the repository guidance in each new file.

Also at `src/index/utils/journallogger.h:1`, `autotests/index/test_journallogger.cpp:1`.

From AGENTS.md L94:

- Include SPDX headers: `// Copyright (C) <year> UOS Technology Co., Ltd.`

@wangrong1069 wangrong1069 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 没有问题

@Johnson-zs

Copy link
Copy Markdown
Author

/forcemerge

@deepin-bot
deepin-bot Bot merged commit ed76e3a into linuxdeepin:develop/snipe Nov 30, 2026
18 of 20 checks passed
@deepin-bot

deepin-bot Bot commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

This pr force merged! (status: unstable, merge_method: rebase)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants