Changeset - ddec6a8e1ac5
[Not reviewed]
0 5 0
Jan Kaluza - 13 years ago 2012-05-30 11:14:56
hanzz.k@gmail.com
removed Config::getUnregistered. CONFIG_* macros should be used instead even for unregistered options
5 files changed with 19 insertions and 14 deletions:
0 comments (0 inline, 0 general)
backends/libcommuni/main.cpp
Show inline comments
 
/*
 
 * Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
 
 *
 
 * This example is free, and not covered by LGPL license. There is no
 
 * restriction applied to their modification, redistribution, using and so on.
 
 * You can study them, modify them, use them in your own program - either
 
 * completely or partially. By using it you may give me some credits in your
 
 * program, but you don't have to.
 
 */
 

	
 
#include "transport/config.h"
 
#include "transport/networkplugin.h"
 
#include "transport/logging.h"
 
#include "session.h"
 
#include <QtCore>
 
#include <QtNetwork>
 
#include "Swiften/EventLoop/Qt/QtEventLoop.h"
 
#include "ircnetworkplugin.h"
 
#include "singleircnetworkplugin.h"
 

	
 
using namespace boost::program_options;
 
using namespace Transport;
 

	
 
NetworkPlugin * np = NULL;
 

	
 
int main (int argc, char* argv[]) {
 
	std::string host;
 
	int port;
 

	
 

	
 
	boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <config_file.cfg>\nAllowed options");
 
	desc.add_options()
 
		("host,h", value<std::string>(&host), "host")
 
		("port,p", value<int>(&port), "port")
 
		;
 
	try
 
	{
 
		boost::program_options::variables_map vm;
 
		boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
 
		boost::program_options::notify(vm);
 
	}
 
	catch (std::runtime_error& e)
 
	{
 
		std::cout << desc << "\n";
 
		exit(1);
 
	}
 
	catch (...)
 
	{
 
		std::cout << desc << "\n";
 
		exit(1);
 
	}
 

	
 

	
 
	if (argc < 5) {
 
		qDebug("Usage: %s <config>", argv[0]);
 
		return 1;
 
	}
 

	
 
// 	QStringList channels;
 
// 	for (int i = 3; i < argc; ++i)
 
// 	{
 
// 		channels.append(argv[i]);
 
// 	}
 
// 
 
// 	MyIrcSession session;
 
// 	session.setNick(argv[2]);
 
// 	session.setAutoJoinChannels(channels);
 
// 	session.connectToServer(argv[1], 6667);
 

	
 
	Config config;
 
	if (!config.load(argv[5])) {
 
		std::cerr << "Can't open " << argv[1] << " configuration file.\n";
 
		return 1;
 
	}
 
	QCoreApplication app(argc, argv);
 

	
 
	Logging::initBackendLogging(&config);
 

	
 
	Swift::QtEventLoop eventLoop;
 

	
 
	if (config.getUnregistered().find("service.irc_server") == config.getUnregistered().end()) {
 
	if (!CONFIG_HAS_KEY(&config, "service.irc_server")) {
 
		np = new IRCNetworkPlugin(&config, &eventLoop, host, port);
 
	}
 
	else {
 
		np = new SingleIRCNetworkPlugin(&config, &eventLoop, host, port);
 
	}
 

	
 
	return app.exec();
 
}
backends/libcommuni/singleircnetworkplugin.cpp
Show inline comments
 
#include "singleircnetworkplugin.h"
 
#include "transport/logging.h"
 
#include <IrcCommand>
 
#include <IrcMessage>
 

	
 
#define FROM_UTF8(WHAT) QString::fromUtf8((WHAT).c_str(), (WHAT).size())
 
#define TO_UTF8(WHAT) std::string((WHAT).toUtf8().data(), (WHAT).toUtf8().size())
 

	
 
DEFINE_LOGGER(logger, "SingleIRCNetworkPlugin");
 

	
 
SingleIRCNetworkPlugin::SingleIRCNetworkPlugin(Config *config, Swift::QtEventLoop *loop, const std::string &host, int port) {
 
	this->config = config;
 
	m_server = config->getUnregistered().find("service.irc_server")->second;
 
	if (CONFIG_HAS_KEY(config, "service.irc_server")) {
 
		m_server = CONFIG_STRING(config, "service.irc_server");
 
	}
 
	else {
 
		LOG4CXX_ERROR(logger, "No [service] irc_server defined, exiting...");
 
		exit(-1);
 
	}
 
	m_socket = new QTcpSocket();
 
	m_socket->connectToHost(FROM_UTF8(host), port);
 
	connect(m_socket, SIGNAL(readyRead()), this, SLOT(readData()));
 

	
 
	if (config->getUnregistered().find("service.irc_identify") != config->getUnregistered().end()) {
 
		m_identify = config->getUnregistered().find("service.irc_identify")->second;
 
	if (CONFIG_HAS_KEY(config, "service.irc_identify")) {
 
		m_identify = CONFIG_STRING(config, "service.irc_identify");
 
	}
 
	else {
 
		m_identify = "NickServ identify $name $password";
 
	}
 

	
 
	LOG4CXX_INFO(logger, "SingleIRCNetworkPlugin for server " << m_server << " initialized.");
 
}
 

	
 
void SingleIRCNetworkPlugin::readData() {
 
	size_t availableBytes = m_socket->bytesAvailable();
 
	if (availableBytes == 0)
 
		return;
 

	
 
	std::string d = std::string(m_socket->readAll().data(), availableBytes);
 
	handleDataRead(d);
 
}
 

	
 
void SingleIRCNetworkPlugin::sendData(const std::string &string) {
 
	m_socket->write(string.c_str(), string.size());
 
}
 

	
 
void SingleIRCNetworkPlugin::handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
	// legacy name is users nickname
 
	if (m_sessions[user] != NULL) {
 
		LOG4CXX_WARN(logger, user << ": Already logged in.");
 
		return;
 
	}
 
	LOG4CXX_INFO(logger, user << ": Connecting " << m_server << " as " << legacyName);
 

	
 
	MyIrcSession *session = new MyIrcSession(user, this);
 
	session->setUserName(FROM_UTF8(legacyName));
 
	session->setNickName(FROM_UTF8(legacyName));
 
	session->setRealName(FROM_UTF8(legacyName));
 
	session->setHost(FROM_UTF8(m_server));
 
	session->setPort(6667);
 

	
 
	if (!password.empty()) {
 
		std::string identify = m_identify;
 
		boost::replace_all(identify, "$password", password);
 
		boost::replace_all(identify, "$name", legacyName);
 
		session->setIdentify(identify);
 
	}
 

	
 
	session->open();
 

	
 
	m_sessions[user] = session;
 
}
 

	
 
void SingleIRCNetworkPlugin::handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
	if (m_sessions[user] == NULL) {
 
		LOG4CXX_WARN(logger, user << ": Already disconnected.");
 
		return;
 
	}
 
	LOG4CXX_INFO(logger, user << ": Disconnecting.");
 

	
 
	m_sessions[user]->close();
 
	m_sessions[user]->deleteLater();
 
	m_sessions.erase(user);
 
}
 

	
 
