blob: ea1fc3c5bdcb2ebcec81979477f432cefbaf83ac [file] [log] [blame]
David Benjamin06b94de2015-05-09 22:46:47 -04001/* Copyright (c) 2015, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15#include "file_test.h"
16
Martin Kreichgauer7c125872017-04-24 13:29:11 -070017#include <algorithm>
David Benjamin1f1eeea2017-05-18 19:39:06 -040018#include <utility>
Adam Langleya5ee83f2016-02-24 10:04:31 -080019
David Benjamin1f1eeea2017-05-18 19:39:06 -040020#include <assert.h>
David Benjamin06b94de2015-05-09 22:46:47 -040021#include <ctype.h>
22#include <errno.h>
23#include <stdarg.h>
David Benjamin1f1eeea2017-05-18 19:39:06 -040024#include <stdio.h>
David Benjamin771a1382015-05-12 18:01:17 -040025#include <stdlib.h>
David Benjamin06b94de2015-05-09 22:46:47 -040026#include <string.h>
27
David Benjamin5c694e32015-05-11 15:58:08 -040028#include <openssl/err.h>
29
David Benjamin17cf2cb2016-12-13 01:07:13 -050030#include "../internal.h"
31
David Benjamin06b94de2015-05-09 22:46:47 -040032
Adam Langleyd79bc9d2017-05-30 15:37:27 -070033FileTest::FileTest(std::unique_ptr<FileTest::LineReader> reader,
34 std::function<void(const std::string &)> comment_callback)
David Benjamin27e377e2017-07-31 19:09:42 -040035 : reader_(std::move(reader)),
36 comment_callback_(std::move(comment_callback)) {}
David Benjamin06b94de2015-05-09 22:46:47 -040037
David Benjamin1f1eeea2017-05-18 19:39:06 -040038FileTest::~FileTest() {}
David Benjamin06b94de2015-05-09 22:46:47 -040039
40// FindDelimiter returns a pointer to the first '=' or ':' in |str| or nullptr
41// if there is none.
42static const char *FindDelimiter(const char *str) {
43 while (*str) {
44 if (*str == ':' || *str == '=') {
45 return str;
46 }
47 str++;
48 }
49 return nullptr;
50}
51
52// StripSpace returns a string containing up to |len| characters from |str| with
53// leading and trailing whitespace removed.
54static std::string StripSpace(const char *str, size_t len) {
55 // Remove leading space.
56 while (len > 0 && isspace(*str)) {
57 str++;
58 len--;
59 }
Martin Kreichgauer7c125872017-04-24 13:29:11 -070060 while (len > 0 && isspace(str[len - 1])) {
David Benjamin06b94de2015-05-09 22:46:47 -040061 len--;
62 }
63 return std::string(str, len);
64}
65
Martin Kreichgauer7c125872017-04-24 13:29:11 -070066static std::pair<std::string, std::string> ParseKeyValue(const char *str, const size_t len) {
67 const char *delimiter = FindDelimiter(str);
68 std::string key, value;
69 if (delimiter == nullptr) {
70 key = StripSpace(str, len);
71 } else {
72 key = StripSpace(str, delimiter - str);
73 value = StripSpace(delimiter + 1, str + len - delimiter - 1);
74 }
75 return {key, value};
76}
77
David Benjamin06b94de2015-05-09 22:46:47 -040078FileTest::ReadResult FileTest::ReadNext() {
Martin Kreichgauer7c125872017-04-24 13:29:11 -070079 // If the previous test had unused attributes or instructions, it is an error.
David Benjamindfef2082017-05-18 19:02:21 -040080 if (!unused_attributes_.empty()) {
David Benjamin06b94de2015-05-09 22:46:47 -040081 for (const std::string &key : unused_attributes_) {
82 PrintLine("Unused attribute: %s", key.c_str());
83 }
84 return kReadError;
85 }
David Benjamindfef2082017-05-18 19:02:21 -040086 if (!unused_instructions_.empty()) {
Martin Kreichgauer7c125872017-04-24 13:29:11 -070087 for (const std::string &key : unused_instructions_) {
88 PrintLine("Unused instruction: %s", key.c_str());
89 }
90 return kReadError;
91 }
David Benjamin06b94de2015-05-09 22:46:47 -040092
93 ClearTest();
94
Steven Valdezb8a35502017-04-28 16:17:54 -040095 static const size_t kBufLen = 8192 * 4;
Adam Langleya5ee83f2016-02-24 10:04:31 -080096 std::unique_ptr<char[]> buf(new char[kBufLen]);
97
Martin Kreichgauer7c125872017-04-24 13:29:11 -070098 bool in_instruction_block = false;
Martin Kreichgauer2b2676f2017-05-01 11:56:43 -070099 is_at_new_instruction_block_ = false;
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700100
David Benjamin06b94de2015-05-09 22:46:47 -0400101 while (true) {
102 // Read the next line.
David Benjamin1f1eeea2017-05-18 19:39:06 -0400103 switch (reader_->ReadLine(buf.get(), kBufLen)) {
104 case kReadError:
105 fprintf(stderr, "Error reading from input at line %u.\n", line_ + 1);
106 return kReadError;
107 case kReadEOF:
David Benjamin06b94de2015-05-09 22:46:47 -0400108 // EOF is a valid terminator for a test.
109 return start_line_ > 0 ? kReadSuccess : kReadEOF;
David Benjamin1f1eeea2017-05-18 19:39:06 -0400110 case kReadSuccess:
111 break;
David Benjamin06b94de2015-05-09 22:46:47 -0400112 }
113
114 line_++;
Adam Langleya5ee83f2016-02-24 10:04:31 -0800115 size_t len = strlen(buf.get());
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700116 if (buf[0] == '\n' || buf[0] == '\r' || buf[0] == '\0') {
David Benjamin06b94de2015-05-09 22:46:47 -0400117 // Empty lines delimit tests.
118 if (start_line_ > 0) {
119 return kReadSuccess;
120 }
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700121 if (in_instruction_block) {
122 in_instruction_block = false;
123 // Delimit instruction block from test with a blank line.
124 current_test_ += "\r\n";
125 }
Adam Langleyd79bc9d2017-05-30 15:37:27 -0700126 } else if (buf[0] == '#') {
127 if (comment_callback_) {
128 comment_callback_(buf.get());
129 }
130 // Otherwise ignore comments.
131 } else if (strcmp("[B.4.2 Key Pair Generation by Testing Candidates]\r\n",
David Benjamineb599892017-05-01 14:56:22 -0400132 buf.get()) == 0) {
Adam Langleyd79bc9d2017-05-30 15:37:27 -0700133 // The above instruction-like line is ignored because the FIPS lab's
134 // request files are hopelessly inconsistent.
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700135 } else if (buf[0] == '[') { // Inside an instruction block.
Martin Kreichgauer2b2676f2017-05-01 11:56:43 -0700136 is_at_new_instruction_block_ = true;
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700137 if (start_line_ != 0) {
138 // Instructions should be separate blocks.
139 fprintf(stderr, "Line %u is an instruction in a test case.\n", line_);
Brian Smith7b5f08e2015-08-06 10:42:49 -0400140 return kReadError;
David Benjamin06b94de2015-05-09 22:46:47 -0400141 }
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700142 if (!in_instruction_block) {
143 ClearInstructions();
144 in_instruction_block = true;
145 }
146
147 // Parse the line as an instruction ("[key = value]" or "[key]").
148 std::string kv = StripSpace(buf.get(), len);
149 if (kv[kv.size() - 1] != ']') {
150 fprintf(stderr, "Line %u, invalid instruction: %s\n", line_,
151 kv.c_str());
152 return kReadError;
153 }
154 current_test_ += kv + "\r\n";
155 kv = std::string(kv.begin() + 1, kv.end() - 1);
156
David Benjamin0c292ed2017-04-28 17:41:28 -0400157 for (;;) {
158 size_t idx = kv.find(",");
159 if (idx == std::string::npos) {
160 idx = kv.size();
161 }
162 std::string key, value;
163 std::tie(key, value) = ParseKeyValue(kv.c_str(), idx);
164 instructions_[key] = value;
165 if (idx == kv.size())
166 break;
167 kv = kv.substr(idx + 1);
168 }
David Benjamineb599892017-05-01 14:56:22 -0400169 } else {
Martin Kreichgauer2b2676f2017-05-01 11:56:43 -0700170 // Parsing a test case.
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700171 if (in_instruction_block) {
Martin Kreichgauer2b2676f2017-05-01 11:56:43 -0700172 // Some NIST CAVP test files (TDES) have a test case immediately
173 // following an instruction block, without a separate blank line, some
174 // of the time.
175 in_instruction_block = false;
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700176 }
177
178 current_test_ += std::string(buf.get(), len);
179 std::string key, value;
180 std::tie(key, value) = ParseKeyValue(buf.get(), len);
David Benjamin06b94de2015-05-09 22:46:47 -0400181
Adam Langleyb387e222017-05-01 10:54:03 -0700182 // Duplicate keys are rewritten to have “/2”, “/3”, … suffixes.
183 std::string mapped_key = key;
184 for (unsigned i = 2; attributes_.count(mapped_key) != 0; i++) {
185 char suffix[32];
186 snprintf(suffix, sizeof(suffix), "/%u", i);
187 suffix[sizeof(suffix)-1] = 0;
188 mapped_key = key + suffix;
189 }
190
191 unused_attributes_.insert(mapped_key);
192 attributes_[mapped_key] = value;
David Benjamin06b94de2015-05-09 22:46:47 -0400193 if (start_line_ == 0) {
194 // This is the start of a test.
Adam Langleyb387e222017-05-01 10:54:03 -0700195 type_ = mapped_key;
David Benjamin06b94de2015-05-09 22:46:47 -0400196 parameter_ = value;
197 start_line_ = line_;
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700198 for (const auto &kv : instructions_) {
199 unused_instructions_.insert(kv.first);
200 }
David Benjamin06b94de2015-05-09 22:46:47 -0400201 }
202 }
203 }
204}
205
206void FileTest::PrintLine(const char *format, ...) {
207 va_list args;
208 va_start(args, format);
209
210 fprintf(stderr, "Line %u: ", start_line_);
211 vfprintf(stderr, format, args);
212 fprintf(stderr, "\n");
213
214 va_end(args);
215}
216
217const std::string &FileTest::GetType() {
218 OnKeyUsed(type_);
219 return type_;
220}
221
222const std::string &FileTest::GetParameter() {
223 OnKeyUsed(type_);
224 return parameter_;
225}
226
David Benjamin06b94de2015-05-09 22:46:47 -0400227bool FileTest::HasAttribute(const std::string &key) {
228 OnKeyUsed(key);
229 return attributes_.count(key) > 0;
230}
231
232bool FileTest::GetAttribute(std::string *out_value, const std::string &key) {
233 OnKeyUsed(key);
234 auto iter = attributes_.find(key);
235 if (iter == attributes_.end()) {
236 PrintLine("Missing attribute '%s'.", key.c_str());
237 return false;
238 }
239 *out_value = iter->second;
240 return true;
241}
242
David Benjamin5c694e32015-05-11 15:58:08 -0400243const std::string &FileTest::GetAttributeOrDie(const std::string &key) {
244 if (!HasAttribute(key)) {
245 abort();
246 }
247 return attributes_[key];
248}
249
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700250bool FileTest::HasInstruction(const std::string &key) {
251 OnInstructionUsed(key);
252 return instructions_.count(key) > 0;
253}
254
255bool FileTest::GetInstruction(std::string *out_value, const std::string &key) {
256 OnInstructionUsed(key);
257 auto iter = instructions_.find(key);
258 if (iter == instructions_.end()) {
259 PrintLine("Missing instruction '%s'.", key.c_str());
260 return false;
261 }
262 *out_value = iter->second;
263 return true;
264}
265
266const std::string &FileTest::CurrentTestToString() const {
267 return current_test_;
268}
269
David Benjamin06b94de2015-05-09 22:46:47 -0400270static bool FromHexDigit(uint8_t *out, char c) {
271 if ('0' <= c && c <= '9') {
272 *out = c - '0';
273 return true;
274 }
275 if ('a' <= c && c <= 'f') {
276 *out = c - 'a' + 10;
277 return true;
278 }
279 if ('A' <= c && c <= 'F') {
280 *out = c - 'A' + 10;
281 return true;
282 }
283 return false;
284}
285
286bool FileTest::GetBytes(std::vector<uint8_t> *out, const std::string &key) {
287 std::string value;
288 if (!GetAttribute(&value, key)) {
289 return false;
290 }
291
292 if (value.size() >= 2 && value[0] == '"' && value[value.size() - 1] == '"') {
293 out->assign(value.begin() + 1, value.end() - 1);
294 return true;
295 }
296
297 if (value.size() % 2 != 0) {
298 PrintLine("Error decoding value: %s", value.c_str());
299 return false;
300 }
David Benjamine30a09e2016-01-01 01:17:30 -0500301 out->clear();
David Benjamin06b94de2015-05-09 22:46:47 -0400302 out->reserve(value.size() / 2);
303 for (size_t i = 0; i < value.size(); i += 2) {
304 uint8_t hi, lo;
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700305 if (!FromHexDigit(&hi, value[i]) || !FromHexDigit(&lo, value[i + 1])) {
David Benjamin06b94de2015-05-09 22:46:47 -0400306 PrintLine("Error decoding value: %s", value.c_str());
307 return false;
308 }
309 out->push_back((hi << 4) | lo);
310 }
311 return true;
312}
313
314static std::string EncodeHex(const uint8_t *in, size_t in_len) {
315 static const char kHexDigits[] = "0123456789abcdef";
316 std::string ret;
317 ret.reserve(in_len * 2);
318 for (size_t i = 0; i < in_len; i++) {
319 ret += kHexDigits[in[i] >> 4];
320 ret += kHexDigits[in[i] & 0xf];
321 }
322 return ret;
323}
324
325bool FileTest::ExpectBytesEqual(const uint8_t *expected, size_t expected_len,
326 const uint8_t *actual, size_t actual_len) {
327 if (expected_len == actual_len &&
David Benjamin17cf2cb2016-12-13 01:07:13 -0500328 OPENSSL_memcmp(expected, actual, expected_len) == 0) {
David Benjamin06b94de2015-05-09 22:46:47 -0400329 return true;
330 }
331
332 std::string expected_hex = EncodeHex(expected, expected_len);
333 std::string actual_hex = EncodeHex(actual, actual_len);
334 PrintLine("Expected: %s", expected_hex.c_str());
335 PrintLine("Actual: %s", actual_hex.c_str());
336 return false;
337}
338
339void FileTest::ClearTest() {
340 start_line_ = 0;
341 type_.clear();
342 parameter_.clear();
343 attributes_.clear();
David Benjamin06b94de2015-05-09 22:46:47 -0400344 unused_attributes_.clear();
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700345 current_test_ = "";
346}
347
348void FileTest::ClearInstructions() {
349 instructions_.clear();
350 unused_attributes_.clear();
David Benjamin06b94de2015-05-09 22:46:47 -0400351}
352
353void FileTest::OnKeyUsed(const std::string &key) {
354 unused_attributes_.erase(key);
355}
356
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700357void FileTest::OnInstructionUsed(const std::string &key) {
358 unused_instructions_.erase(key);
359}
360
Martin Kreichgauer2b2676f2017-05-01 11:56:43 -0700361bool FileTest::IsAtNewInstructionBlock() const {
362 return is_at_new_instruction_block_;
363}
364
Martin Kreichgauer6dd055d2017-05-01 15:31:43 -0700365void FileTest::InjectInstruction(const std::string &key,
366 const std::string &value) {
367 instructions_[key] = value;
368}
369
David Benjamin1f1eeea2017-05-18 19:39:06 -0400370class FileLineReader : public FileTest::LineReader {
371 public:
372 explicit FileLineReader(const char *path) : file_(fopen(path, "r")) {}
373 ~FileLineReader() override {
374 if (file_ != nullptr) {
375 fclose(file_);
376 }
377 }
378
379 // is_open returns true if the file was successfully opened.
380 bool is_open() const { return file_ != nullptr; }
381
382 FileTest::ReadResult ReadLine(char *out, size_t len) override {
383 assert(len > 0);
384 if (file_ == nullptr) {
385 return FileTest::kReadError;
386 }
387
388 if (fgets(out, len, file_) == nullptr) {
389 return feof(file_) ? FileTest::kReadEOF : FileTest::kReadError;
390 }
391
392 if (strlen(out) == len - 1 && out[len - 2] != '\n' && !feof(file_)) {
393 fprintf(stderr, "Line too long.\n");
394 return FileTest::kReadError;
395 }
396
397 return FileTest::kReadSuccess;
398 }
399
400 private:
401 FILE *file_;
402
403 FileLineReader(const FileLineReader &) = delete;
404 FileLineReader &operator=(const FileLineReader &) = delete;
405};
406
Adam Langleyd79bc9d2017-05-30 15:37:27 -0700407int FileTestMain(FileTestFunc run_test, void *arg, const char *path) {
408 FileTest::Options opts;
409 opts.callback = run_test;
410 opts.arg = arg;
411 opts.path = path;
412
413 return FileTestMain(opts);
414}
415
416int FileTestMain(const FileTest::Options &opts) {
417 std::unique_ptr<FileLineReader> reader(
418 new FileLineReader(opts.path));
David Benjamin1f1eeea2017-05-18 19:39:06 -0400419 if (!reader->is_open()) {
Adam Langleyd79bc9d2017-05-30 15:37:27 -0700420 fprintf(stderr, "Could not open file %s: %s.\n", opts.path,
421 strerror(errno));
David Benjamin06b94de2015-05-09 22:46:47 -0400422 return 1;
423 }
424
Adam Langleyd79bc9d2017-05-30 15:37:27 -0700425 FileTest t(std::move(reader), opts.comment_callback);
426
David Benjamin06b94de2015-05-09 22:46:47 -0400427 bool failed = false;
428 while (true) {
429 FileTest::ReadResult ret = t.ReadNext();
430 if (ret == FileTest::kReadError) {
431 return 1;
432 } else if (ret == FileTest::kReadEOF) {
433 break;
434 }
435
Adam Langleyd79bc9d2017-05-30 15:37:27 -0700436 bool result = opts.callback(&t, opts.arg);
David Benjamin5c694e32015-05-11 15:58:08 -0400437 if (t.HasAttribute("Error")) {
438 if (result) {
439 t.PrintLine("Operation unexpectedly succeeded.");
440 failed = true;
441 continue;
442 }
443 uint32_t err = ERR_peek_error();
444 if (ERR_reason_error_string(err) != t.GetAttributeOrDie("Error")) {
445 t.PrintLine("Unexpected error; wanted '%s', got '%s'.",
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700446 t.GetAttributeOrDie("Error").c_str(),
447 ERR_reason_error_string(err));
David Benjamin5c694e32015-05-11 15:58:08 -0400448 failed = true;
David Benjamine30a09e2016-01-01 01:17:30 -0500449 ERR_clear_error();
David Benjamin5c694e32015-05-11 15:58:08 -0400450 continue;
451 }
452 ERR_clear_error();
453 } else if (!result) {
454 // In case the test itself doesn't print output, print something so the
455 // line number is reported.
456 t.PrintLine("Test failed");
457 ERR_print_errors_fp(stderr);
David Benjamin06b94de2015-05-09 22:46:47 -0400458 failed = true;
David Benjamin5c694e32015-05-11 15:58:08 -0400459 continue;
David Benjamin06b94de2015-05-09 22:46:47 -0400460 }
461 }
462
Adam Langleyd79bc9d2017-05-30 15:37:27 -0700463 if (!opts.silent && !failed) {
Martin Kreichgauer7c125872017-04-24 13:29:11 -0700464 printf("PASS\n");
465 }
Adam Langleyd79bc9d2017-05-30 15:37:27 -0700466
467 return failed ? 1 : 0;
David Benjamin06b94de2015-05-09 22:46:47 -0400468}
Martin Kreichgauerd977eaa2017-06-26 10:16:50 -0700469
470void FileTest::SkipCurrent() {
471 ClearTest();
472}