OLD | NEW |
| (Empty) |
1 // Copyright 2016 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include "remoting/host/security_key/security_key_message_writer.h" | |
6 | |
7 #include <cstdint> | |
8 #include <string> | |
9 #include <utility> | |
10 | |
11 #include "remoting/host/security_key/security_key_message.h" | |
12 | |
13 namespace remoting { | |
14 | |
15 SecurityKeyMessageWriter::SecurityKeyMessageWriter(base::File output_file) | |
16 : output_stream_(std::move(output_file)) {} | |
17 | |
18 SecurityKeyMessageWriter::~SecurityKeyMessageWriter() {} | |
19 | |
20 bool SecurityKeyMessageWriter::WriteMessage( | |
21 SecurityKeyMessageType message_type) { | |
22 return WriteMessageWithPayload(message_type, std::string()); | |
23 } | |
24 | |
25 bool SecurityKeyMessageWriter::WriteMessageWithPayload( | |
26 SecurityKeyMessageType message_type, | |
27 const std::string& message_payload) { | |
28 if (write_failed_ || !output_stream_.IsValid()) { | |
29 return false; | |
30 } | |
31 | |
32 int message_payload_size_bytes = message_payload.size(); | |
33 uint32_t total_message_size_bytes = | |
34 SecurityKeyMessage::kMessageTypeSizeBytes + message_payload_size_bytes; | |
35 CHECK(SecurityKeyMessage::IsValidMessageSize(total_message_size_bytes)); | |
36 | |
37 // First we send the message header which is the length of the message_type | |
38 // and message_payload in bytes. | |
39 if (!WriteBytesToOutput(reinterpret_cast<char*>(&total_message_size_bytes), | |
40 SecurityKeyMessage::kHeaderSizeBytes)) { | |
41 LOG(ERROR) << "Failed to send message header."; | |
42 return false; | |
43 } | |
44 | |
45 // Next we send the message_type. | |
46 if (!WriteBytesToOutput(reinterpret_cast<char*>(&message_type), | |
47 SecurityKeyMessage::kMessageTypeSizeBytes)) { | |
48 LOG(ERROR) << "Failed to send message type."; | |
49 return false; | |
50 } | |
51 | |
52 // Lastly, send the message data if appropriate. | |
53 if (!message_payload.empty()) { | |
54 if (!WriteBytesToOutput(message_payload.data(), | |
55 message_payload_size_bytes)) { | |
56 LOG(ERROR) << "Failed to send message payload."; | |
57 return false; | |
58 } | |
59 } | |
60 | |
61 return true; | |
62 } | |
63 | |
64 bool SecurityKeyMessageWriter::WriteBytesToOutput(const char* message, | |
65 int bytes_to_write) { | |
66 DCHECK(message); | |
67 DCHECK_GT(bytes_to_write, 0); | |
68 | |
69 int result = output_stream_.WriteAtCurrentPos(message, bytes_to_write); | |
70 if (result != bytes_to_write) { | |
71 LOG(ERROR) << "Failed to write all bytes to output stream. bytes written: " | |
72 << result << ", file error: " | |
73 << base::File::ErrorToString(output_stream_.error_details()); | |
74 write_failed_ = true; | |
75 return false; | |
76 } | |
77 | |
78 return true; | |
79 } | |
80 | |
81 } // namespace remoting | |
OLD | NEW |