cli.cc 11.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2010-2016  Belledonne Communications SARL, All rights reserved.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as
	published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <poll.h>

#include "cli.hh"
30 31 32
#include <flexisip/common.hh>
#include <flexisip/logmanager.hh>
#include <flexisip/registrardb.hh>
33

34
using namespace flexisip;
35
using namespace std;
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

CommandLineInterface::CommandLineInterface(const std::string &name) : mName(name) {
	if (pipe(mControlFds) == -1)
		LOGF("Cannot create control pipe of CommandLineInterface thread: %s", strerror(errno));
}

CommandLineInterface::~CommandLineInterface() {
	if (mRunning)
		stop();
	close(mControlFds[0]);
	close(mControlFds[1]);
}


void CommandLineInterface::start() {
	mRunning = true;
	pthread_create(&mThread, nullptr, &CommandLineInterface::threadfunc, this);
}

void CommandLineInterface::stop() {
	if (!mRunning)
		return;

	mRunning = false;
	if (write(mControlFds[1], "please stop", 1) == -1)
		LOGF("Cannot write to control pipe of CommandLineInterface thread: %s", strerror(errno));
	pthread_join(mThread, nullptr);
}

void CommandLineInterface::answer(unsigned int socket, const std::string &message) {
	send(socket, message.c_str(), message.length(), 0);
	shutdown(socket, SHUT_RDWR);
	close(socket);
}

void CommandLineInterface::parseAndAnswer(unsigned int socket, const std::string &command, const std::vector<std::string> &args) {
	if ((command == "CONFIG_GET") || (command == "GET"))
		handle_config_get_command(socket, args);
	else if ((command == "CONFIG_LIST") || (command == "LIST"))
		handle_config_list_command(socket, args);
	else if ((command == "CONFIG_SET") || (command == "SET"))
		handle_config_set_command(socket, args);
	else
		answer(socket, "Error: unknown command " + command);
}

GenericEntry *CommandLineInterface::get_generic_entry(const std::string &arg) const {
	std::vector<std::string> arg_split = split(arg, '/');
	GenericManager *manager = GenericManager::get();
	GenericStruct *root = manager->getRoot();

	if (arg == "all")
		return root;
	return find(root, arg_split);
}

void CommandLineInterface::handle_config_get_command(unsigned int socket, const std::vector<std::string> &args) {
	if (args.size() < 1) {
		answer(socket, "Error: at least 1 argument is expected for the CONFIG_GET command");
		return;
	}

	GenericEntry *entry = get_generic_entry(args.front());
	if (!entry) {
		answer(socket, "Error: " + args.front() + " not found");
		return;
	}

	GenericStruct *gstruct = dynamic_cast<GenericStruct *>(entry);
	if (gstruct)
		answer(socket, printSection(gstruct, false));
	else
		answer(socket, printEntry(entry, false));
}

void CommandLineInterface::handle_config_list_command(unsigned int socket, const std::vector<std::string> &args) {
	if (args.size() < 1) {
		answer(socket, "Error: at least 1 argument is expected for the CONFIG_LIST command");
		return;
	}

	GenericEntry *entry = get_generic_entry(args.front());
	if (!entry) {
		answer(socket, "Error: " + args.front() + " not found");
		return;
	}

	GenericStruct *gstruct = dynamic_cast<GenericStruct *>(entry);
	if (gstruct)
		answer(socket, printSection(gstruct, true));
	else
		answer(socket, printEntry(entry, true));
}

