1// Copyright (c) 2012 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#include "net/cert/test_root_certs.h" 6 7#include <string> 8 9#include "base/file_util.h" 10#include "base/files/file_path.h" 11#include "base/logging.h" 12#include "net/cert/x509_certificate.h" 13 14namespace net { 15 16namespace { 17 18bool g_has_instance = false; 19 20base::LazyInstance<TestRootCerts>::Leaky 21 g_test_root_certs = LAZY_INSTANCE_INITIALIZER; 22 23CertificateList LoadCertificates(const base::FilePath& filename) { 24 std::string raw_cert; 25 if (!base::ReadFileToString(filename, &raw_cert)) { 26 LOG(ERROR) << "Can't load certificate " << filename.value(); 27 return CertificateList(); 28 } 29 30 return X509Certificate::CreateCertificateListFromBytes( 31 raw_cert.data(), raw_cert.length(), X509Certificate::FORMAT_AUTO); 32} 33 34} // namespace 35 36// static 37TestRootCerts* TestRootCerts::GetInstance() { 38 return g_test_root_certs.Pointer(); 39} 40 41bool TestRootCerts::HasInstance() { 42 return g_has_instance; 43} 44 45bool TestRootCerts::AddFromFile(const base::FilePath& file) { 46 CertificateList root_certs = LoadCertificates(file); 47 if (root_certs.empty() || root_certs.size() > 1) 48 return false; 49 50 return Add(root_certs.front().get()); 51} 52 53TestRootCerts::TestRootCerts() { 54 Init(); 55 g_has_instance = true; 56} 57 58ScopedTestRoot::ScopedTestRoot() {} 59 60ScopedTestRoot::ScopedTestRoot(X509Certificate* cert) { 61 Reset(cert); 62} 63 64ScopedTestRoot::~ScopedTestRoot() { 65 Reset(NULL); 66} 67 68void ScopedTestRoot::Reset(X509Certificate* cert) { 69 if (cert_.get()) 70 TestRootCerts::GetInstance()->Clear(); 71 if (cert) 72 TestRootCerts::GetInstance()->Add(cert); 73 cert_ = cert; 74} 75 76} // namespace net 77