Debian Codegraph @

src/Base/Base64Filter.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /****************************************************************************
4 * *
5 * Copyright (c) 2019 Zheng Lei ([email protected]) *
6 * *
7 * This file is part of FreeCAD. *
8 * *
9 * FreeCAD is free software: you can redistribute it and/or modify it *
10 * under the terms of the GNU Lesser General Public License as *
11 * published by the Free Software Foundation, either version 2.1 of the *
12 * License, or (at your option) any later version. *
13 * *
14 * FreeCAD is distributed in the hope that it will be useful, but *
15 * WITHOUT ANY WARRANTY; without even the implied warranty of *
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
17 * Lesser General Public License for more details. *
18 * *
19 * You should have received a copy of the GNU Lesser General Public *
20 * License along with FreeCAD. If not, see *
21 * <https://www.gnu.org/licenses/>. *
22 * *
23 ***************************************************************************/
24
25 #ifndef FREECAD_BASE_BASE64FILTER_H
26 #define FREECAD_BASE_BASE64FILTER_H
27
28
29 #include "Base64.h"
30 #include "FCGlobal.h"
31
32 #include <boost/iostreams/concepts.hpp>
33 #include <boost/iostreams/device/file.hpp>
34 #include <boost/iostreams/filtering_stream.hpp>
35 #include <boost/iostreams/operations.hpp>
36
37
38 // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic,
39 // cppcoreguidelines-pro-bounds-constant-array-index, cppcoreguidelines-avoid-magic-numbers,
40 // readability-magic-numbers)
41
42 namespace Base
43 {
44
45 namespace bio = boost::iostreams;
46
47 enum class Base64ErrorHandling
48 {
49 throws,
50 silent
51 };
52 static constexpr int base64DefaultBufferSize {80};
53
54 /** A base64 encoder that can be used as a boost iostream filter
55 *
56 * @sa See create_base64_encoder() for example usage
57 */
58 struct base64_encoder
59 {
60
61 using char_type = char;
62 struct category: bio::multichar_output_filter_tag, bio::closable_tag, bio::optimally_buffered_tag
63 {
64 };
65
66 /** Constructor
67 * @param line_size: line size for the output base64 string, 0 to
68 * disable segmentation.
69 */
70 explicit base64_encoder(std::size_t line_size)
71 : line_size(line_size)
72 {}
73
74 std::streamsize optimal_buffer_size() const
75 {
76 static constexpr int defaultBufferSize {1024};
77 return static_cast<std::streamsize>(
78 base64_encode_size(line_size != 0U ? line_size : defaultBufferSize)
79 );
80 }
81
82 template<typename Device>
83 void close(Device& dev)
84 {
85 if (pending_size) {
86 base64_encode(buffer, pending.data(), pending_size);
87 }
88 if (!buffer.empty()) {
89 bio::write(dev, buffer.c_str(), buffer.size());
90 if (line_size) {
91 bio::put(dev, '\n');
92 }
93 buffer.clear();
94 }
95 else if (pos && line_size) {
96 bio::put(dev, '\n');
97 }
98 }
99
100 template<typename Device>
101 std::streamsize write(Device& dev, const char_type* str, std::streamsize n)
102 {
103 std::streamsize res = n;
104
105 if (pending_size > 0) {
106 while (n && pending_size < 3) {
107 pending[pending_size] = *str++;
108 ++pending_size;
109 --n;
110 }
111 if (pending_size != 3) {
112 return res;
113 }
114
115 base64_encode(buffer, pending.data(), 3);
116 }
117 pending_size = n % 3;
118 n = n / 3 * 3;
119 base64_encode(buffer, str, n);
120 str += n;
121 for (unsigned i = 0; i < pending_size; ++i) {
122 pending[i] = str[i];
123 }
124
125 const char* buf = buffer.c_str();
126 const char* end = buf + buffer.size();
127 if (line_size && buffer.size() >= line_size - pos) {
128 bio::write(dev, buf, line_size - pos);
129 bio::put(dev, '\n');
130 buf += line_size - pos;
131 pos = 0;
132 for (; end - buf >= (int)line_size; buf += line_size) {
133 bio::write(dev, buf, line_size);
134 bio::put(dev, '\n');
135 }
136 }
137 pos += end - buf;
138 bio::write(dev, buf, end - buf);
139 buffer.clear();
140 return n;
141 }
142
143 std::size_t line_size;
144 std::size_t pos = 0;
145 std::size_t pending_size = 0;
146 std::array<unsigned char, 3> pending {};
147 std::string buffer;
148 };
149
150 /** A base64 decoder that can be used as a boost iostream filter
151 *
152 * @sa See create_base64_decoder() for example usage
153 */
154 struct base64_decoder
155 {
156
157 using char_type = char;
158 struct category: bio::multichar_input_filter_tag, bio::optimally_buffered_tag
159 {
160 };
161
162 /** Constructor
163 * @param line_size: line size of the encoded base64 string. This is
164 * used just as a suggestion for better buffering.
165 * @param silent: whether to throw on invalid non white space character.
166 */
167 base64_decoder(std::size_t line_size, Base64ErrorHandling errHandling)
168 : line_size(line_size)
169 , errHandling(errHandling)
170 {}
171
172 std::streamsize optimal_buffer_size() const
173 {
174 static constexpr int defaultBufferSize {1024};
175 return static_cast<std::streamsize>(
176 base64_encode_size(line_size != 0U ? line_size : defaultBufferSize)
177 );
178 }
179
180 template<typename Device>
181 std::streamsize read(Device& dev, char_type* str, std::streamsize n)
182 {
183 static auto table = base64_decode_table();
184
185 if (!n) {
186 return 0;
187 }
188
189 std::streamsize count = 0;
190
191 for (;;) {
192 while (pending_out < out_count) {
193 *str++ = char_array_3[pending_out++];
194 ++count;
195 if (--n == 0) {
196 return count;
197 }
198 }
199
200 if (eof) {
201 return count ? count : -1;
202 }
203
204 for (;;) {
205 int newChar = bio::get(dev);
206 if (newChar < 0) {
207 eof = true;
208 if (pending_in <= 1) {
209 if (pending_in == 1 && errHandling == Base64ErrorHandling::throws) {
210 throw BOOST_IOSTREAMS_FAILURE("Unexpected ending of base64 string");
211 }
212 return count ? count : -1;
213 }
214 out_count = pending_in - 1;
215 pending_in = 4;
216 }
217 else {
218 signed char decodedChar = table[newChar];
219 if (decodedChar < 0) {
220 if (decodedChar == -2 || errHandling == Base64ErrorHandling::silent) {
221 continue;
222 }
223 throw BOOST_IOSTREAMS_FAILURE("Invalid character in base64 string");
224 }
225 char_array_4[pending_in++] = (char)decodedChar;
226 }
227 if (pending_in == 4) {
228 pending_out = pending_in = 0;
229 char_array_3[0] = static_cast<char>(
230 (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4)
231 );
232 char_array_3[1] = static_cast<char>(
233 ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2)
234 );
235 char_array_3[2] = static_cast<char>(
236 ((char_array_4[2] & 0x3) << 6) + char_array_4[3]
237 );
238 break;
239 }
240 }
241 }
242 }
243
244 std::size_t line_size;
245 std::uint8_t pending_in = 0;
246 std::array<char, 4> char_array_4 {};
247 std::uint8_t pending_out = 3;
248 std::uint8_t out_count = 3;
249 std::array<char, 3> char_array_3 {};
250 Base64ErrorHandling errHandling;
251 bool eof = false;
252 };
253
254 /** Create an output stream that transforms the input binary data to base64 strings
255 *
256 * @param out: the downstream output stream that will be fed with base64 string
257 * @param line_size: line size of the base64 string. Zero to disable segmenting.
258 *
259 * @return A unique pointer to an output stream that can transforms the
260 * input binary data to base64 strings.
261 */
262 inline std::unique_ptr<std::ostream> create_base64_encoder(
263 std::ostream& out,
264 std::size_t line_size = base64DefaultBufferSize
265 )
266 {
267 std::unique_ptr<std::ostream> res(new bio::filtering_ostream);
268 auto* filteringStream = dynamic_cast<bio::filtering_ostream*>(res.get());
269 filteringStream->push(base64_encoder(line_size));
270 filteringStream->push(out);
271 return res;
272 }
273
274 /** Create an output stream that stores the input binary data to file as base64 strings
275 *
276 * @param filename: the output file path
277 * @param line_size: line size of the base64 string. Zero to disable segmenting.
278 *
279 * @return A unique pointer to an output stream that can transforms the
280 * input binary data to base64 strings.
281 */
282 inline std::unique_ptr<std::ostream> create_base64_encoder(
283 const std::string& filepath,
284 std::size_t line_size = base64DefaultBufferSize
285 )
286 {
287 std::unique_ptr<std::ostream> res(new bio::filtering_ostream);
288 auto* filteringStream = dynamic_cast<bio::filtering_ostream*>(res.get());
289 filteringStream->push(base64_encoder(line_size));
290 filteringStream->push(bio::file_sink(filepath));
291 return res;
292 }
293
294 /** Create an input stream that can transform base64 into binary
295 *
296 * @param in: input upstream.
297 * @param line_size: line size of the encoded base64 string. This is
298 * used just as a suggestion for better buffering.
299 * @param silent: whether to throw on invalid non white space character.
300 *
301 * @return A unique pointer to an input stream that read from the given
302 * upstream and transform the read base64 strings into binary data.
303 */
304 inline std::unique_ptr<std::istream> create_base64_decoder(
305 std::istream& in,
306 std::size_t line_size = base64DefaultBufferSize,
307 Base64ErrorHandling errHandling = Base64ErrorHandling::silent
308 )
309 {
310 std::unique_ptr<std::istream> res(new bio::filtering_istream);
311 auto* filteringStream = dynamic_cast<bio::filtering_istream*>(res.get());
312 filteringStream->push(base64_decoder(line_size, errHandling));
313 filteringStream->push(in);
314 return res;
315 }
316
317 /** Create an input stream that can transform base64 into binary
318 *
319 * @param filepath: input file.
320 * @param ending: optional ending character. If non zero, the filter
321 * will signal EOF when encounter this character.
322 * @param putback: if true and the filter read the ending character
323 * it will put it back into upstream
324 * @param line_size: line size of the encoded base64 string. This is
325 * used just as a suggestion for better buffering.
326 * @param silent: whether to throw on invalid non white space character.
327 *
328 * @return A unique pointer to an input stream that read from the given
329 * file and transform the read base64 strings into binary data.
330 */
331 inline std::unique_ptr<std::istream> create_base64_decoder(
332 const std::string& filepath,
333 std::size_t line_size = base64DefaultBufferSize,
334 Base64ErrorHandling errHandling = Base64ErrorHandling::silent
335 )
336 {
337 std::unique_ptr<std::istream> res(new bio::filtering_istream);
338 auto* filteringStream = dynamic_cast<bio::filtering_istream*>(res.get());
339 filteringStream->push(base64_decoder(line_size, errHandling));
340 filteringStream->push(bio::file_source(filepath));
341 return res;
342 }
343
344 } // namespace Base
345
346 // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic,
347 // cppcoreguidelines-pro-bounds-constant-array-index, cppcoreguidelines-avoid-magic-numbers,
348 // readability-magic-numbers)
349
350 #endif // FREECAD_BASE_BASE64FILTER_H