summaryrefslogtreecommitdiffstats
path: root/src/lib/dns/base64.cc
blob: f1082452b88071f98455b43774e19e2ab371e557 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

// $Id$

#include <stdint.h>
#include <cassert>
#include <iterator>
#include <string>
#include <vector>

#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>

#include <exceptions/exceptions.h>

#include <dns/base64.h>

using namespace std;
using namespace boost::archive::iterators;

namespace isc {
namespace dns {

namespace {
const char BASE64_PADDING_CHAR = '=';
const uint8_t BINARY_ZERO_CODE = 0;
  
class BinaryNormalizer : public iterator<input_iterator_tag, uint8_t> {
public:
    BinaryNormalizer(const vector<uint8_t>::const_iterator& base,
                     const vector<uint8_t>::const_iterator& base_end) :
        base_(base), base_end_(base_end), in_pad_(false)
    {}
    BinaryNormalizer& operator++()
    {
        if (!in_pad_) {
            ++base_;
        }
        if (base_ == base_end_) {
            in_pad_ = true;
        }
        return (*this);
    }
    const uint8_t& operator*() const {
        if (in_pad_) {
            return (BINARY_ZERO_CODE);
        } else {
            return (*base_);
        }
    }
    bool operator==(const BinaryNormalizer& other) const
    {
        return (base_ == other.base_);
    }
private:
    vector<uint8_t>::const_iterator base_;
    const vector<uint8_t>::const_iterator base_end_;
    bool in_pad_;
};

typedef
base64_from_binary<transform_width<BinaryNormalizer, 6, 8> > base64_encoder;
} // end of anonymous namespace

string
encodeBase64(const vector<uint8_t>& binary)
{
    // calculate the resulting length.  it's the smallest multiple of 4
    // equal to or larger than 4/3 * original data length.
    size_t len = ((binary.size() * 4 / 3) + 3) & ~3;

    string base64;
    base64.reserve(len);
    base64.assign(base64_encoder(BinaryNormalizer(binary.begin(),
                                                  binary.end())),
                  base64_encoder(BinaryNormalizer(binary.end(), binary.end())));
    assert(len >= base64.length());
    base64.append(len - base64.length(), BASE64_PADDING_CHAR);
    return (base64);
}

namespace {
const size_t BASE64_MAX_PADDING_CHARS = 2;
const char BASE64_ZERO_CODE = 'A'; // correspond to 000000(2)

class Base64Normalizer : public iterator<input_iterator_tag, char> {
public:
    Base64Normalizer(const string::const_iterator& base,
                     const string::const_iterator& base_beginpad,
                     const string::const_iterator& base_end) :
        base_(base), base_beginpad_(base_beginpad), base_end_(base_end),
        in_pad_(false)
    {}
    Base64Normalizer& operator++()
    {
        ++base_;
        while (base_ != base_end_ && isspace(*base_)) {
            ++base_;
        }
        if (base_ == base_beginpad_) {
            in_pad_ = true;
        }
        return (*this);
    }
    const char& operator*() const {
        if (in_pad_ && *base_ == BASE64_PADDING_CHAR) {
            return (BASE64_ZERO_CODE);
        } else {
            return (*base_);
        }
    }
    bool operator==(const Base64Normalizer& other) const
    {
        return (base_ == other.base_);
    }
private:
    string::const_iterator base_;
    const string::const_iterator base_beginpad_;
    const string::const_iterator base_end_;
    bool in_pad_;
};

typedef
transform_width<binary_from_base64<Base64Normalizer, char>, 8, 6, char>
base64_decoder;
} // end of anonymous namespace

void
decodeBase64(const string& base64, vector<uint8_t>& result)
{
    // enumerate the number of trailing padding characters (=), ignoring
    // white spaces.  since base64_from_binary doesn't accept padding,
    // we handle it explicitly.
    size_t padlen = 0;
    string::const_reverse_iterator srit = base64.rbegin();
    string::const_reverse_iterator srit_end = base64.rend();
    while (srit != srit_end) {
        char ch = *srit;
        if (ch == BASE64_PADDING_CHAR) {
            if (++padlen > BASE64_MAX_PADDING_CHARS) {
                isc_throw(BadBase64String,
                          "Too many Base64 padding characters");
            }
        } else if (!isspace(ch)) {
            break;
        }
        ++srit;
    }

    try {
        result.assign(base64_decoder(Base64Normalizer(base64.begin(),
                                                      srit.base(),
                                                      base64.end())),
                      base64_decoder(Base64Normalizer(base64.end(),
                                                      base64.end(),
                                                      base64.end())));
    } catch (dataflow_exception& ex) {
        isc_throw(BadBase64String, ex.what());
    }

    // Confirm the original base64 text is the canonical encoding of the
    // data.
    assert(result.size() >= padlen);
    vector<uint8_t>::const_reverse_iterator rit = result.rbegin();
    for (int i = 0; i < padlen; ++i, ++rit) {
        if (*rit != 0) {
            isc_throw(BadBase64String, "Non 0 bits included in padding");
        }
    }

    // strip the padded zero-bit fields
    result.resize(result.size() - padlen);
}

}
}