130 131 132 133 134 135 136 137
string CommandLineInterface::agregate(const std::vector<std::string> &args, size_t from_pos){
	ostringstream ostr;
	for (size_t i = from_pos; i < args.size(); ++i){
		ostr << args[i] << " ";
	}
	return ostr.str();
}

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
void CommandLineInterface::handle_config_set_command(unsigned int socket, const std::vector<std::string> &args) {
	if (args.size() < 2) {
		answer(socket, "Error: at least 2 arguments are expected for the CONFIG_SET command");
		return;
	}

	std::string arg = args.front();
	GenericEntry *entry = get_generic_entry(arg);
	if (!entry) {
		answer(socket, "Error: " + args.front() + " not found");
		return;
	}

	std::string value = args.at(1);
	ConfigValue *config_value = dynamic_cast<ConfigValue *>(entry);
	if (config_value && (arg == "global/debug")) {
		config_value->set(value);
155
		LogManager::get().setLogLevel(BCTBX_LOG_DEBUG);
156 157 158
		answer(socket, "debug : " + value);
	} else if (config_value && (arg == "global/log-level")) {
		config_value->set(value);
159
		LogManager::get().setLogLevel(LogManager::get().logLevelFromName(value));
160 161 162
		answer(socket, "log-level : " + value);
	} else if (config_value && (arg == "global/syslog-level")) {
		config_value->set(value);
163
		LogManager::get().setSyslogLevel(LogManager::get().logLevelFromName(value));
164
		answer(socket, "syslog-level : " + value);
165 166 167 168 169 170 171 172 173
	} else if (config_value && (arg == "global/contextual-log-level")) {
		config_value->set(value);
		LogManager::get().setContextualLevel(LogManager::get().logLevelFromName(value));
		answer(socket, "contextual-log-level : " + value);
	}else if (config_value && (arg == "global/contextual-log-filter")) {
		value = agregate(args, 1);
		config_value->set(value);
		LogManager::get().setContextualFilter(value);
		answer(socket, "contextual-log-filter : " + value);
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
	} else {
		answer(socket, "Only debug, log-level and syslog-level from global can be updated while flexisip is running");
	}
}

void CommandLineInterface::run() {
	int server_socket = socket(AF_UNIX, SOCK_STREAM, 0);
	if (server_socket == -1) {
		SLOGE << "Socket error " << errno << ": " << std::strerror(errno);
		stop();
	}

	int pid = getpid();
	std::string path = "/tmp/flexisip-" + mName + "-" + std::to_string(pid);
	SLOGD << "CLI socket is at " << path;
	struct sockaddr_un local;
	local.sun_family = AF_UNIX;
	strcpy(local.sun_path, path.c_str());
	unlink(local.sun_path);
	int local_length = strlen(local.sun_path) + sizeof(local.sun_family);
	if (::bind(server_socket, (struct sockaddr *)&local, local_length) == -1) {
		SLOGE << "Bind error " << errno << ": " << std::strerror(errno);
		stop();
	}

	if (listen(server_socket, 1) == -1) {
		SLOGE << "Listen error " << errno << ": " << std::strerror(errno);
		stop();
	}

	struct pollfd pfd[2];
	while (mRunning) {
		memset(pfd, 0, sizeof(pfd));
		pfd[0].fd = server_socket;
		pfd[0].events = POLLIN;
		pfd[1].fd = mControlFds[0];
		pfd[1].events = POLLIN;
		
		int ret = poll(pfd, 2, -1);
		if (ret == -1) {
			if (errno != EINTR)
				SLOGE << "CommandLineInterface thread getting poll() error: " << strerror(errno);
			continue;
		} else if (ret == 0) {
			continue; // Timeout not possible
		} else if (pfd[0].revents != POLLIN) {
			continue;
		}
		// Otherwise we have something to accept on our server_socket

		struct sockaddr_un remote;
		auto remote_length = (socklen_t )sizeof(remote);
		int child_socket = accept(server_socket, (struct sockaddr *)&remote, &remote_length);
		if (child_socket == -1) {
			SLOGE << "Accept error " << errno << ": " << std::strerror(errno);
			continue;
		}

		bool finished = false;
		do {
			char buffer[512] = { 0 };
			int n = recv(child_socket, buffer, sizeof(buffer) - 1, 0);
			if (n < 0) {
				SLOGE << "Recv error " << errno << ": " << std::strerror(errno);
				shutdown(child_socket, SHUT_RDWR);
				close(child_socket);
				finished = true;
			} else if (n > 0) {
				SLOGD << "CommandLineInterface " << mName << " received: " << buffer;
				auto split_query = split(buffer, ' ');
				std::string command = split_query.front();
				split_query.erase(split_query.begin());
				parseAndAnswer(child_socket, command, split_query);
				finished = true;
			}
		} while (!finished && mRunning);
	}

	shutdown(server_socket, SHUT_RDWR);
	close(server_socket);
	unlink(path.c_str());
}

