1 /*
2 * Copyright 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #pragma once
18
19 #include <chrono>
20 #include <cstdint>
21 #include <limits>
22 #include <ostream>
23
24 namespace rootcanal::pcap {
25
26 using namespace std::literals;
27
WriteHeader(std::ostream & output,uint32_t linktype)28 static void WriteHeader(std::ostream& output, uint32_t linktype) {
29 // https://tools.ietf.org/id/draft-gharris-opsawg-pcap-00.html#name-file-header
30 uint32_t magic_number = 0xa1b2c3d4;
31 uint16_t major_version = 2;
32 uint16_t minor_version = 4;
33 uint32_t reserved1 = 0;
34 uint32_t reserved2 = 0;
35 uint32_t snaplen = std::numeric_limits<uint32_t>::max();
36
37 output.write((char*)&magic_number, 4);
38 output.write((char*)&major_version, 2);
39 output.write((char*)&minor_version, 2);
40 output.write((char*)&reserved1, 4);
41 output.write((char*)&reserved2, 4);
42 output.write((char*)&snaplen, 4);
43 output.write((char*)&linktype, 4);
44 }
45
WriteRecordHeader(std::ostream & output,uint32_t length)46 static void WriteRecordHeader(std::ostream& output, uint32_t length) {
47 auto time = std::chrono::system_clock::now().time_since_epoch();
48
49 // https://tools.ietf.org/id/draft-gharris-opsawg-pcap-00.html#name-packet-record
50 uint32_t seconds = time / 1s;
51 uint32_t microseconds = (time % 1s) / 1ms;
52 uint32_t captured_packet_length = length;
53 uint32_t original_packet_length = length;
54
55 output.write((char*)&seconds, 4);
56 output.write((char*)µseconds, 4);
57 output.write((char*)&captured_packet_length, 4);
58 output.write((char*)&original_packet_length, 4);
59 }
60
61 } // namespace rootcanal::pcap
62