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 "test_util.h"
16
17 #include <ostream>
18
19 #include <openssl/err.h>
20
21 #include "../internal.h"
22
23
hexdump(FILE * fp,const char * msg,const void * in,size_t len)24 void hexdump(FILE *fp, const char *msg, const void *in, size_t len) {
25 const uint8_t *data = reinterpret_cast<const uint8_t*>(in);
26
27 fputs(msg, fp);
28 for (size_t i = 0; i < len; i++) {
29 fprintf(fp, "%02x", data[i]);
30 }
31 fputs("\n", fp);
32 }
33
operator <<(std::ostream & os,const Bytes & in)34 std::ostream &operator<<(std::ostream &os, const Bytes &in) {
35 if (in.span_.empty()) {
36 return os << "<empty Bytes>";
37 }
38
39 // Print a byte slice as hex.
40 os << EncodeHex(in.span_);
41 return os;
42 }
43
DecodeHex(std::vector<uint8_t> * out,const std::string & in)44 bool DecodeHex(std::vector<uint8_t> *out, const std::string &in) {
45 out->clear();
46 if (in.size() % 2 != 0) {
47 return false;
48 }
49 out->reserve(in.size() / 2);
50 for (size_t i = 0; i < in.size(); i += 2) {
51 uint8_t hi, lo;
52 if (!OPENSSL_fromxdigit(&hi, in[i]) ||
53 !OPENSSL_fromxdigit(&lo, in[i + 1])) {
54 return false;
55 }
56 out->push_back((hi << 4) | lo);
57 }
58 return true;
59 }
60
EncodeHex(bssl::Span<const uint8_t> in)61 std::string EncodeHex(bssl::Span<const uint8_t> in) {
62 static const char kHexDigits[] = "0123456789abcdef";
63 std::string ret;
64 ret.reserve(in.size() * 2);
65 for (uint8_t b : in) {
66 ret += kHexDigits[b >> 4];
67 ret += kHexDigits[b & 0xf];
68 }
69 return ret;
70 }
71
ErrorEquals(uint32_t err,int lib,int reason)72 testing::AssertionResult ErrorEquals(uint32_t err, int lib, int reason) {
73 if (ERR_GET_LIB(err) == lib && ERR_GET_REASON(err) == reason) {
74 return testing::AssertionSuccess();
75 }
76
77 char buf[128], expected[128];
78 return testing::AssertionFailure()
79 << "Got \"" << ERR_error_string_n(err, buf, sizeof(buf))
80 << "\", wanted \""
81 << ERR_error_string_n(ERR_PACK(lib, reason), expected,
82 sizeof(expected))
83 << "\"";
84 }
85