blob: 03ea1361aded6bdeeafecaf9a1959017bec21359 [file] [log] [blame]
Darin Petkov3c5e4dc2012-04-02 14:44:27 +02001// Copyright (c) 2012 The Chromium OS 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 "shill/nss.h"
6
Darin Petkov3c5e4dc2012-04-02 14:44:27 +02007#include <base/string_number_conversions.h>
8#include <base/string_util.h>
9#include <base/stringprintf.h>
10
11#include "shill/glib.h"
Christopher Wileyb691efd2012-08-09 13:51:51 -070012#include "shill/logging.h"
Darin Petkov3c5e4dc2012-04-02 14:44:27 +020013
14using base::HexEncode;
15using base::StringPrintf;
16using std::string;
17using std::vector;
18
19namespace shill {
20
21namespace {
Ben Chanbbdef5f2012-04-23 13:58:15 -070022base::LazyInstance<NSS> g_nss = LAZY_INSTANCE_INITIALIZER;
Darin Petkov3c5e4dc2012-04-02 14:44:27 +020023const char kCertfileBasename[] = "/tmp/nss-cert.";
24const char kNSSGetCertScript[] = SCRIPTDIR "/nss-get-cert";
25} // namespace
26
Darin Petkov3c5e4dc2012-04-02 14:44:27 +020027NSS::NSS()
28 : glib_(NULL) {
Ben Chanfad4a0b2012-04-18 15:49:59 -070029 SLOG(Crypto, 2) << __func__;
Darin Petkov3c5e4dc2012-04-02 14:44:27 +020030}
31
32NSS::~NSS() {
Ben Chanfad4a0b2012-04-18 15:49:59 -070033 SLOG(Crypto, 2) << __func__;
Darin Petkov3c5e4dc2012-04-02 14:44:27 +020034}
35
36// static
37NSS *NSS::GetInstance() {
38 return g_nss.Pointer();
39}
40
41void NSS::Init(GLib *glib) {
42 glib_ = glib;
43}
44
45FilePath NSS::GetPEMCertfile(const string &nickname, const vector<char> &id) {
46 return GetCertfile(nickname, id, "pem");
47}
48
49FilePath NSS::GetDERCertfile(const string &nickname, const vector<char> &id) {
50 return GetCertfile(nickname, id, "der");
51}
52
53FilePath NSS::GetCertfile(
54 const string &nickname, const vector<char> &id, const string &type) {
55 CHECK(glib_);
56 string filename =
57 kCertfileBasename + StringToLowerASCII(HexEncode(&id[0], id.size()));
58 char *argv[] = {
59 const_cast<char *>(kNSSGetCertScript),
60 const_cast<char *>(nickname.c_str()),
61 const_cast<char *>(type.c_str()),
62 const_cast<char *>(filename.c_str()),
63 NULL
64 };
Darin Petkove2c3d112012-04-17 12:20:15 +020065 char *envp[1] = { NULL };
Darin Petkov3c5e4dc2012-04-02 14:44:27 +020066 int status = 0;
67 GError *error = NULL;
68 if (!glib_->SpawnSync(NULL,
69 argv,
Darin Petkove2c3d112012-04-17 12:20:15 +020070 envp,
Darin Petkov3c5e4dc2012-04-02 14:44:27 +020071 static_cast<GSpawnFlags>(0),
72 NULL,
73 NULL,
74 NULL,
75 NULL,
76 &status,
77 &error)) {
78 LOG(ERROR) << "nss-get-cert failed: "
79 << glib_->ConvertErrorToMessage(error);
80 return FilePath();
81 }
82 if (!WIFEXITED(status) || WEXITSTATUS(status)) {
83 LOG(ERROR) << "nss-get-cert failed, status=" << status;
84 return FilePath();
85 }
86 return FilePath(filename);
87}
88
89} // namespace shill