summaryrefslogtreecommitdiff
path: root/tools/rootcanal/include/pcap.h
blob: a86e52f369db5e718e62c2a0b12f4df7de010b81 (plain)
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
/*
 * Copyright 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <chrono>
#include <cstdint>
#include <limits>
#include <ostream>

namespace rootcanal::pcap {

using namespace std::literals;

static void WriteHeader(std::ostream& output, uint32_t linktype) {
  // https://tools.ietf.org/id/draft-gharris-opsawg-pcap-00.html#name-file-header
  uint32_t magic_number = 0xa1b2c3d4;
  uint16_t major_version = 2;
  uint16_t minor_version = 4;
  uint32_t reserved1 = 0;
  uint32_t reserved2 = 0;
  uint32_t snaplen = std::numeric_limits<uint32_t>::max();

  output.write((char*)&magic_number, 4);
  output.write((char*)&major_version, 2);
  output.write((char*)&minor_version, 2);
  output.write((char*)&reserved1, 4);
  output.write((char*)&reserved2, 4);
  output.write((char*)&snaplen, 4);
  output.write((char*)&linktype, 4);
}

static void WriteRecordHeader(std::ostream& output, uint32_t length) {
  auto time = std::chrono::system_clock::now().time_since_epoch();

  // https://tools.ietf.org/id/draft-gharris-opsawg-pcap-00.html#name-packet-record
  uint32_t seconds = time / 1s;
  uint32_t microseconds = (time % 1s) / 1ms;
  uint32_t captured_packet_length = length;
  uint32_t original_packet_length = length;

  output.write((char*)&seconds, 4);
  output.write((char*)&microseconds, 4);
  output.write((char*)&captured_packet_length, 4);
  output.write((char*)&original_packet_length, 4);
}

}  // namespace rootcanal::pcap