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