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 
15 #include "file_test.h"
16 
17 #include <memory>
18 
19 #include <ctype.h>
20 #include <errno.h>
21 #include <stdarg.h>
22 #include <stdlib.h>
23 #include <string.h>
24 
25 #include <openssl/err.h>
26 
27 #include "../internal.h"
28 
29 
FileTest(const char * path)30 FileTest::FileTest(const char *path) {
31   file_ = fopen(path, "r");
32   if (file_ == nullptr) {
33     fprintf(stderr, "Could not open file %s: %s.\n", path, strerror(errno));
34   }
35 }
36 
~FileTest()37 FileTest::~FileTest() {
38   if (file_ != nullptr) {
39     fclose(file_);
40   }
41 }
42 
43 // FindDelimiter returns a pointer to the first '=' or ':' in |str| or nullptr
44 // if there is none.
FindDelimiter(const char * str)45 static const char *FindDelimiter(const char *str) {
46   while (*str) {
47     if (*str == ':' || *str == '=') {
48       return str;
49     }
50     str++;
51   }
52   return nullptr;
53 }
54 
55 // StripSpace returns a string containing up to |len| characters from |str| with
56 // leading and trailing whitespace removed.
StripSpace(const char * str,size_t len)57 static std::string StripSpace(const char *str, size_t len) {
58   // Remove leading space.
59   while (len > 0 && isspace(*str)) {
60     str++;
61     len--;
62   }
63   while (len > 0 && isspace(str[len-1])) {
64     len--;
65   }
66   return std::string(str, len);
67 }
68 
ReadNext()69 FileTest::ReadResult FileTest::ReadNext() {
70   // If the previous test had unused attributes, it is an error.
71   if (!unused_attributes_.empty()) {
72     for (const std::string &key : unused_attributes_) {
73       PrintLine("Unused attribute: %s", key.c_str());
74     }
75     return kReadError;
76   }
77 
78   ClearTest();
79 
80   static const size_t kBufLen = 64 + 8192*2;
81   std::unique_ptr<char[]> buf(new char[kBufLen]);
82 
83   while (true) {
84     // Read the next line.
85     if (fgets(buf.get(), kBufLen, file_) == nullptr) {
86       if (feof(file_)) {
87         // EOF is a valid terminator for a test.
88         return start_line_ > 0 ? kReadSuccess : kReadEOF;
89       }
90       fprintf(stderr, "Error reading from input.\n");
91       return kReadError;
92     }
93 
94     line_++;
95     size_t len = strlen(buf.get());
96     // Check for truncation.
97     if (len > 0 && buf[len - 1] != '\n' && !feof(file_)) {
98       fprintf(stderr, "Line %u too long.\n", line_);
99       return kReadError;
100     }
101 
102     if (buf[0] == '\n' || buf[0] == '\0') {
103       // Empty lines delimit tests.
104       if (start_line_ > 0) {
105         return kReadSuccess;
106       }
107     } else if (buf[0] != '#') {  // Comment lines are ignored.
108       // Parse the line as an attribute.
109       const char *delimiter = FindDelimiter(buf.get());
110       if (delimiter == nullptr) {
111         fprintf(stderr, "Line %u: Could not parse attribute.\n", line_);
112         return kReadError;
113       }
114       std::string key = StripSpace(buf.get(), delimiter - buf.get());
115       std::string value = StripSpace(delimiter + 1,
116                                      buf.get() + len - delimiter - 1);
117 
118       unused_attributes_.insert(key);
119       attributes_[key] = value;
120       if (start_line_ == 0) {
121         // This is the start of a test.
122         type_ = key;
123         parameter_ = value;
124         start_line_ = line_;
125       }
126     }
127   }
128 }
129 
PrintLine(const char * format,...)130 void FileTest::PrintLine(const char *format, ...) {
131   va_list args;
132   va_start(args, format);
133 
134   fprintf(stderr, "Line %u: ", start_line_);
135   vfprintf(stderr, format, args);
136   fprintf(stderr, "\n");
137 
138   va_end(args);
139 }
140 
GetType()141 const std::string &FileTest::GetType() {
142   OnKeyUsed(type_);
143   return type_;
144 }
145 
GetParameter()146 const std::string &FileTest::GetParameter() {
147   OnKeyUsed(type_);
148   return parameter_;
149 }
150 
HasAttribute(const std::string & key)151 bool FileTest::HasAttribute(const std::string &key) {
152   OnKeyUsed(key);
153   return attributes_.count(key) > 0;
154 }
155 
GetAttribute(std::string * out_value,const std::string & key)156 bool FileTest::GetAttribute(std::string *out_value, const std::string &key) {
157   OnKeyUsed(key);
158   auto iter = attributes_.find(key);
159   if (iter == attributes_.end()) {
160     PrintLine("Missing attribute '%s'.", key.c_str());
161     return false;
162   }
163   *out_value = iter->second;
164   return true;
165 }
166 
GetAttributeOrDie(const std::string & key)167 const std::string &FileTest::GetAttributeOrDie(const std::string &key) {
168   if (!HasAttribute(key)) {
169     abort();
170   }
171   return attributes_[key];
172 }
173 
FromHexDigit(uint8_t * out,char c)174 static bool FromHexDigit(uint8_t *out, char c) {
175   if ('0' <= c && c <= '9') {
176     *out = c - '0';
177     return true;
178   }
179   if ('a' <= c && c <= 'f') {
180     *out = c - 'a' + 10;
181     return true;
182   }
183   if ('A' <= c && c <= 'F') {
184     *out = c - 'A' + 10;
185     return true;
186   }
187   return false;
188 }
189 
GetBytes(std::vector<uint8_t> * out,const std::string & key)190 bool FileTest::GetBytes(std::vector<uint8_t> *out, const std::string &key) {
191   std::string value;
192   if (!GetAttribute(&value, key)) {
193     return false;
194   }
195 
196   if (value.size() >= 2 && value[0] == '"' && value[value.size() - 1] == '"') {
197     out->assign(value.begin() + 1, value.end() - 1);
198     return true;
199   }
200 
201   if (value.size() % 2 != 0) {
202     PrintLine("Error decoding value: %s", value.c_str());
203     return false;
204   }
205   out->clear();
206   out->reserve(value.size() / 2);
207   for (size_t i = 0; i < value.size(); i += 2) {
208     uint8_t hi, lo;
209     if (!FromHexDigit(&hi, value[i]) || !FromHexDigit(&lo, value[i+1])) {
210       PrintLine("Error decoding value: %s", value.c_str());
211       return false;
212     }
213     out->push_back((hi << 4) | lo);
214   }
215   return true;
216 }
217 
EncodeHex(const uint8_t * in,size_t in_len)218 static std::string EncodeHex(const uint8_t *in, size_t in_len) {
219   static const char kHexDigits[] = "0123456789abcdef";
220   std::string ret;
221   ret.reserve(in_len * 2);
222   for (size_t i = 0; i < in_len; i++) {
223     ret += kHexDigits[in[i] >> 4];
224     ret += kHexDigits[in[i] & 0xf];
225   }
226   return ret;
227 }
228 
ExpectBytesEqual(const uint8_t * expected,size_t expected_len,const uint8_t * actual,size_t actual_len)229 bool FileTest::ExpectBytesEqual(const uint8_t *expected, size_t expected_len,
230                                 const uint8_t *actual, size_t actual_len) {
231   if (expected_len == actual_len &&
232       OPENSSL_memcmp(expected, actual, expected_len) == 0) {
233     return true;
234   }
235 
236   std::string expected_hex = EncodeHex(expected, expected_len);
237   std::string actual_hex = EncodeHex(actual, actual_len);
238   PrintLine("Expected: %s", expected_hex.c_str());
239   PrintLine("Actual:   %s", actual_hex.c_str());
240   return false;
241 }
242 
ClearTest()243 void FileTest::ClearTest() {
244   start_line_ = 0;
245   type_.clear();
246   parameter_.clear();
247   attributes_.clear();
248   unused_attributes_.clear();
249 }
250 
OnKeyUsed(const std::string & key)251 void FileTest::OnKeyUsed(const std::string &key) {
252   unused_attributes_.erase(key);
253 }
254 
FileTestMain(bool (* run_test)(FileTest * t,void * arg),void * arg,const char * path)255 int FileTestMain(bool (*run_test)(FileTest *t, void *arg), void *arg,
256                  const char *path) {
257   FileTest t(path);
258   if (!t.is_open()) {
259     return 1;
260   }
261 
262   bool failed = false;
263   while (true) {
264     FileTest::ReadResult ret = t.ReadNext();
265     if (ret == FileTest::kReadError) {
266       return 1;
267     } else if (ret == FileTest::kReadEOF) {
268       break;
269     }
270 
271     bool result = run_test(&t, arg);
272     if (t.HasAttribute("Error")) {
273       if (result) {
274         t.PrintLine("Operation unexpectedly succeeded.");
275         failed = true;
276         continue;
277       }
278       uint32_t err = ERR_peek_error();
279       if (ERR_reason_error_string(err) != t.GetAttributeOrDie("Error")) {
280         t.PrintLine("Unexpected error; wanted '%s', got '%s'.",
281                      t.GetAttributeOrDie("Error").c_str(),
282                      ERR_reason_error_string(err));
283         failed = true;
284         ERR_clear_error();
285         continue;
286       }
287       ERR_clear_error();
288     } else if (!result) {
289       // In case the test itself doesn't print output, print something so the
290       // line number is reported.
291       t.PrintLine("Test failed");
292       ERR_print_errors_fp(stderr);
293       failed = true;
294       continue;
295     }
296   }
297 
298   if (failed) {
299     return 1;
300   }
301 
302   printf("PASS\n");
303   return 0;
304 }
305