選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

473 行
13 KiB

  1. /* 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. #include "file_test.h"
  15. #include <algorithm>
  16. #include <utility>
  17. #include <assert.h>
  18. #include <ctype.h>
  19. #include <errno.h>
  20. #include <stdarg.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <openssl/err.h>
  25. #include "../internal.h"
  26. FileTest::FileTest(std::unique_ptr<FileTest::LineReader> reader,
  27. std::function<void(const std::string &)> comment_callback)
  28. : reader_(std::move(reader)),
  29. comment_callback_(std::move(comment_callback)) {}
  30. FileTest::~FileTest() {}
  31. // FindDelimiter returns a pointer to the first '=' or ':' in |str| or nullptr
  32. // if there is none.
  33. static const char *FindDelimiter(const char *str) {
  34. while (*str) {
  35. if (*str == ':' || *str == '=') {
  36. return str;
  37. }
  38. str++;
  39. }
  40. return nullptr;
  41. }
  42. // StripSpace returns a string containing up to |len| characters from |str| with
  43. // leading and trailing whitespace removed.
  44. static std::string StripSpace(const char *str, size_t len) {
  45. // Remove leading space.
  46. while (len > 0 && isspace(*str)) {
  47. str++;
  48. len--;
  49. }
  50. while (len > 0 && isspace(str[len - 1])) {
  51. len--;
  52. }
  53. return std::string(str, len);
  54. }
  55. static std::pair<std::string, std::string> ParseKeyValue(const char *str, const size_t len) {
  56. const char *delimiter = FindDelimiter(str);
  57. std::string key, value;
  58. if (delimiter == nullptr) {
  59. key = StripSpace(str, len);
  60. } else {
  61. key = StripSpace(str, delimiter - str);
  62. value = StripSpace(delimiter + 1, str + len - delimiter - 1);
  63. }
  64. return {key, value};
  65. }
  66. FileTest::ReadResult FileTest::ReadNext() {
  67. // If the previous test had unused attributes or instructions, it is an error.
  68. if (!unused_attributes_.empty()) {
  69. for (const std::string &key : unused_attributes_) {
  70. PrintLine("Unused attribute: %s", key.c_str());
  71. }
  72. return kReadError;
  73. }
  74. if (!unused_instructions_.empty()) {
  75. for (const std::string &key : unused_instructions_) {
  76. PrintLine("Unused instruction: %s", key.c_str());
  77. }
  78. return kReadError;
  79. }
  80. ClearTest();
  81. static const size_t kBufLen = 8192 * 4;
  82. std::unique_ptr<char[]> buf(new char[kBufLen]);
  83. bool in_instruction_block = false;
  84. is_at_new_instruction_block_ = false;
  85. while (true) {
  86. // Read the next line.
  87. switch (reader_->ReadLine(buf.get(), kBufLen)) {
  88. case kReadError:
  89. fprintf(stderr, "Error reading from input at line %u.\n", line_ + 1);
  90. return kReadError;
  91. case kReadEOF:
  92. // EOF is a valid terminator for a test.
  93. return start_line_ > 0 ? kReadSuccess : kReadEOF;
  94. case kReadSuccess:
  95. break;
  96. }
  97. line_++;
  98. size_t len = strlen(buf.get());
  99. if (buf[0] == '\n' || buf[0] == '\r' || buf[0] == '\0') {
  100. // Empty lines delimit tests.
  101. if (start_line_ > 0) {
  102. return kReadSuccess;
  103. }
  104. if (in_instruction_block) {
  105. in_instruction_block = false;
  106. // Delimit instruction block from test with a blank line.
  107. current_test_ += "\r\n";
  108. }
  109. } else if (buf[0] == '#') {
  110. if (comment_callback_) {
  111. comment_callback_(buf.get());
  112. }
  113. // Otherwise ignore comments.
  114. } else if (strcmp("[B.4.2 Key Pair Generation by Testing Candidates]\r\n",
  115. buf.get()) == 0) {
  116. // The above instruction-like line is ignored because the FIPS lab's
  117. // request files are hopelessly inconsistent.
  118. } else if (buf[0] == '[') { // Inside an instruction block.
  119. is_at_new_instruction_block_ = true;
  120. if (start_line_ != 0) {
  121. // Instructions should be separate blocks.
  122. fprintf(stderr, "Line %u is an instruction in a test case.\n", line_);
  123. return kReadError;
  124. }
  125. if (!in_instruction_block) {
  126. ClearInstructions();
  127. in_instruction_block = true;
  128. }
  129. // Parse the line as an instruction ("[key = value]" or "[key]").
  130. std::string kv = StripSpace(buf.get(), len);
  131. if (kv[kv.size() - 1] != ']') {
  132. fprintf(stderr, "Line %u, invalid instruction: %s\n", line_,
  133. kv.c_str());
  134. return kReadError;
  135. }
  136. current_test_ += kv + "\r\n";
  137. kv = std::string(kv.begin() + 1, kv.end() - 1);
  138. for (;;) {
  139. size_t idx = kv.find(",");
  140. if (idx == std::string::npos) {
  141. idx = kv.size();
  142. }
  143. std::string key, value;
  144. std::tie(key, value) = ParseKeyValue(kv.c_str(), idx);
  145. instructions_[key] = value;
  146. if (idx == kv.size())
  147. break;
  148. kv = kv.substr(idx + 1);
  149. }
  150. } else {
  151. // Parsing a test case.
  152. if (in_instruction_block) {
  153. // Some NIST CAVP test files (TDES) have a test case immediately
  154. // following an instruction block, without a separate blank line, some
  155. // of the time.
  156. in_instruction_block = false;
  157. }
  158. current_test_ += std::string(buf.get(), len);
  159. std::string key, value;
  160. std::tie(key, value) = ParseKeyValue(buf.get(), len);
  161. // Duplicate keys are rewritten to have “/2”, “/3”, … suffixes.
  162. std::string mapped_key = key;
  163. for (unsigned i = 2; attributes_.count(mapped_key) != 0; i++) {
  164. char suffix[32];
  165. snprintf(suffix, sizeof(suffix), "/%u", i);
  166. suffix[sizeof(suffix)-1] = 0;
  167. mapped_key = key + suffix;
  168. }
  169. unused_attributes_.insert(mapped_key);
  170. attributes_[mapped_key] = value;
  171. if (start_line_ == 0) {
  172. // This is the start of a test.
  173. type_ = mapped_key;
  174. parameter_ = value;
  175. start_line_ = line_;
  176. for (const auto &kv : instructions_) {
  177. unused_instructions_.insert(kv.first);
  178. }
  179. }
  180. }
  181. }
  182. }
  183. void FileTest::PrintLine(const char *format, ...) {
  184. va_list args;
  185. va_start(args, format);
  186. fprintf(stderr, "Line %u: ", start_line_);
  187. vfprintf(stderr, format, args);
  188. fprintf(stderr, "\n");
  189. va_end(args);
  190. }
  191. const std::string &FileTest::GetType() {
  192. OnKeyUsed(type_);
  193. return type_;
  194. }
  195. const std::string &FileTest::GetParameter() {
  196. OnKeyUsed(type_);
  197. return parameter_;
  198. }
  199. bool FileTest::HasAttribute(const std::string &key) {
  200. OnKeyUsed(key);
  201. return attributes_.count(key) > 0;
  202. }
  203. bool FileTest::GetAttribute(std::string *out_value, const std::string &key) {
  204. OnKeyUsed(key);
  205. auto iter = attributes_.find(key);
  206. if (iter == attributes_.end()) {
  207. PrintLine("Missing attribute '%s'.", key.c_str());
  208. return false;
  209. }
  210. *out_value = iter->second;
  211. return true;
  212. }
  213. const std::string &FileTest::GetAttributeOrDie(const std::string &key) {
  214. if (!HasAttribute(key)) {
  215. abort();
  216. }
  217. return attributes_[key];
  218. }
  219. bool FileTest::HasInstruction(const std::string &key) {
  220. OnInstructionUsed(key);
  221. return instructions_.count(key) > 0;
  222. }
  223. bool FileTest::GetInstruction(std::string *out_value, const std::string &key) {
  224. OnInstructionUsed(key);
  225. auto iter = instructions_.find(key);
  226. if (iter == instructions_.end()) {
  227. PrintLine("Missing instruction '%s'.", key.c_str());
  228. return false;
  229. }
  230. *out_value = iter->second;
  231. return true;
  232. }
  233. const std::string &FileTest::CurrentTestToString() const {
  234. return current_test_;
  235. }
  236. static bool FromHexDigit(uint8_t *out, char c) {
  237. if ('0' <= c && c <= '9') {
  238. *out = c - '0';
  239. return true;
  240. }
  241. if ('a' <= c && c <= 'f') {
  242. *out = c - 'a' + 10;
  243. return true;
  244. }
  245. if ('A' <= c && c <= 'F') {
  246. *out = c - 'A' + 10;
  247. return true;
  248. }
  249. return false;
  250. }
  251. bool FileTest::GetBytes(std::vector<uint8_t> *out, const std::string &key) {
  252. std::string value;
  253. if (!GetAttribute(&value, key)) {
  254. return false;
  255. }
  256. if (value.size() >= 2 && value[0] == '"' && value[value.size() - 1] == '"') {
  257. out->assign(value.begin() + 1, value.end() - 1);
  258. return true;
  259. }
  260. if (value.size() % 2 != 0) {
  261. PrintLine("Error decoding value: %s", value.c_str());
  262. return false;
  263. }
  264. out->clear();
  265. out->reserve(value.size() / 2);
  266. for (size_t i = 0; i < value.size(); i += 2) {
  267. uint8_t hi, lo;
  268. if (!FromHexDigit(&hi, value[i]) || !FromHexDigit(&lo, value[i + 1])) {
  269. PrintLine("Error decoding value: %s", value.c_str());
  270. return false;
  271. }
  272. out->push_back((hi << 4) | lo);
  273. }
  274. return true;
  275. }
  276. static std::string EncodeHex(const uint8_t *in, size_t in_len) {
  277. static const char kHexDigits[] = "0123456789abcdef";
  278. std::string ret;
  279. ret.reserve(in_len * 2);
  280. for (size_t i = 0; i < in_len; i++) {
  281. ret += kHexDigits[in[i] >> 4];
  282. ret += kHexDigits[in[i] & 0xf];
  283. }
  284. return ret;
  285. }
  286. bool FileTest::ExpectBytesEqual(const uint8_t *expected, size_t expected_len,
  287. const uint8_t *actual, size_t actual_len) {
  288. if (expected_len == actual_len &&
  289. OPENSSL_memcmp(expected, actual, expected_len) == 0) {
  290. return true;
  291. }
  292. std::string expected_hex = EncodeHex(expected, expected_len);
  293. std::string actual_hex = EncodeHex(actual, actual_len);
  294. PrintLine("Expected: %s", expected_hex.c_str());
  295. PrintLine("Actual: %s", actual_hex.c_str());
  296. return false;
  297. }
  298. void FileTest::ClearTest() {
  299. start_line_ = 0;
  300. type_.clear();
  301. parameter_.clear();
  302. attributes_.clear();
  303. unused_attributes_.clear();
  304. current_test_ = "";
  305. }
  306. void FileTest::ClearInstructions() {
  307. instructions_.clear();
  308. unused_attributes_.clear();
  309. }
  310. void FileTest::OnKeyUsed(const std::string &key) {
  311. unused_attributes_.erase(key);
  312. }
  313. void FileTest::OnInstructionUsed(const std::string &key) {
  314. unused_instructions_.erase(key);
  315. }
  316. bool FileTest::IsAtNewInstructionBlock() const {
  317. return is_at_new_instruction_block_;
  318. }
  319. void FileTest::InjectInstruction(const std::string &key,
  320. const std::string &value) {
  321. instructions_[key] = value;
  322. }
  323. class FileLineReader : public FileTest::LineReader {
  324. public:
  325. explicit FileLineReader(const char *path) : file_(fopen(path, "r")) {}
  326. ~FileLineReader() override {
  327. if (file_ != nullptr) {
  328. fclose(file_);
  329. }
  330. }
  331. // is_open returns true if the file was successfully opened.
  332. bool is_open() const { return file_ != nullptr; }
  333. FileTest::ReadResult ReadLine(char *out, size_t len) override {
  334. assert(len > 0);
  335. if (file_ == nullptr) {
  336. return FileTest::kReadError;
  337. }
  338. if (fgets(out, len, file_) == nullptr) {
  339. return feof(file_) ? FileTest::kReadEOF : FileTest::kReadError;
  340. }
  341. if (strlen(out) == len - 1 && out[len - 2] != '\n' && !feof(file_)) {
  342. fprintf(stderr, "Line too long.\n");
  343. return FileTest::kReadError;
  344. }
  345. return FileTest::kReadSuccess;
  346. }
  347. private:
  348. FILE *file_;
  349. FileLineReader(const FileLineReader &) = delete;
  350. FileLineReader &operator=(const FileLineReader &) = delete;
  351. };
  352. int FileTestMain(FileTestFunc run_test, void *arg, const char *path) {
  353. FileTest::Options opts;
  354. opts.callback = run_test;
  355. opts.arg = arg;
  356. opts.path = path;
  357. return FileTestMain(opts);
  358. }
  359. int FileTestMain(const FileTest::Options &opts) {
  360. std::unique_ptr<FileLineReader> reader(
  361. new FileLineReader(opts.path));
  362. if (!reader->is_open()) {
  363. fprintf(stderr, "Could not open file %s: %s.\n", opts.path,
  364. strerror(errno));
  365. return 1;
  366. }
  367. FileTest t(std::move(reader), opts.comment_callback);
  368. bool failed = false;
  369. while (true) {
  370. FileTest::ReadResult ret = t.ReadNext();
  371. if (ret == FileTest::kReadError) {
  372. return 1;
  373. } else if (ret == FileTest::kReadEOF) {
  374. break;
  375. }
  376. bool result = opts.callback(&t, opts.arg);
  377. if (t.HasAttribute("Error")) {
  378. if (result) {
  379. t.PrintLine("Operation unexpectedly succeeded.");
  380. failed = true;
  381. continue;
  382. }
  383. uint32_t err = ERR_peek_error();
  384. if (ERR_reason_error_string(err) != t.GetAttributeOrDie("Error")) {
  385. t.PrintLine("Unexpected error; wanted '%s', got '%s'.",
  386. t.GetAttributeOrDie("Error").c_str(),
  387. ERR_reason_error_string(err));
  388. failed = true;
  389. ERR_clear_error();
  390. continue;
  391. }
  392. ERR_clear_error();
  393. } else if (!result) {
  394. // In case the test itself doesn't print output, print something so the
  395. // line number is reported.
  396. t.PrintLine("Test failed");
  397. ERR_print_errors_fp(stderr);
  398. failed = true;
  399. continue;
  400. }
  401. }
  402. if (!opts.silent && !failed) {
  403. printf("PASS\n");
  404. }
  405. return failed ? 1 : 0;
  406. }
  407. void FileTest::SkipCurrent() {
  408. ClearTest();
  409. }