Coverage Report

Created: 2026-12-01 07:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/PcapPlusPlus/Common++/src/Serializers.cpp
Line
Count
Source
1
#include "Serializers.h"
2
3
#include <iomanip>
4
#include <ostream>
5
#include <sstream>
6
#include "json.hpp"
7
8
namespace pcpp
9
{
10
  namespace
11
  {
12
    // JS Number.MAX_SAFE_INTEGER == 2^53 - 1. Above this, a JSON number
13
    // literal can silently lose precision in JS-based parsers. Shared
14
    // by JsonSerializer and JsonSerializer2's uint64_t handling.
15
    constexpr uint64_t kMaxSafeJsonInteger = 9007199254740991ULL;
16
17
    void hexNumToStream(std::ostream& out, uint64_t number)
18
0
    {
19
0
      const std::ios_base::fmtflags flags = out.flags();
20
0
      out << "0x" << std::hex << number;
21
0
      out.flags(flags);
22
0
    }
23
24
    std::string hexNumToString(uint64_t number)
25
0
    {
26
0
      std::ostringstream oss;
27
0
      hexNumToStream(oss, number);
28
0
      return oss.str();
29
0
    }
30
31
    /// @brief Formatting view that prints a string as an escaped quoted string.
32
    ///
33
    /// Backslash-escapes a string for embedding in a double-quoted JSON or YAML scalar.
34
    /// Shared by JsonSerializer and YamlSerializer.
35
    struct EscapedQuotedString
36
    {
37
0
      explicit EscapedQuotedString(std::string const& s) : str(s)
38
0
      {}
39
40
      std::string const& str;
41
42
      friend std::ostream& operator<<(std::ostream& os, EscapedQuotedString const& eqs)
43
0
      {
44
0
        for (char c : eqs.str)
45
0
        {
46
0
          switch (c)
47
0
          {
48
0
          case '"':
49
0
            os << "\\\"";
50
0
            break;
51
0
          case '\\':
52
0
            os << "\\\\";
53
0
            break;
54
0
          case '\n':
55
0
            os << "\\n";
56
0
            break;
57
0
          case '\t':
58
0
            os << "\\t";
59
0
            break;
60
0
          default:
61
0
            os << c;
62
0
          }
63
0
        }
64
0
        return os;
65
0
      }
66
    };
67
  }  // namespace
68
69
  // ============================================================
70
  // ISerializer
71
  // ============================================================
72
73
  void ISerializer::enforceOneRoot()
74
0
  {
75
0
    if (!m_ShouldEnforceOneRoot)
76
0
    {
77
0
      return;
78
0
    }
79
80
0
    if (m_RootWritten)
81
0
    {
82
0
      throw std::logic_error("Only one root value may be written per instance");
83
0
    }
84
85
0
    m_RootWritten = true;
86
0
  }
87
88
  ArrayScope ISerializer::writeArray(const FieldDescriptor& field)
89
0
  {
90
0
    enforceOneRoot();
91
0
    return { this, field };
92
0
  }
93
94
  ObjectScope ISerializer::writeObject(const FieldDescriptor& field)
95
0
  {
96
0
    enforceOneRoot();
97
0
    return { this, field };
98
0
  }
99
100
  // ============================================================
101
  // ScopeBase
102
  // ============================================================
103
104
  void ScopeBase::writeField(const FieldDescriptor& field, const std::string& value)
105
0
  {
106
0
    m_Serializer->writeField(field, value);
107
0
  }
108
109
  void ScopeBase::writeField(const FieldDescriptor& field, int64_t value)
110
0
  {
111
0
    m_Serializer->writeField(field, value);
112
0
  }
113
114
  void ScopeBase::writeField(const FieldDescriptor& field, uint64_t value)
115
0
  {
116
0
    m_Serializer->writeField(field, value);
117
0
  }
118
119
  void ScopeBase::writeField(const FieldDescriptor& field, double value)
120
0
  {
121
0
    m_Serializer->writeField(field, value);
122
0
  }
123
124
  void ScopeBase::writeField(const FieldDescriptor& field, bool value)
125
0
  {
126
0
    m_Serializer->writeField(field, value);
127
0
  }
128
129
  void ScopeBase::writeNullField(const FieldDescriptor& field)
130
0
  {
131
0
    m_Serializer->writeNullField(field);
132
0
  }
133
134
  void ScopeBase::writeHexField(const FieldDescriptor& field, uint64_t value)
135
0
  {
136
0
    m_Serializer->writeHexField(field, value);
137
0
  }
138
139
  void ScopeBase::startObject(const FieldDescriptor& field)
140
0
  {
141
0
    m_Serializer->startObject(field);
142
0
  }
143
144
  void ScopeBase::endObject()
145
0
  {
146
0
    m_Serializer->endObject();
147
0
  }
148
149
  void ScopeBase::startArray(const FieldDescriptor& field)
150
0
  {
151
0
    m_Serializer->startArray(field);
152
0
  }
153
154
  void ScopeBase::endArray()
155
0
  {
156
0
    m_Serializer->endArray();
157
0
  }
158
159
  // ============================================================
160
  // ArrayScope
161
  // ============================================================
162
163
0
  ArrayScope::ArrayScope(ISerializer* serializer, const FieldDescriptor& field) : ScopeBase(serializer)
164
0
  {
165
0
    m_Serializer->startArray(field);
166
0
  }
167
168
  ArrayScope::~ArrayScope()
169
0
  {
170
0
    m_Serializer->endArray();
171
0
  }
172
173
  // ============================================================
174
  // ObjectScope
175
  // ============================================================
176
177
0
  ObjectScope::ObjectScope(ISerializer* serializer, const FieldDescriptor& field) : ScopeBase(serializer)
178
0
  {
179
0
    m_Serializer->startObject(field);
180
0
  }
181
182
  ObjectScope::~ObjectScope()
183
0
  {
184
0
    m_Serializer->endObject();
185
0
  }
186
187
  // ============================================================
188
  // JsonSerializer
189
  // ============================================================
190
191
0
  JsonSerializer::JsonSerializer(std::ostream& out, int indent) : m_Out(out), m_IndentPerLevel(indent)
192
0
  {}
193
194
  void JsonSerializer::startObject(const FieldDescriptor& field)
195
0
  {
196
0
    prepareNext();
197
0
    writeKey(field.name);
198
0
    m_Out << '{';
199
0
    m_ContextStack.push_back(Context::Object);
200
0
    m_FirstAtLevel.push_back(true);
201
0
  }
202
203
  void JsonSerializer::endObject()
204
0
  {
205
0
    bool hasContent = !m_FirstAtLevel.back();
206
0
    m_ContextStack.pop_back();
207
0
    m_FirstAtLevel.pop_back();
208
    // If no content was written, an object should be written as {} on a single line.
209
0
    if (hasContent)
210
0
    {
211
0
      writeNewlineAndIndent();
212
0
    }
213
0
    m_Out << '}';
214
0
  }
215
216
  void JsonSerializer::startArray(const FieldDescriptor& field)
217
0
  {
218
0
    prepareNext();
219
0
    writeKey(field.name);
220
0
    m_Out << '[';
221
0
    m_ContextStack.push_back(Context::Array);
222
0
    m_FirstAtLevel.push_back(true);
223
0
  }
224
225
  void JsonSerializer::endArray()
226
0
  {
227
0
    bool hasContent = !m_FirstAtLevel.back();
228
0
    m_ContextStack.pop_back();
229
0
    m_FirstAtLevel.pop_back();
230
    // If no content was written, an array should be written as [] on a single line.
231
0
    if (hasContent)
232
0
    {
233
0
      writeNewlineAndIndent();
234
0
    }
235
0
    m_Out << ']';
236
0
  }
237
238
  void JsonSerializer::writeField(const FieldDescriptor& field, const std::string& value)
239
0
  {
240
0
    prepareNext();
241
0
    writeKey(field.name);
242
0
    m_Out << '"' << EscapedQuotedString(value) << '"';
243
0
  }
244
245
  void JsonSerializer::writeField(const FieldDescriptor& field, int64_t value)
246
0
  {
247
0
    prepareNext();
248
0
    writeKey(field.name);
249
0
    m_Out << value;
250
0
  }
251
252
  void JsonSerializer::writeField(const FieldDescriptor& field, uint64_t value)
253
0
  {
254
0
    prepareNext();
255
0
    writeKey(field.name);
256
    // Only quote when the value could actually lose precision in a
257
    // JS-based JSON parser — not unconditionally for every uint64_t
258
    // caller, since narrower widths (uint8_t/16_t/32_t) also arrive
259
    // here via the canonical virtual and shouldn't be quoted needlessly.
260
0
    if (value > kMaxSafeJsonInteger)
261
0
      m_Out << '"' << value << '"';
262
0
    else
263
0
      m_Out << value;
264
0
  }
265
266
  void JsonSerializer::writeField(const FieldDescriptor& field, double value)
267
0
  {
268
0
    prepareNext();
269
0
    writeKey(field.name);
270
0
    m_Out << value;
271
0
  }
272
273
  void JsonSerializer::writeField(const FieldDescriptor& field, bool value)
274
0
  {
275
0
    prepareNext();
276
0
    writeKey(field.name);
277
0
    m_Out << (value ? "true" : "false");
278
0
  }
279
280
  void JsonSerializer::writeNullField(const FieldDescriptor& field)
281
0
  {
282
0
    prepareNext();
283
0
    writeKey(field.name);
284
0
    m_Out << "null";
285
0
  }
286
287
  void JsonSerializer::writeHexField(const FieldDescriptor& field, uint64_t value)
288
0
  {
289
0
    prepareNext();
290
0
    writeKey(field.name);
291
0
    m_Out << '"' << hexNumToString(value) << '"';
292
0
  }
293
294
  void JsonSerializer::writeSeparatorIfNeeded()
295
0
  {
296
0
    if (m_FirstAtLevel.empty())
297
0
      return;
298
0
    if (!m_FirstAtLevel.back())
299
0
      m_Out << ',';
300
0
    m_FirstAtLevel.back() = false;
301
0
  }
302
303
  void JsonSerializer::writeKey(const std::string& name)
304
0
  {
305
0
    if (m_ContextStack.empty())
306
0
      return;
307
0
    if (m_ContextStack.back() == Context::Array)
308
0
      return;
309
0
    m_Out << '"' << EscapedQuotedString(name) << "\":";
310
311
    // Write a space after the colon if we're not minifying, for readability.
312
0
    if (m_IndentPerLevel >= 0)
313
0
      m_Out << ' ';
314
0
  }
315
316
  void JsonSerializer::writeNewlineAndIndent()
317
0
  {
318
    // Negative indent means minified JSON.
319
0
    if (m_IndentPerLevel < 0)
320
0
      return;
321
322
0
    m_Out << '\n';
323
0
    if (m_IndentPerLevel > 0)
324
0
    {
325
0
      for (size_t i = 0; i < m_ContextStack.size() * m_IndentPerLevel; ++i)
326
0
        m_Out << ' ';
327
0
    }
328
0
  }
329
330
  // ============================================================
331
  // YamlSerializer
332
  // ============================================================
333
334
0
  YamlSerializer::YamlSerializer(std::ostream& out) : m_Out(out)
335
0
  {}
336
337
  void YamlSerializer::writeIndent()
338
0
  {
339
0
    if (!m_WriteIdent)
340
0
    {
341
0
      m_WriteIdent = true;
342
0
      return;
343
0
    }
344
    // The outermost/root container contributes no visual indent (it
345
    // has no "-"/"key:" wrapper of its own to be nested under) — only
346
    // containers pushed while the stack was already non-empty do.
347
0
    size_t depth = m_ContextStack.empty() ? 0 : m_ContextStack.size() - 1;
348
0
    m_Out << std::string(depth * 2, ' ');
349
0
  }
350
351
  void YamlSerializer::writeNewlineIfNeeded()
352
0
  {
353
0
    if (m_WriteNewLine)
354
0
      m_Out << '\n';
355
0
    m_WriteNewLine = true;
356
0
  }
357
358
  void YamlSerializer::writeContainerHeader(const std::string& name)
359
0
  {
360
0
    if (m_ContextStack.empty())
361
0
      return;  // document root: nothing visible to write at all — writing
362
               // indent(0)/newline here would leave a spurious leading blank line
363
0
    writeNewlineIfNeeded();
364
0
    writeIndent();
365
0
    if (isArrayContext())
366
0
    {
367
0
      m_Out << "- ";
368
0
      if (m_ContextStack.back() == Context::EmptyArray)
369
0
      {
370
0
        m_ContextStack.back() = Context::Array;
371
0
      }
372
0
    }
373
0
    else
374
0
      m_Out << name << ':';
375
0
  }
376
377
  void YamlSerializer::writeFieldPrefix(const std::string& name)
378
0
  {
379
0
    writeNewlineIfNeeded();
380
0
    writeIndent();
381
0
    if (isArrayContext())
382
0
    {
383
0
      m_Out << "- ";
384
0
      if (m_ContextStack.back() == Context::EmptyArray)
385
0
      {
386
0
        m_ContextStack.back() = Context::Array;
387
0
      }
388
0
      return;
389
0
    }
390
0
    m_Out << name << ": ";  // also covers the (degenerate) root-scalar case
391
0
  }
392
393
  void YamlSerializer::startObject(const FieldDescriptor& field)
394
0
  {
395
0
    writeContainerHeader(field.name);
396
0
    if (isArrayContext())
397
0
    {
398
0
      m_WriteIdent = false;
399
0
      m_WriteNewLine = false;
400
0
    }
401
0
    m_ContextStack.push_back(Context::Object);
402
0
  }
403
404
  void YamlSerializer::endObject()
405
0
  {
406
0
    m_ContextStack.pop_back();
407
0
  }
408
409
  void YamlSerializer::startArray(const FieldDescriptor& field)
410
0
  {
411
0
    writeContainerHeader(field.name);
412
0
    m_ContextStack.push_back(Context::EmptyArray);
413
0
  }
414
415
  void YamlSerializer::endArray()
416
0
  {
417
0
    if (m_ContextStack.back() == Context::EmptyArray)
418
0
    {
419
0
      m_Out << " []";
420
0
    }
421
0
    m_ContextStack.pop_back();
422
0
  }
423
424
  void YamlSerializer::writeField(const FieldDescriptor& field, const std::string& value)
425
0
  {
426
0
    writeFieldPrefix(field.name);
427
0
    m_Out << '"' << EscapedQuotedString(value) << '"';
428
0
  }
429
430
  void YamlSerializer::writeField(const FieldDescriptor& field, int64_t value)
431
0
  {
432
0
    writeFieldPrefix(field.name);
433
0
    m_Out << value;
434
0
  }
435
436
  void YamlSerializer::writeField(const FieldDescriptor& field, uint64_t value)
437
0
  {
438
0
    writeFieldPrefix(field.name);
439
    // Same reasoning as JsonSerializer: only quote when the value
440
    // could actually lose precision in a JS-based consumer (many YAML
441
    // tools, e.g. js-yaml, are JS-based) — not unconditionally.
442
0
    if (value > kMaxSafeJsonInteger)
443
0
      m_Out << '"' << value << '"';
444
0
    else
445
0
      m_Out << value;
446
0
  }
447
448
  void YamlSerializer::writeField(const FieldDescriptor& field, double value)
449
0
  {
450
0
    writeFieldPrefix(field.name);
451
0
    m_Out << value;
452
0
  }
453
454
  void YamlSerializer::writeField(const FieldDescriptor& field, bool value)
455
0
  {
456
0
    writeFieldPrefix(field.name);
457
0
    m_Out << (value ? "true" : "false");
458
0
  }
459
460
  void YamlSerializer::writeNullField(const FieldDescriptor& field)
461
0
  {
462
0
    writeFieldPrefix(field.name);
463
0
    m_Out << "null";
464
0
  }
465
466
  void YamlSerializer::writeHexField(const FieldDescriptor& field, uint64_t value)
467
0
  {
468
0
    writeFieldPrefix(field.name);
469
0
    hexNumToStream(m_Out, value);
470
0
  }
471
472
  bool YamlSerializer::isArrayContext() const
473
0
  {
474
0
    return !m_ContextStack.empty() &&
475
0
           (m_ContextStack.back() == Context::EmptyArray || m_ContextStack.back() == Context::Array);
476
0
  }
477
478
  // ============================================================
479
  // XmlSerializer
480
  // ============================================================
481
482
  namespace
483
  {
484
    bool isXmlControlChar(char c)
485
0
    {
486
0
      return (c >= 0x00 && c <= 0x1F) && c != '\t' && c != '\n' && c != '\r';
487
0
    }
488
  }  // namespace
489
490
0
  XmlSerializer::XmlSerializer(std::ostream& out) : m_Out(out)
491
0
  {
492
    // Write XML declaration
493
0
    m_Out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
494
0
  }
495
496
  void XmlSerializer::startObject(const FieldDescriptor& field)
497
0
  {
498
0
    Context ctx;
499
0
    ctx.name = resolveElementName(field.name, "object");
500
0
    ctx.isArray = false;
501
502
0
    writeIndent();
503
0
    writeOpenTag(ctx.name);
504
0
    m_ContextStack.push_back(ctx);
505
0
  }
506
507
  void XmlSerializer::endObject()
508
0
  {
509
0
    if (m_ContextStack.empty())
510
0
      return;  // Unbalanced call - ignore
511
512
0
    Context ctx = m_ContextStack.back();
513
0
    m_ContextStack.pop_back();
514
515
0
    writeIndent();
516
0
    writeCloseTag(ctx.name);
517
0
  }
518
519
  void XmlSerializer::startArray(const FieldDescriptor& field)
520
0
  {
521
0
    Context ctx;
522
0
    ctx.name = resolveElementName(field.name, "array");
523
0
    ctx.isArray = true;
524
525
0
    writeIndent();
526
0
    writeOpenTag(ctx.name);
527
0
    m_ContextStack.push_back(std::move(ctx));
528
0
  }
529
530
  void XmlSerializer::endArray()
531
0
  {
532
0
    if (m_ContextStack.empty())
533
0
      return;
534
535
0
    Context ctx = m_ContextStack.back();
536
0
    m_ContextStack.pop_back();
537
538
0
    writeIndent();
539
0
    writeCloseTag(ctx.name);
540
0
  }
541
542
  void XmlSerializer::writeField(const FieldDescriptor& field, const std::string& value)
543
0
  {
544
0
    writeValueElement(resolveElementName(field.name, "field"), escapeXML(value), false);
545
0
  }
546
547
  void XmlSerializer::writeField(const FieldDescriptor& field, int64_t value)
548
0
  {
549
0
    writeValueElement(resolveElementName(field.name, "field"), std::to_string(value), false);
550
0
  }
551
552
  void XmlSerializer::writeField(const FieldDescriptor& field, uint64_t value)
553
0
  {
554
0
    writeValueElement(resolveElementName(field.name, "field"), std::to_string(value), false);
555
0
  }
556
557
  void XmlSerializer::writeField(const FieldDescriptor& field, double value)
558
0
  {
559
0
    std::string strVal = std::to_string(value);
560
    // Remove trailing zeros for cleaner output (and the decimal point
561
    // itself if nothing remains after it). find_last_not_of('0') lands
562
    // on the last significant digit — e.g. for "1.500000" that's the
563
    // '5', not the '.' — so we must erase everything AFTER it, not
564
    // just the "whole fraction is zero" case where it happens to land
565
    // on the decimal point.
566
0
    size_t pos = strVal.find_last_not_of('0');
567
0
    if (pos != std::string::npos)
568
0
    {
569
0
      if (strVal[pos] == '.')
570
0
        --pos;
571
0
      strVal.erase(pos + 1);
572
0
    }
573
0
    writeValueElement(resolveElementName(field.name, "field"), strVal, false);
574
0
  }
575
576
  void XmlSerializer::writeField(const FieldDescriptor& field, bool value)
577
0
  {
578
0
    writeValueElement(resolveElementName(field.name, "field"), value ? "true" : "false", false);
579
0
  }
580
581
  void XmlSerializer::writeNullField(const FieldDescriptor& field)
582
0
  {
583
0
    writeValueElement(resolveElementName(field.name, "field"), "", true);
584
0
  }
585
586
  void XmlSerializer::writeHexField(const FieldDescriptor& field, uint64_t value)
587
0
  {
588
0
    writeValueElement(resolveElementName(field.name, "field"), hexNumToString(value), false);
589
0
  }
590
591
  // --- Private helper methods ---
592
593
  void XmlSerializer::writeOpenTag(const std::string& name)
594
0
  {
595
0
    m_Out << '<' << name << '>' << '\n';
596
0
  }
597
598
  void XmlSerializer::writeCloseTag(const std::string& name)
599
0
  {
600
0
    m_Out << "</" << name << '>' << '\n';
601
0
  }
602
603
  void XmlSerializer::writeValueElement(const std::string& name, const std::string& value, bool isNull)
604
0
  {
605
0
    writeIndent();
606
0
    m_Out << '<' << name;
607
608
0
    if (isNull)
609
0
    {
610
0
      m_Out << " xsi:nil=\"true\"";
611
0
    }
612
613
0
    if (value.empty() || isNull)
614
0
    {
615
      // Empty value - self-closing tag
616
0
      m_Out << "/>\n";
617
0
    }
618
0
    else
619
0
    {
620
0
      m_Out << '>' << value << "</" << name << ">\n";
621
0
    }
622
0
  }
623
624
  void XmlSerializer::writeIndent()
625
0
  {
626
0
    if (m_ContextStack.empty())
627
0
      return;
628
629
0
    size_t depth = m_ContextStack.size();
630
    // Cache indentation strings for performance
631
0
    if (m_IndentCache.size() <= depth)
632
0
    {
633
0
      m_IndentCache.resize(depth + 1);
634
0
      std::string indent;
635
0
      for (size_t i = 0; i < depth; ++i)
636
0
      {
637
0
        indent += "  ";
638
0
      }
639
0
      m_IndentCache[depth] = indent;
640
0
    }
641
0
    m_Out << m_IndentCache[depth];
642
0
  }
643
644
  std::string XmlSerializer::escapeXML(const std::string& s)
645
0
  {
646
0
    std::string result;
647
0
    result.reserve(s.size() + s.size() / 5);  // Pre-allocate for typical ~20% expansion
648
649
0
    for (char c : s)
650
0
    {
651
      // Filter out invalid XML control characters
652
0
      if (isXmlControlChar(c))
653
0
        continue;
654
655
0
      switch (c)
656
0
      {
657
0
      case '&':
658
0
        result += "&amp;";
659
0
        break;
660
0
      case '<':
661
0
        result += "&lt;";
662
0
        break;
663
0
      case '>':
664
0
        result += "&gt;";
665
0
        break;
666
0
      case '"':
667
0
        result += "&quot;";
668
0
        break;
669
0
      case '\'':
670
0
        result += "&apos;";
671
0
        break;
672
0
      default:
673
0
        result += c;
674
0
        break;
675
0
      }
676
0
    }
677
0
    return result;
678
0
  }
679
680
  bool XmlSerializer::isValidXMLName(const std::string& name)
681
0
  {
682
0
    if (name.empty())
683
0
      return false;
684
685
    // XML names must start with a letter or underscore
686
0
    char first = name[0];
687
0
    if (!((first >= 'a' && first <= 'z') || (first >= 'A' && first <= 'Z') || first == '_' || first == ':'))
688
0
    {
689
0
      return false;
690
0
    }
691
692
    // Subsequent characters can be letters, digits, or certain punctuation
693
0
    for (size_t i = 1; i < name.length(); ++i)
694
0
    {
695
0
      char c = name[i];
696
0
      if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' ||
697
0
            c == '.' || c == ':'))
698
0
      {
699
0
        return false;
700
0
      }
701
0
    }
702
0
    return true;
703
0
  }
704
705
  std::string XmlSerializer::resolveElementName(const std::string& name, const char* fallback)
706
0
  {
707
0
    return isValidXMLName(name) ? name : std::string(fallback);
708
0
  }
709
}  // namespace pcpp