GenericEntry* CommandLineInterface::find(GenericStruct *root, std::vector<std::string> &path) {
	std::string elem = path.front();
	path.erase(path.begin());
	for (const auto entry : root->getChildren()) {
		if (!entry || (entry->getName() != elem))
			continue;

		if (path.empty()) {
			return entry;
		} else {
			auto gstruct = dynamic_cast<GenericStruct *>(entry);
			if (gstruct)
				return find(gstruct, path);
			return nullptr;
		}
	}
	return nullptr;
}

std::string CommandLineInterface::printEntry(GenericEntry *entry, bool printHelpInsteadOfValue) {
	auto gstruct = dynamic_cast<GenericStruct *>(entry);
	bool isNode = (gstruct != nullptr);
	std::string answer;
	
	if (printHelpInsteadOfValue) {
		if (isNode)
			answer += "[";
		answer += entry->getName();
		if (isNode)
			answer += "]";
		answer += " : " + entry->getHelp();
	} else {
		if (isNode) {
			answer += "[" + gstruct->getName() + "]";
		} else {
			auto counter = dynamic_cast<StatCounter64 *>(entry);
			if (counter) {
				answer += counter->getName() + " : " + std::to_string(counter->read());
			} else {
				auto value = dynamic_cast<ConfigValue *>(entry);
				if (value)
					answer += value->getName() + " : " + value->get();
			}
		}
	}
	return answer;
}

std::string CommandLineInterface::printSection(GenericStruct *gstruct, bool printHelpInsteadOfValue) {
	std::string answer = "";
	for (const auto child : gstruct->getChildren()) {
		if (child)
			answer += printEntry(child, printHelpInsteadOfValue) + "\r\n";
	}
	return answer;
}

void *CommandLineInterface::threadfunc(void *arg) {
	CommandLineInterface *thiz = reinterpret_cast<CommandLineInterface *>(arg);
	thiz->run();
	return nullptr;
}


ProxyCommandLineInterface::ProxyCommandLineInterface(const std::shared_ptr<Agent> &agent) : CommandLineInterface("proxy"), mAgent(agent) {}

void ProxyCommandLineInterface::handle_registrar_clear_command(unsigned int socket, const std::vector<std::string> &args) {
	if (args.size() < 1) {
		answer(socket, "Error: a SIP address argument is expected for the REGISTRAR_CLEAR command");
		return;
	}

	class ClearListener : public ContactUpdateListener {
	public:
		ClearListener(ProxyCommandLineInterface *cli, unsigned int socket, const std::string &uri)
			: mCli(cli), mSocket(socket), mUri(uri) {}

334
		void onRecordFound(const shared_ptr<Record> &r) override {
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
			RegistrarDb::get()->publish(mUri, "");
			mCli->answer(mSocket, "Done: cleared record " + mUri);
		}
		void onError() override {
			mCli->answer(mSocket, "Error: cannot clear record " + mUri);
		}
		void onInvalid() override {
			mCli->answer(mSocket, "Error: cannot clear record " + mUri);
		}
		void onContactUpdated(const std::shared_ptr<ExtendedContact> &ec) override {}

	private:
		ProxyCommandLineInterface *mCli = nullptr;
		unsigned int mSocket = 0;
		std::string mUri;
	};

	std::string arg = args.front();
	auto msg = nta_msg_create(mAgent->getSofiaAgent(), 0);
	auto sip = sip_object(msg);
	sip->sip_from = sip_from_create(msg_home(msg), (url_string_t *)arg.c_str());
	auto listener = std::make_shared<ClearListener>(this, socket, arg);
	RegistrarDb::get()->clear(sip, listener);
}

void ProxyCommandLineInterface::parseAndAnswer(unsigned int socket, const std::string &command, const std::vector<std::string> &args) {
	if (command == "REGISTRAR_CLEAR")
		handle_registrar_clear_command(socket, args);
	else
		CommandLineInterface::parseAndAnswer(socket, command, args);
}