blob: 031df254928dc092635ea263479ea60c3ae5bd38 [file] [log] [blame]
Steve DiBenedettoc07b3a22014-03-19 12:32:52 -06001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (C) 2014 Named Data Networking Project
4 * See COPYING for copyright and distribution information.
5 */
6
7
8#include "config-file.hpp"
9
10#include <boost/property_tree/ini_parser.hpp>
11#include <boost/filesystem.hpp>
12
13namespace ndn {
14
15ConfigFile::ConfigFile()
16 : m_path(findConfigFile())
17{
18 if (open())
19 {
20 parse();
21 close();
22 }
23}
24
25ConfigFile::~ConfigFile()
26{
27 if (m_input.is_open())
28 {
29 m_input.close();
30 }
31}
32
33boost::filesystem::path
34ConfigFile::findConfigFile()
35{
36 using namespace boost::filesystem;
37
38 path home(std::getenv("HOME"));
39 if (!home.empty())
40 {
41 home /= ".ndn/client.conf";
42 if (exists(home))
43 {
44 return absolute(home);
45 }
46 }
47
48#ifdef NDN_CPP_SYSCONFDIR
49 path sysconfdir(NDN_CPP_SYSCONFDIR);
50 sysconfdir /= "ndn/client.conf";
51
52 if (exists(sysconfdir))
53 {
54 return absolute(sysconfdir);
55 }
56#endif // NDN_CPP_SYSCONFDIR
57
58 path etc("/etc/ndn/client.conf");
59 if (exists(etc))
60 {
61 return absolute(etc);
62 }
63
64 return path();
65}
66
67
68
69bool
70ConfigFile::open()
71{
72 if (m_path.empty())
73 {
74 return false;
75 }
76
77 m_input.open(m_path.c_str());
78 if (!m_input.good() || !m_input.is_open())
79 {
80 return false;
81 }
82 return true;
83}
84
85void
86ConfigFile::close()
87{
88 if (m_input.is_open())
89 {
90 m_input.close();
91 }
92}
93
94
95const ConfigFile::Parsed&
96ConfigFile::parse()
97{
98 if (m_path.empty())
99 {
100 throw Error("Failed to locate configuration file for parsing");
101 }
102 else if (!m_input.is_open() && !open())
103 {
104 throw Error("Failed to open configuration file for parsing");
105 }
106
107 try
108 {
109 boost::property_tree::read_ini(m_input, m_config);
110 }
111 catch (const boost::property_tree::ini_parser_error& error)
112 {
113 std::stringstream msg;
114 msg << "Failed to parse configuration file";
115 msg << " " << m_path;
116 msg << " " << error.message() << " line " << error.line();
117 throw Error(msg.str());
118 }
119 return m_config;
120}
121
122}
123