void SingleIRCNetworkPlugin::handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &/*xhtml*/) {
 
	if (m_sessions[user] == NULL) {
 
		LOG4CXX_WARN(logger, user << ": Message received for unconnected user");
 
		return;
 
	}
 

	
 
	// handle PMs
 
	std::string r = legacyName;
 
	if (legacyName.find("/") == std::string::npos) {
 
		r = legacyName.substr(0, r.find("@"));
 
	}
 
	else {
 
		r = legacyName.substr(legacyName.find("/") + 1);
 
	}
 

	
 
	LOG4CXX_INFO(logger, user << ": Forwarding message to " << r);
 
	m_sessions[user]->sendCommand(IrcCommand::createMessage(FROM_UTF8(r), FROM_UTF8(message)));
 

	
 
	if (r.find("#") == 0) {
 
		handleMessage(user, legacyName, message, TO_UTF8(m_sessions[user]->nickName()));
 
	}
 
}
 

	
 
void SingleIRCNetworkPlugin::handleJoinRoomRequest(const std::string &user, const std::string &room, const std::string &nickname, const std::string &password) {
 
	if (m_sessions[user] == NULL) {
 
		LOG4CXX_WARN(logger, user << ": Join room requested for unconnected user");
 
		return;
 
	}
 

	
 
	LOG4CXX_INFO(logger, user << ": Joining " << room);
 
	m_sessions[user]->addAutoJoinChannel(room);
 
	m_sessions[user]->sendCommand(IrcCommand::createJoin(FROM_UTF8(room), FROM_UTF8(password)));
 
	m_sessions[user]->rooms += 1;
 

	
 
	// update nickname, because we have nickname per session, no nickname per room.
 
	handleRoomNicknameChanged(user, room, TO_UTF8(m_sessions[user]->userName()));
backends/smstools3/main.cpp
Show inline comments
 
@@ -31,194 +31,194 @@ Swift::SimpleEventLoop *loop_;
 

	
 
using namespace boost::filesystem;
 

	
 
using namespace boost::program_options;
 
using namespace Transport;
 

	
 
DEFINE_LOGGER(logger, "SMSNetworkPlugin");
 

	
 
#define INTERNAL_USER "/sms@backend@internal@user"
 

	
 
class SMSNetworkPlugin;
 
SMSNetworkPlugin * np = NULL;
 
StorageBackend *storageBackend;
 

	
 
class SMSNetworkPlugin : public NetworkPlugin {
 
	public:
 
		Swift::BoostNetworkFactories *m_factories;
 
		Swift::BoostIOServiceThread m_boostIOServiceThread;
 
		boost::shared_ptr<Swift::Connection> m_conn;
 
		Swift::Timer::ref m_timer;
 
		int m_internalUser;
 

	
 
		SMSNetworkPlugin(Config *config, Swift::SimpleEventLoop *loop, const std::string &host, int port) : NetworkPlugin() {
 
			this->config = config;
 
			m_factories = new Swift::BoostNetworkFactories(loop);
 
			m_conn = m_factories->getConnectionFactory()->createConnection();
 
			m_conn->onDataRead.connect(boost::bind(&SMSNetworkPlugin::_handleDataRead, this, _1));
 
			m_conn->connect(Swift::HostAddressPort(Swift::HostAddress(host), port));
 
// 			m_conn->onConnectFinished.connect(boost::bind(&FrotzNetworkPlugin::_handleConnected, this, _1));
 
// 			m_conn->onDisconnected.connect(boost::bind(&FrotzNetworkPlugin::handleDisconnected, this));
 

	
 
			LOG4CXX_INFO(logger, "Starting the plugin.");
 

	
 
			m_timer = m_factories->getTimerFactory()->createTimer(5000);
 
			m_timer->onTick.connect(boost::bind(&SMSNetworkPlugin::handleSMSDir, this));
 
			m_timer->start();
 

	
 
			// We're reusing our database model here. Buddies of user with JID INTERNAL_USER are there
 
			// to match received GSM messages from number N with the XMPP users who sent message to number N.
 
			// BuddyName = GSM number
 
			// Alias = XMPP user JID to which the messages from this number is sent to.
 
			// TODO: This should be per Modem!!!
 
			UserInfo info;
 
			info.jid = INTERNAL_USER;
 
			info.password = "";
 
			storageBackend->setUser(info);
 
			storageBackend->getUser(INTERNAL_USER, info);
 
			m_internalUser = info.id;
 
		}
 

	
 

	
 
		void handleSMS(const std::string &sms) {
 
			LOG4CXX_INFO(logger, "Handling SMS " << sms << ".")
 
			std::ifstream t(sms.c_str());
 
			std::string str;
 

	
 
			t.seekg(0, std::ios::end);
 
			str.reserve(t.tellg());
 
			t.seekg(0, std::ios::beg);
 

	
 
			str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
 

	
 
			std::string from = "";
 
			std::string msg = "";
 
			while(str.find("\n") != std::string::npos) {
 
				std::string line = str.substr(0, str.find("\n"));
 
				if (line.find("From: ") == 0) {
 
					from = line.substr(strlen("From: "));
 
				}
 
				else if (line.empty()) {
 
					msg = str.substr(1);
 
					break;
 
				}
 
				str = str.substr(str.find("\n") + 1);
 
			}
 

	
 
			std::list<BuddyInfo> roster;
 
			storageBackend->getBuddies(m_internalUser, roster);
 

	
 
			std::string to;
 
			BOOST_FOREACH(BuddyInfo &b, roster) {
 
				if (b.legacyName == from) {
 
					to = b.alias;
 
				}
 
			}
 

	
 
			if (to.empty()) {
 
				LOG4CXX_WARN(logger, "Received SMS from " << from << ", but this number is not associated with any XMPP user.");
 
			}
 

	
 
			LOG4CXX_INFO(logger, "Forwarding SMS from " << from << " to " << to << ".");
 
			handleMessage(to, from, msg);
 
		}
 

	
 
		void handleSMSDir() {
 
			std::string dir = "/var/spool/sms/incoming/";
 
			if (config->getUnregistered().find("backend.incoming_dir") != config->getUnregistered().end()) {
 
				dir = config->getUnregistered().find("backend.incoming_dir")->second;
 
			if (CONFIG_HAS_KEY(config, "backend.incoming_dir")) {
 
				dir = CONFIG_STRING(config, "backend.incoming_dir");
 
			}
 
			LOG4CXX_INFO(logger, "Checking directory " << dir << " for incoming SMS.");
 

	
 
			path p(dir);
 
			directory_iterator end_itr;
 
			for (directory_iterator itr(p); itr != end_itr; ++itr) {
 

	
 
				try {
 
					if (is_regular(itr->path())) {
 
						handleSMS(itr->path().string());
 
						remove(itr->path());
 
					}
 
				}
 
				catch (const filesystem_error& ex) {
 
					LOG4CXX_ERROR(logger, "Error when removing the SMS: " << ex.what() << ".");
 
				}
 
			}
 
			m_timer->start();
 
		}
 

	
 
		void sendSMS(const std::string &to, const std::string &msg) {
 
			// TODO: Probably 
 
			std::string data = "To: " + to + "\n";
 
			data += "\n";
 
			data += msg;
 

	
 
			// generate random string here...
 
			std::string bucket = "abcdefghijklmnopqrstuvwxyz";
 
			std::string uuid;
 
			for (int i = 0; i < 10; i++) {
 
				uuid += bucket[rand() % bucket.size()];
 
			}
 
			std::ofstream myfile;
 
			myfile.open (std::string("/var/spool/sms/outgoing/spectrum." + uuid).c_str());
 
			myfile << data;
 
			myfile.close();
 
		}
 

	
 
		void sendData(const std::string &string) {
 
			m_conn->write(Swift::createSafeByteArray(string));
 
		}
 

	
 
		void _handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
 
			std::string d(data->begin(), data->end());
 
			handleDataRead(d);
 
		}
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			UserInfo info;
 
			if (!storageBackend->getUser(user, info)) {
 
				handleDisconnected(user, 0, "Not registered user.");
 
				return;
 
			}
 
			std::list<BuddyInfo> roster;
 
			storageBackend->getBuddies(info.id, roster);
 

	
 
			// Send available presence to every number in the roster.
 
			BOOST_FOREACH(BuddyInfo &b, roster) {
 
				handleBuddyChanged(user, b.legacyName, b.alias, b.groups, pbnetwork::STATUS_ONLINE);
 
			}
 

	
 
			np->handleConnected(user);
 
		}
 

	
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
		}
 

	
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "") {
 
			// Remove trailing +, because smstools doesn't use it in "From: " field for received messages.
 
			std::string n = legacyName;
 
			if (n.find("+") == 0) {
 
				n = n.substr(1);
 
			}
 

	
 
			// Create GSM Number - XMPP user pair to match the potential response and send it to the proper JID.
 
			BuddyInfo info;
 
			info.legacyName = n;
 
			info.alias = user;
 
			info.id = -1;
 
			info.subscription = "both";
 
			info.flags = 0;
 
			storageBackend->addBuddy(m_internalUser, info);
 

	
 
			LOG4CXX_INFO(logger, "Sending SMS from " << user << " to " << n << ".");
 
			sendSMS(n, message);
 
		}
 

	
 
		void handleJoinRoomRequest(const std::string &user, const std::string &room, const std::string &nickname, const std::string &password) {
 
		}
 

	
 
		void handleLeaveRoomRequest(const std::string &user, const std::string &room) {
 
		}
 

	
 
		void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups) {
 
			LOG4CXX_INFO(logger, user << ": Added buddy " << buddyName << ".");
 
			handleBuddyChanged(user, buddyName, alias, groups, pbnetwork::STATUS_ONLINE);
include/transport/config.h
Show inline comments
 
/**
 
 * libtransport -- C++ library for easy XMPP Transports development
 
 *
 
 * Copyright (C) 2011, Jan Kaluza <hanzz.k@gmail.com>
 
 *
 
 * This program is free software; you can redistribute it and/or modify
 
 * it under the terms of the GNU General Public License as published by
 
 * the Free Software Foundation; either version 2 of the License, or
 
 * (at your option) any later version.
 
 *
 
 * This program is distributed in the hope that it will be useful,
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <boost/program_options.hpp>
 
#include <boost/foreach.hpp>
 
#include <boost/format.hpp>
 
#include <boost/algorithm/string.hpp>
 
#include <boost/assign.hpp>
 
#include <boost/bind.hpp>
 
#include <boost/signal.hpp>
 

	
 
#define CONFIG_HAS_KEY(PTR, KEY) (*PTR).hasKey(KEY)
 
#define CONFIG_STRING(PTR, KEY) (*PTR)[KEY].as<std::string>()
 
#define CONFIG_INT(PTR, KEY) (*PTR)[KEY].as<int>()
 
#define CONFIG_BOOL(PTR, KEY) (*PTR)[KEY].as<bool>()
 
#define CONFIG_LIST(PTR, KEY) (*PTR)[KEY].as<std::list<std::string> >()
 
#define CONFIG_VECTOR(PTR, KEY) ((*PTR).hasKey(KEY) ? (*PTR)[KEY].as<std::vector<std::string> >() : std::vector<std::string>())
 

	
 

	
 
namespace Transport {
 

	
 
/// Represents variable:value pairs.
 
typedef boost::program_options::variables_map Variables;
 

	
 
/// Represents config file.
 

	
 
/// It's used to load config file and allows others parts of libtransport to be configured
 
/// properly. Config files are text files which use "ini" format. Variables are divided into multiple
 
/// sections. Every class is configurable with some variables which change its behavior. Check particular
 
/// class documentation to get a list of all relevant variables for that class.
 
class Config {
 
	public:
 
		/// Constructor.
 
		Config(int argc = 0, char **argv = NULL) : m_argc(argc), m_argv(argv) {}
 

	
 
		/// Destructor
 
		virtual ~Config() {}
 

	
 
		/// Loads data from config file.
 
		
 
		/// You can pass your extra options which will be recognized by
 
		/// the parser using opts parameter.
 
		/// \param configfile path to config file
 
		/// \param opts extra options which will be recognized by a parser
 
		bool load(const std::string &configfile, boost::program_options::options_description &opts, const std::string &jid = "");
 

	
 
		bool load(std::istream &ifs, boost::program_options::options_description &opts, const std::string &jid = "");
 

	
 
		bool load(std::istream &ifs);
 

	
 
		/// Loads data from config file.
 
		
 
		/// This function loads only config variables needed by libtransport.
 
		/// \see load(const std::string &, boost::program_options::options_description &)
 
		/// \param configfile path to config file
 
		bool load(const std::string &configfile, const std::string &jid = "");
 

	
 
		bool reload();
 

	
 
		bool hasKey(const std::string &key) {
 
			return m_variables.find(key) != m_variables.end();
 
			return m_variables.find(key) != m_variables.end() || m_unregistered.find(key) != m_unregistered.end();
 
		}
 

	
 
		/// Returns value of variable defined by key.
 
		
 
		/// For variables in sections you can use "section.variable" key format.
 
		/// \param key config variable name
 
		const boost::program_options::variable_value &operator[] (const std::string &key) {
 
			return m_variables[key];
 
			if (m_variables.find(key) != m_variables.end()) {
 
				return m_variables[key];
 
			}
 
			return m_unregistered[key];
 
		}
 

	
 
		/// Returns path to config file from which data were loaded.
 
		const std::string &getConfigFile() { return m_file; }
 

	
 
		const std::map<std::string, std::string> &getUnregistered() {
 
			return m_unregistered;
 
		}
 

	
 
		/// This signal is emitted when config is loaded/reloaded.
 
		boost::signal<void ()> onConfigReloaded;
 
	
 
	private:
 
		int m_argc;
 
		char **m_argv;
 
		Variables m_variables;
 
		std::map<std::string, std::string> m_unregistered;
 
		std::map<std::string, boost::program_options::variable_value> m_unregistered;
 
		std::string m_file;
 
};
 

	
 
}
src/config.cpp
Show inline comments
 
@@ -94,139 +94,139 @@ bool Config::load(std::istream &ifs, boost::program_options::options_description
 
		("identity.name", value<std::string>()->default_value("Spectrum 2 Transport"), "Name showed in service discovery.")
 
		("identity.category", value<std::string>()->default_value("gateway"), "Disco#info identity category. 'gateway' by default.")
 
		("identity.type", value<std::string>()->default_value(""), "Type of transport ('icq','msn','gg','irc', ...)")
 
		("registration.enable_public_registration", value<bool>()->default_value(true), "True if users should be able to register.")
 
		("registration.language", value<std::string>()->default_value("en"), "Default language for registration form")
 
		("registration.instructions", value<std::string>()->default_value("Enter your legacy network username and password."), "Instructions showed to user in registration form")
 
		("registration.username_label", value<std::string>()->default_value("Legacy network username:"), "Label for username field")
 
		("registration.username_mask", value<std::string>()->default_value(""), "Username mask")
 
		("registration.auto_register", value<bool>()->default_value(false), "Register new user automatically when the presence arrives.")
 
		("registration.encoding", value<std::string>()->default_value("utf8"), "Default encoding in registration form")
 
		("registration.require_local_account", value<bool>()->default_value(false), "True if users have to have a local account to register to this transport from remote servers.")
 
		("registration.local_username_label", value<std::string>()->default_value("Local username:"), "Label for local usernme field")
 
		("registration.local_account_server", value<std::string>()->default_value("localhost"), "The server on which the local accounts will be checked for validity")
 
		("registration.local_account_server_timeout", value<int>()->default_value(10000), "Timeout when checking local user on local_account_server (msecs)")
 
		("gateway_responder.prompt", value<std::string>()->default_value("Contact ID"), "Value of <prompt> </promt> field")
 
		("gateway_responder.label", value<std::string>()->default_value("Enter legacy network contact ID."), "Label for add contact ID field")
 
		("database.type", value<std::string>()->default_value("none"), "Database type.")
 
		("database.database", value<std::string>()->default_value("/var/lib/spectrum2/$jid/database.sql"), "Database used to store data")
 
		("database.server", value<std::string>()->default_value("localhost"), "Database server.")
 
		("database.user", value<std::string>()->default_value(""), "Database user.")
 
		("database.password", value<std::string>()->default_value(""), "Database Password.")
 
		("database.port", value<int>()->default_value(0), "Database port.")
 
		("database.prefix", value<std::string>()->default_value(""), "Prefix of tables in database")
 
		("database.encryption_key", value<std::string>()->default_value(""), "Encryption key.")
 
		("logging.config", value<std::string>()->default_value(""), "Path to log4cxx config file which is used for Spectrum 2 instance")
 
		("logging.backend_config", value<std::string>()->default_value(""), "Path to log4cxx config file which is used for backends")
 
		("backend.default_avatar", value<std::string>()->default_value(""), "Full path to default avatar")
 
		("backend.avatars_directory", value<std::string>()->default_value(""), "Path to directory with avatars")
 
		("backend.no_vcard_fetch", value<bool>()->default_value(false), "True if VCards for buddies should not be fetched. Only avatars will be forwarded.")
 
	;
 

	
 
	// Load configs passed by command line
 
	if (m_argc != 0 && m_argv) {
 
		basic_command_line_parser<char> parser = command_line_parser(m_argc, m_argv).options(opts).allow_unregistered();
 
		parsed_options parsed = parser.run();
 
		store(parsed, m_variables);
 
	}
 

	
 
	parsed_options parsed = parse_config_file(ifs, opts, true);
 

	
 
	bool found_working = false;
 
	bool found_pidfile = false;
 
	bool found_backend_port = false;
 
	bool found_database = false;
 
	std::string jid = "";
 
	BOOST_FOREACH(option &opt, parsed.options) {
 
		if (opt.string_key == "service.jid") {
 
			if (_jid.empty()) {
 
				jid = opt.value[0];
 
			}
 
			else {
 
				opt.value[0] = _jid;
 
				jid = _jid;
 
			}
 
		}
 
		else if (opt.string_key == "service.backend_port") {
 
			found_backend_port = true;
 
			if (opt.value[0] == "0") {
 
				opt.value[0] = boost::lexical_cast<std::string>(getRandomPort(_jid.empty() ? jid : _jid));
 
			}
 
		}
 
		else if (opt.string_key == "service.working_dir") {
 
			found_working = true;
 
		}
 
		else if (opt.string_key == "service.pidfile") {
 
			found_pidfile = true;
 
		}
 
		else if (opt.string_key == "database.database") {
 
			found_database = true;
 
		}
 
	}
 

	
 
	if (!found_working) {
 
		std::vector<std::string> value;
 
		value.push_back("/var/lib/spectrum2/$jid");
 
		parsed.options.push_back(boost::program_options::basic_option<char>("service.working_dir", value));
 
	}
 
	if (!found_pidfile) {
 
		std::vector<std::string> value;
 
		value.push_back("/var/run/spectrum2/$jid.pid");
 
		parsed.options.push_back(boost::program_options::basic_option<char>("service.pidfile", value));
 
	}
 
	if (!found_backend_port) {
 
		std::vector<std::string> value;
 
		std::string p = boost::lexical_cast<std::string>(getRandomPort(_jid.empty() ? jid : _jid));
 
		value.push_back(p);
 
		parsed.options.push_back(boost::program_options::basic_option<char>("service.backend_port", value));
 
	}
 
	if (!found_database) {
 
		std::vector<std::string> value;
 
		value.push_back("/var/lib/spectrum2/$jid/database.sql");
 
		parsed.options.push_back(boost::program_options::basic_option<char>("database.database", value));
 
	}
 

	
 
	BOOST_FOREACH(option &opt, parsed.options) {
 
		if (opt.unregistered) {
 
			m_unregistered[opt.string_key] = opt.value[0];
 
			m_unregistered[opt.string_key] = variable_value(opt.value[0], false);
 
		}
 
		else if (opt.value[0].find("$jid") != std::string::npos) {
 
			boost::replace_all(opt.value[0], "$jid", jid);
 
		}
 
	}
 

	
 
	store(parsed, m_variables);
 
	notify(m_variables);
 

	
 
	onConfigReloaded();
 

	
 
	return true;
 
}
 

	
 
bool Config::load(std::istream &ifs) {
 
	options_description opts("Transport options");
 
	return load(ifs, opts);
 
}
 

	
 
bool Config::load(const std::string &configfile, const std::string &jid) {
 
	try {
 
		options_description opts("Transport options");
 
		return load(configfile, opts, jid);
 
	} catch ( const boost::program_options::multiple_occurrences& e ) {
 
#if (BOOST_MAJOR_VERSION >= 1 && BOOST_MINOR_VERSION >= 42)
 
		std::cerr << configfile << " parsing error: " << e.what() << " from option: " << e.get_option_name() << std::endl;
 
#else
 
		std::cerr << configfile << " parsing error: " << e.what() << std::endl;
 
#endif
 
		return false;
 
	}
 
}
 

	
 
bool Config::reload() {
 
	if (m_file.empty()) {
 
		return false;
 
	}
 

	
 
	return load(m_file);
 
}
 

	
 
}
0 comments (0 inline, 0 general)