1// Copyright (c) 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef NET_CERT_PEM_TOKENIZER_H_
6#define NET_CERT_PEM_TOKENIZER_H_
7
8#include <stddef.h>
9
10#include <string>
11#include <vector>
12
13#include "base/macros.h"
14#include "base/strings/string_piece.h"
15#include "net/base/net_export.h"
16
17namespace net {
18
19// PEMTokenizer is a utility class for the parsing of data encapsulated
20// using RFC 1421, Privacy Enhancement for Internet Electronic Mail. It
21// does not implement the full specification, most notably it does not
22// support the Encapsulated Header Portion described in Section 4.4.
23class NET_EXPORT_PRIVATE PEMTokenizer {
24 public:
25 // Create a new PEMTokenizer that iterates through |str| searching for
26 // instances of PEM encoded blocks that are of the |allowed_block_types|.
27 // |str| must remain valid for the duration of the PEMTokenizer.
28 PEMTokenizer(const base::StringPiece& str,
29 const std::vector<std::string>& allowed_block_types);
30 ~PEMTokenizer();
31
32 // Attempts to decode the next PEM block in the string. Returns false if no
33 // PEM blocks can be decoded. The decoded PEM block will be available via
34 // data().
35 bool GetNext();
36
37 // Returns the PEM block type (eg: CERTIFICATE) of the last successfully
38 // decoded PEM block.
39 // GetNext() must have returned true before calling this method.
40 const std::string& block_type() const { return block_type_; }
41
42 // Returns the raw, Base64-decoded data of the last successfully decoded
43 // PEM block.
44 // GetNext() must have returned true before calling this method.
45 const std::string& data() const { return data_; }
46
47 private:
48 void Init(const base::StringPiece& str,
49 const std::vector<std::string>& allowed_block_types);
50
51 // A simple cache of the allowed PEM header and footer for a given PEM
52 // block type, so that it is only computed once.
53 struct PEMType;
54
55 // The string to search, which must remain valid for as long as this class
56 // is around.
57 base::StringPiece str_;
58
59 // The current position within |str_| that searching should begin from,
60 // or StringPiece::npos if iteration is complete
61 base::StringPiece::size_type pos_;
62
63 // The type of data that was encoded, as indicated in the PEM
64 // Pre-Encapsulation Boundary (eg: CERTIFICATE, PKCS7, or
65 // PRIVACY-ENHANCED MESSAGE).
66 std::string block_type_;
67
68 // The types of PEM blocks that are allowed. PEM blocks that are not of
69 // one of these types will be skipped.
70 std::vector<PEMType> block_types_;
71
72 // The raw (Base64-decoded) data of the last successfully decoded block.
73 std::string data_;
74
75 DISALLOW_COPY_AND_ASSIGN(PEMTokenizer);
76};
77
78} // namespace net
79
80#endif // NET_CERT_PEM_TOKENIZER_H_
81