const int POLL_TIMEOUT = 300000;
-void authPasswdClientEnableLogSystem(void) {
- AuthPasswd::Singleton<AuthPasswd::Log::LogSystem>::Instance().SetTag("AUTH_PASSWD_CLIENT");
+void authPasswdClientEnableLogSystem(void)
+{
+ AuthPasswd::Singleton<AuthPasswd::Log::LogSystem>::Instance().SetTag("AUTH_PASSWD_CLIENT");
}
-int waitForSocket(int sock, int event, int timeout) {
- int retval;
- pollfd desc[1];
- desc[0].fd = sock;
- desc[0].events = event;
-
- while((-1 == (retval = poll(desc, 1, timeout))) && (errno == EINTR)) {
- timeout >>= 1;
- errno = 0;
- }
-
- if (0 == retval) {
- LogDebug("Poll timeout");
- } else if (-1 == retval) {
- int err = errno;
- LogError("Error in poll: " << AuthPasswd::errnoToString(err));
- }
- return retval;
+int waitForSocket(int sock, int event, int timeout)
+{
+ int retval;
+ pollfd desc[1];
+ desc[0].fd = sock;
+ desc[0].events = event;
+
+ while ((-1 == (retval = poll(desc, 1, timeout))) && (errno == EINTR)) {
+ timeout >>= 1;
+ errno = 0;
+ }
+
+ if (0 == retval)
+ LogDebug("Poll timeout");
+ else if (-1 == retval) {
+ int err = errno;
+ LogError("Error in poll: " << AuthPasswd::errnoToString(err));
+ }
+
+ return retval;
}
} // namespace anonymous
namespace AuthPasswd {
-int SockRAII::Connect(char const * const interface) {
- sockaddr_un clientAddr;
- int flags;
-
- if (m_sock != -1) // guard
- close(m_sock);
-
- m_sock = socket(AF_UNIX, SOCK_STREAM, 0);
- if (m_sock < 0) {
- int err = errno;
- LogError("Error creating socket: " << AuthPasswd::errnoToString(err));
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- if ((flags = fcntl(m_sock, F_GETFL, 0)) < 0 ||
- fcntl(m_sock, F_SETFL, flags | O_NONBLOCK) < 0)
- {
- int err = errno;
- LogError("Error in fcntl: " << AuthPasswd::errnoToString(err));
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- memset(&clientAddr, 0, sizeof(clientAddr));
-
- clientAddr.sun_family = AF_UNIX;
-
- if (strlen(interface) >= sizeof(clientAddr.sun_path)) {
- LogError("Error: interface name " << interface << "is too long. Max len is:" << sizeof(clientAddr.sun_path));
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- strncpy(clientAddr.sun_path, interface, sizeof(clientAddr.sun_path) - 1);
-
- LogDebug("ClientAddr.sun_path = " << interface);
-
- int retval = TEMP_FAILURE_RETRY(connect(m_sock, (struct sockaddr*)&clientAddr, SUN_LEN(&clientAddr)));
- if ((retval == -1) && (errno == EINPROGRESS)) {
- if (0 >= waitForSocket(m_sock, POLLOUT, POLL_TIMEOUT)) {
- LogError("Error in waitForSocket.");
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
- int error = 0;
- socklen_t len = sizeof(error);
- retval = getsockopt(m_sock, SOL_SOCKET, SO_ERROR, &error, &len);
-
- if (-1 == retval) {
- int err = errno;
- LogError("Error in getsockopt: " << AuthPasswd::errnoToString(err));
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- if (error == EACCES) {
- LogError("Access denied");
- return AUTH_PASSWD_API_ERROR_ACCESS_DENIED;
- }
-
- if (error != 0) {
- LogError("Error in connect: " << AuthPasswd::errnoToString(error));
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- return AUTH_PASSWD_API_SUCCESS;
- }
-
- if (-1 == retval) {
- int err = errno;
- LogError("Error connecting socket: " << AuthPasswd::errnoToString(err));
- if (err == EACCES)
- return AUTH_PASSWD_API_ERROR_ACCESS_DENIED;
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- return AUTH_PASSWD_API_SUCCESS;
+int SockRAII::Connect(char const *const interface)
+{
+ sockaddr_un clientAddr;
+ int flags;
+
+ if (m_sock != -1) // guard
+ close(m_sock);
+
+ m_sock = socket(AF_UNIX, SOCK_STREAM, 0);
+
+ if (m_sock < 0) {
+ int err = errno;
+ LogError("Error creating socket: " << AuthPasswd::errnoToString(err));
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ if ((flags = fcntl(m_sock, F_GETFL, 0)) < 0 ||
+ fcntl(m_sock, F_SETFL, flags | O_NONBLOCK) < 0) {
+ int err = errno;
+ LogError("Error in fcntl: " << AuthPasswd::errnoToString(err));
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ memset(&clientAddr, 0, sizeof(clientAddr));
+ clientAddr.sun_family = AF_UNIX;
+
+ if (strlen(interface) >= sizeof(clientAddr.sun_path)) {
+ LogError("Error: interface name " << interface << "is too long. Max len is:" << sizeof(
+ clientAddr.sun_path));
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ strncpy(clientAddr.sun_path, interface, sizeof(clientAddr.sun_path) - 1);
+ LogDebug("ClientAddr.sun_path = " << interface);
+ int retval = TEMP_FAILURE_RETRY(connect(m_sock, (struct sockaddr *)&clientAddr,
+ SUN_LEN(&clientAddr)));
+
+ if ((retval == -1) && (errno == EINPROGRESS)) {
+ if (0 >= waitForSocket(m_sock, POLLOUT, POLL_TIMEOUT)) {
+ LogError("Error in waitForSocket.");
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ int error = 0;
+ socklen_t len = sizeof(error);
+ retval = getsockopt(m_sock, SOL_SOCKET, SO_ERROR, &error, &len);
+
+ if (-1 == retval) {
+ int err = errno;
+ LogError("Error in getsockopt: " << AuthPasswd::errnoToString(err));
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ if (error == EACCES) {
+ LogError("Access denied");
+ return AUTH_PASSWD_API_ERROR_ACCESS_DENIED;
+ }
+
+ if (error != 0) {
+ LogError("Error in connect: " << AuthPasswd::errnoToString(error));
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ return AUTH_PASSWD_API_SUCCESS;
+ }
+
+ if (-1 == retval) {
+ int err = errno;
+ LogError("Error connecting socket: " << AuthPasswd::errnoToString(err));
+
+ if (err == EACCES)
+ return AUTH_PASSWD_API_ERROR_ACCESS_DENIED;
+
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ return AUTH_PASSWD_API_SUCCESS;
}
-int sendToServerWithFd(int fd, const RawBuffer &send, MessageBuffer &recv) {
- ssize_t done = 0;
- char buffer[2048];
- while ((send.size() - done) > 0) {
- if (0 >= waitForSocket(fd, POLLOUT, POLL_TIMEOUT)) {
- LogError("Error in poll(POLLOUT)");
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
- ssize_t temp = TEMP_FAILURE_RETRY(::send(fd, &send[done], send.size() - done, MSG_NOSIGNAL));
- if (-1 == temp) {
- int err = errno;
- LogError("Error in send: " << errnoToString(err));
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
- done += temp;
- }
-
- do {
- if (0 >= waitForSocket(fd, POLLIN, POLL_TIMEOUT)) {
- LogError("Error in poll(POLLIN)");
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
- ssize_t temp = TEMP_FAILURE_RETRY(::recv(fd, buffer, 2048, 0));
- if (-1 == temp) {
- int err = errno;
- LogError("Error in recv: " << errnoToString(err));
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- if (0 == temp) {
- LogError("Read return 0/Connection closed by server(?)");
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- RawBuffer raw(buffer, buffer+temp);
- recv.Push(raw);
- } while(!recv.Ready());
- return AUTH_PASSWD_API_SUCCESS;
+int sendToServerWithFd(int fd, const RawBuffer &send, MessageBuffer &recv)
+{
+ ssize_t done = 0;
+ char buffer[2048];
+
+ while ((send.size() - done) > 0) {
+ if (0 >= waitForSocket(fd, POLLOUT, POLL_TIMEOUT)) {
+ LogError("Error in poll(POLLOUT)");
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ ssize_t temp = TEMP_FAILURE_RETRY(::send(fd, &send[done], send.size() - done, MSG_NOSIGNAL));
+
+ if (-1 == temp) {
+ int err = errno;
+ LogError("Error in send: " << errnoToString(err));
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ done += temp;
+ }
+
+ do {
+ if (0 >= waitForSocket(fd, POLLIN, POLL_TIMEOUT)) {
+ LogError("Error in poll(POLLIN)");
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ ssize_t temp = TEMP_FAILURE_RETRY(::recv(fd, buffer, 2048, 0));
+
+ if (-1 == temp) {
+ int err = errno;
+ LogError("Error in recv: " << errnoToString(err));
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ if (0 == temp) {
+ LogError("Read return 0/Connection closed by server(?)");
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ RawBuffer raw(buffer, buffer + temp);
+ recv.Push(raw);
+ } while (!recv.Ready());
+
+ return AUTH_PASSWD_API_SUCCESS;
}
-int sendToServer(char const * const interface, const RawBuffer &send, MessageBuffer &recv) {
- int ret;
- SockRAII sock;
+int sendToServer(char const *const interface, const RawBuffer &send, MessageBuffer &recv)
+{
+ int ret;
+ SockRAII sock;
- if (AUTH_PASSWD_API_SUCCESS != (ret = sock.Connect(interface))) {
- LogError("Error in SockRAII");
- return ret;
- }
+ if (AUTH_PASSWD_API_SUCCESS != (ret = sock.Connect(interface))) {
+ LogError("Error in SockRAII");
+ return ret;
+ }
- return sendToServerWithFd(sock.Get(), send, recv);
+ return sendToServerWithFd(sock.Get(), send, recv);
}
-int sendToServerAncData(char const * const interface, const RawBuffer &send, struct msghdr &hdr) {
- int ret;
- SockRAII sock;
- ssize_t done = 0;
-
- if (AUTH_PASSWD_API_SUCCESS != (ret = sock.Connect(interface))) {
- LogError("Error in SockRAII");
- return ret;
- }
-
- while ((send.size() - done) > 0) {
- if (0 >= waitForSocket(sock.Get(), POLLOUT, POLL_TIMEOUT)) {
- LogError("Error in poll(POLLOUT)");
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
- ssize_t temp = TEMP_FAILURE_RETRY(write(sock.Get(), &send[done], send.size() - done));
- if (-1 == temp) {
- int err = errno;
- LogError("Error in write: " << errnoToString(err));
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
- done += temp;
- }
-
- if (0 >= waitForSocket(sock.Get(), POLLIN, POLL_TIMEOUT)) {
- LogError("Error in poll(POLLIN)");
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- ssize_t temp = TEMP_FAILURE_RETRY(recvmsg(sock.Get(), &hdr, MSG_CMSG_CLOEXEC));
-
- if (temp < 0) {
- int err = errno;
- LogError("Error in recvmsg(): " << errnoToString(err) << " errno: " << err);
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- if (0 == temp) {
- LogError("Read return 0/Connection closed by server(?)");
- return AUTH_PASSWD_API_ERROR_SOCKET;
- }
-
- return AUTH_PASSWD_API_SUCCESS;
+int sendToServerAncData(char const *const interface, const RawBuffer &send, struct msghdr &hdr)
+{
+ int ret;
+ SockRAII sock;
+ ssize_t done = 0;
+
+ if (AUTH_PASSWD_API_SUCCESS != (ret = sock.Connect(interface))) {
+ LogError("Error in SockRAII");
+ return ret;
+ }
+
+ while ((send.size() - done) > 0) {
+ if (0 >= waitForSocket(sock.Get(), POLLOUT, POLL_TIMEOUT)) {
+ LogError("Error in poll(POLLOUT)");
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ ssize_t temp = TEMP_FAILURE_RETRY(write(sock.Get(), &send[done], send.size() - done));
+
+ if (-1 == temp) {
+ int err = errno;
+ LogError("Error in write: " << errnoToString(err));
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ done += temp;
+ }
+
+ if (0 >= waitForSocket(sock.Get(), POLLIN, POLL_TIMEOUT)) {
+ LogError("Error in poll(POLLIN)");
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ ssize_t temp = TEMP_FAILURE_RETRY(recvmsg(sock.Get(), &hdr, MSG_CMSG_CLOEXEC));
+
+ if (temp < 0) {
+ int err = errno;
+ LogError("Error in recvmsg(): " << errnoToString(err) << " errno: " << err);
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ if (0 == temp) {
+ LogError("Read return 0/Connection closed by server(?)");
+ return AUTH_PASSWD_API_ERROR_SOCKET;
+ }
+
+ return AUTH_PASSWD_API_SUCCESS;
}
-int try_catch(const std::function<int()>& func)
+int try_catch(const std::function<int()> &func)
{
- try {
- return func();
- } catch (MessageBuffer::Exception::Base &e) {
- LogError("AuthPasswd::MessageBuffer::Exception " << e.DumpToString());
- } catch (std::bad_alloc &e) {
- LogError("Memory allocation failed " << e.what());
- return AUTH_PASSWD_API_ERROR_OUT_OF_MEMORY;
- } catch (std::exception &e) {
- LogError("STD exception " << e.what());
- } catch (...) {
- LogError("Unknown exception occured");
- }
- return AUTH_PASSWD_API_ERROR_UNKNOWN;
+ try {
+ return func();
+ } catch (MessageBuffer::Exception::Base &e) {
+ LogError("AuthPasswd::MessageBuffer::Exception " << e.DumpToString());
+ } catch (std::bad_alloc &e) {
+ LogError("Memory allocation failed " << e.what());
+ return AUTH_PASSWD_API_ERROR_OUT_OF_MEMORY;
+ } catch (std::exception &e) {
+ LogError("STD exception " << e.what());
+ } catch (...) {
+ LogError("Unknown exception occured");
+ }
+
+ return AUTH_PASSWD_API_ERROR_UNKNOWN;
}
} // namespace AuthPasswd
-static void init_lib(void) __attribute__ ((constructor));
+static void init_lib(void) __attribute__((constructor));
static void init_lib(void)
{
- authPasswdClientEnableLogSystem();
+ authPasswdClientEnableLogSystem();
}
-static void fini_lib(void) __attribute__ ((destructor));
+static void fini_lib(void) __attribute__((destructor));
static void fini_lib(void)
{
-
}
namespace {
-inline bool isPasswordIncorrect(const char* pwd)
+inline bool isPasswordIncorrect(const char *pwd)
{
- // NULL means that password must be cancelled.
- return (pwd && (strlen(pwd) == 0 || strlen(pwd) > AuthPasswd::MAX_PASSWORD_LEN));
+ // NULL means that password must be cancelled.
+ return (pwd && (strlen(pwd) == 0 || strlen(pwd) > AuthPasswd::MAX_PASSWORD_LEN));
}
} // namespace anonymous
AUTH_PASSWD_API
int auth_passwd_reset_passwd(password_type passwd_type,
- uid_t uid,
- const char *new_passwd)
+ uid_t uid,
+ const char *new_passwd)
{
- using namespace AuthPasswd;
+ using namespace AuthPasswd;
+ return try_catch([&] {
+ if (isPasswordIncorrect(new_passwd)) {
+ LogError("Wrong input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
- return try_catch([&] {
- if (isPasswordIncorrect(new_passwd)) {
- LogError("Wrong input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
+ if (!new_passwd)
+ new_passwd = NO_PASSWORD;
- if (!new_passwd)
- new_passwd = NO_PASSWORD;
+ MessageBuffer send, recv;
- MessageBuffer send, recv;
+ Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_RST_PASSWD));
+ Serialization::Serialize(send, passwd_type);
+ Serialization::Serialize(send, uid);
+ Serialization::Serialize(send, std::string(new_passwd));
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_RST_PASSWD));
- Serialization::Serialize(send, passwd_type);
- Serialization::Serialize(send, uid);
- Serialization::Serialize(send, std::string(new_passwd));
+ int retCode = sendToServer(SERVICE_SOCKET_PASSWD_RESET, send.Pop(), recv);
+ if (AUTH_PASSWD_API_SUCCESS != retCode) {
+ LogError("Error in sendToServer. Error code: " << retCode);
+ return retCode;
+ }
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_RESET, send.Pop(), recv);
- if (AUTH_PASSWD_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
+ Deserialization::Deserialize(recv, retCode);
- Deserialization::Deserialize(recv, retCode);
-
- return retCode;
- });
+ return retCode;
+ });
}
AUTH_PASSWD_API
int auth_passwd_new_policy(policy_h **pp_policy)
{
- if (!pp_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ if (!pp_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- auto policy = new (std::nothrow) AuthPasswd::Policy;
- if (policy == nullptr)
- return AUTH_PASSWD_API_ERROR_OUT_OF_MEMORY;
+ auto policy = new(std::nothrow) AuthPasswd::Policy;
- *pp_policy = reinterpret_cast<policy_h *>(policy);
+ if (policy == nullptr)
+ return AUTH_PASSWD_API_ERROR_OUT_OF_MEMORY;
- return AUTH_PASSWD_API_SUCCESS;
+ *pp_policy = reinterpret_cast<policy_h *>(policy);
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_user(policy_h *p_policy, uid_t uid)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
-
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_USER);
- policy->uid = uid;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- return AUTH_PASSWD_API_SUCCESS;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_USER);
+ policy->uid = uid;
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_max_attempts(policy_h *p_policy, unsigned int max_attempts)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
-
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- /* TODO: set flag & value in atomic operation */
- policy->setFlag(POLICY_MAX_ATTEMPTS);
- policy->maxAttempts = max_attempts;
-
- return AUTH_PASSWD_API_SUCCESS;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ /* TODO: set flag & value in atomic operation */
+ policy->setFlag(POLICY_MAX_ATTEMPTS);
+ policy->maxAttempts = max_attempts;
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_validity(policy_h *p_policy, unsigned int valid_days)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_VALID_PERIOD);
- policy->validPeriod = valid_days;
-
- return AUTH_PASSWD_API_SUCCESS;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_VALID_PERIOD);
+ policy->validPeriod = valid_days;
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_history_size(policy_h *p_policy, unsigned int history_size)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
-
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_HISTORY_SIZE);
- policy->historySize = history_size;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- return AUTH_PASSWD_API_SUCCESS;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_HISTORY_SIZE);
+ policy->historySize = history_size;
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_min_length(policy_h *p_policy, unsigned int min_length)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_MIN_LENGTH);
- policy->minLength = min_length;
-
- return AUTH_PASSWD_API_SUCCESS;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_MIN_LENGTH);
+ policy->minLength = min_length;
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_min_complex_char_num(policy_h *p_policy, unsigned int val)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
-
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_MIN_COMPLEX_CHAR_NUMBER);
- policy->minComplexCharNumber = val;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- return AUTH_PASSWD_API_SUCCESS;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_MIN_COMPLEX_CHAR_NUMBER);
+ policy->minComplexCharNumber = val;
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_max_char_occurrences(policy_h *p_policy, unsigned int val)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_MAX_CHAR_OCCURRENCES);
- policy->maxCharOccurrences = val;
-
- return AUTH_PASSWD_API_SUCCESS;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_MAX_CHAR_OCCURRENCES);
+ policy->maxCharOccurrences = val;
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_max_num_seq_len(policy_h *p_policy, unsigned int val)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
-
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_MAX_NUMERIC_SEQ_LENGTH);
- policy->maxNumSeqLength = val;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- return AUTH_PASSWD_API_SUCCESS;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_MAX_NUMERIC_SEQ_LENGTH);
+ policy->maxNumSeqLength = val;
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_quality(policy_h *p_policy, password_quality_type quality_type)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_QUALITY_TYPE);
- policy->qualityType = quality_type;
-
- return AUTH_PASSWD_API_SUCCESS;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_QUALITY_TYPE);
+ policy->qualityType = quality_type;
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_pattern(policy_h *p_policy, const char *pattern)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
-
- if (!pattern)
- pattern = AuthPasswd::NO_PATTERN;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_PATTERN);
- policy->pattern = std::string(pattern);
-
- return AUTH_PASSWD_API_SUCCESS;
+ if (!pattern)
+ pattern = AuthPasswd::NO_PATTERN;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_PATTERN);
+ policy->pattern = std::string(pattern);
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_forbidden_passwd(policy_h *p_policy, const char *forbidden_passwd)
{
- if (!p_policy)
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
-
- if (!forbidden_passwd)
- forbidden_passwd = AuthPasswd::NO_FORBIDDEND_PASSWORD;
+ if (!p_policy)
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- policy->setFlag(POLICY_FORBIDDEN_PASSWDS);
- policy->forbiddenPasswds.insert(forbidden_passwd);
+ if (!forbidden_passwd)
+ forbidden_passwd = AuthPasswd::NO_FORBIDDEND_PASSWORD;
- return AUTH_PASSWD_API_SUCCESS;
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ policy->setFlag(POLICY_FORBIDDEN_PASSWDS);
+ policy->forbiddenPasswds.insert(forbidden_passwd);
+ return AUTH_PASSWD_API_SUCCESS;
}
AUTH_PASSWD_API
int auth_passwd_set_policy(policy_h *p_policy)
{
- using namespace AuthPasswd;
+ using namespace AuthPasswd;
+ return try_catch([&] {
+ if (!p_policy) {
+ LogError("Wrong input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
- return try_catch([&] {
- if (!p_policy) {
- LogError("Wrong input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
+ auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
- auto policy = reinterpret_cast<AuthPasswd::Policy *>(p_policy);
+ if (!policy->isFlagOn(POLICY_USER))
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- if (!policy->isFlagOn(POLICY_USER))
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ MessageBuffer send, recv;
- MessageBuffer send, recv;
+ Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PASSWD_POLICY));
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PASSWD_POLICY));
+ PolicySerializable policys(*policy);
+ policys.Serialize(send);
- PolicySerializable policys(*policy);
- policys.Serialize(send);
+ int retCode = sendToServer(SERVICE_SOCKET_PASSWD_POLICY, send.Pop(), recv);
+ if (AUTH_PASSWD_API_SUCCESS != retCode) {
+ LogError("Error in sendToServer. Error code: " << retCode);
+ return retCode;
+ }
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_POLICY, send.Pop(), recv);
- if (AUTH_PASSWD_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
+ Deserialization::Deserialize(recv, retCode);
- Deserialization::Deserialize(recv, retCode);
-
- return retCode;
- });
+ return retCode;
+ });
}
AUTH_PASSWD_API
void auth_passwd_free_policy(policy_h *p_policy)
{
- delete (reinterpret_cast<AuthPasswd::Policy *>(p_policy));
+ delete(reinterpret_cast<AuthPasswd::Policy *>(p_policy));
}
AUTH_PASSWD_API
int auth_passwd_disable_policy(uid_t uid)
{
- using namespace AuthPasswd;
-
- return try_catch([&] {
+ using namespace AuthPasswd;
+ return try_catch([&] {
+ MessageBuffer send, recv;
- MessageBuffer send, recv;
+ Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_DIS_PASSWD_POLICY));
+ Serialization::Serialize(send, uid);
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_DIS_PASSWD_POLICY));
- Serialization::Serialize(send, uid);
+ int retCode = sendToServer(SERVICE_SOCKET_PASSWD_POLICY, send.Pop(), recv);
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_POLICY, send.Pop(), recv);
- if (AUTH_PASSWD_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
+ if (AUTH_PASSWD_API_SUCCESS != retCode) {
+ LogError("Error in sendToServer. Error code: " << retCode);
+ return retCode;
+ }
- Deserialization::Deserialize(recv, retCode);
+ Deserialization::Deserialize(recv, retCode);
- return retCode;
- });
+ return retCode;
+ });
}
namespace {
-inline bool isPasswordIncorrect(const char* passwd)
+inline bool isPasswordIncorrect(const char *passwd)
{
- // NULL means that password must be cancelled.
- return (passwd && (strlen(passwd) == 0 || strlen(passwd) > AuthPasswd::MAX_PASSWORD_LEN));
+ // NULL means that password must be cancelled.
+ return (passwd && (strlen(passwd) == 0 || strlen(passwd) > AuthPasswd::MAX_PASSWORD_LEN));
}
} // namespace anonymous
AUTH_PASSWD_API
int auth_passwd_check_passwd(password_type passwd_type,
- const char *passwd,
- unsigned int *current_attempts,
- unsigned int *max_attempts,
- unsigned int *valid_secs)
+ const char *passwd,
+ unsigned int *current_attempts,
+ unsigned int *max_attempts,
+ unsigned int *valid_secs)
{
- using namespace AuthPasswd;
-
- return try_catch([&] {
- if (isPasswordIncorrect(passwd) ||
- current_attempts == NULL || max_attempts == NULL || valid_secs == NULL) {
- LogError("Wrong input param");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
-
- if (!passwd) {
- passwd = NO_PASSWORD;
- }
-
- MessageBuffer send, recv;
-
- *current_attempts = 0;
- *max_attempts = 0;
- *valid_secs = 0;
-
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_CHK_PASSWD));
- Serialization::Serialize(send, passwd_type);
-
- //Clear pwd memory
- std::string passwd_str(passwd);
- Serialization::Serialize(send, passwd_str);
- passwd_str.clear();
-
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
- if (AUTH_PASSWD_API_SUCCESS != retCode) {
- LogDebug("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
-
- Deserialization::Deserialize(recv, retCode);
-
- switch (retCode) {
- case AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH:
- case AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
- case AUTH_PASSWD_API_ERROR_PASSWORD_EXPIRED:
- case AUTH_PASSWD_API_SUCCESS:
- Deserialization::Deserialize(recv, *current_attempts);
- Deserialization::Deserialize(recv, *max_attempts);
- Deserialization::Deserialize(recv, *valid_secs);
- break;
- default:
- break;
- }
-
- return retCode;
- });
+ using namespace AuthPasswd;
+ return try_catch([&] {
+ if (isPasswordIncorrect(passwd) ||
+ current_attempts == NULL || max_attempts == NULL || valid_secs == NULL) {
+ LogError("Wrong input param");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ if (!passwd)
+ passwd = NO_PASSWORD;
+
+ MessageBuffer send, recv;
+
+ *current_attempts = 0;
+ *max_attempts = 0;
+ *valid_secs = 0;
+
+ Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_CHK_PASSWD));
+ Serialization::Serialize(send, passwd_type);
+
+ //Clear pwd memory
+ std::string passwd_str(passwd);
+ Serialization::Serialize(send, passwd_str);
+ passwd_str.clear();
+
+ int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
+
+ if (AUTH_PASSWD_API_SUCCESS != retCode) {
+ LogDebug("Error in sendToServer. Error code: " << retCode);
+ return retCode;
+ }
+
+ Deserialization::Deserialize(recv, retCode);
+
+ switch (retCode) {
+ case AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH:
+ case AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
+ case AUTH_PASSWD_API_ERROR_PASSWORD_EXPIRED:
+ case AUTH_PASSWD_API_SUCCESS:
+ Deserialization::Deserialize(recv, *current_attempts);
+ Deserialization::Deserialize(recv, *max_attempts);
+ Deserialization::Deserialize(recv, *valid_secs);
+ break;
+
+ default:
+ break;
+ }
+
+ return retCode;
+ });
}
AUTH_PASSWD_API
int auth_passwd_check_passwd_state(password_type passwd_type,
- unsigned int *current_attempts,
- unsigned int *max_attempts,
- unsigned int *valid_secs)
+ unsigned int *current_attempts,
+ unsigned int *max_attempts,
+ unsigned int *valid_secs)
{
- using namespace AuthPasswd;
+ using namespace AuthPasswd;
+ return try_catch([&] {
+ if (NULL == current_attempts || NULL == max_attempts ||
+ NULL == valid_secs) {
+ LogError("Wrong input param");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
- return try_catch([&] {
- if (NULL == current_attempts || NULL == max_attempts ||
- NULL == valid_secs) {
+ MessageBuffer send, recv;
- LogError("Wrong input param");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
+ *current_attempts = 0;
+ *max_attempts = 0;
+ *valid_secs = 0;
- MessageBuffer send, recv;
+ Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_CHK_PASSWD_STATE));
+ Serialization::Serialize(send, passwd_type);
- *current_attempts = 0;
- *max_attempts = 0;
- *valid_secs = 0;
+ int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_CHK_PASSWD_STATE));
- Serialization::Serialize(send, passwd_type);
+ if (AUTH_PASSWD_API_SUCCESS != retCode) {
+ LogDebug("Error in sendToServer. Error code: " << retCode);
+ return retCode;
+ }
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_CHECK, send.Pop(), recv);
- if (AUTH_PASSWD_API_SUCCESS != retCode) {
- LogDebug("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
+ Deserialization::Deserialize(recv, retCode);
- Deserialization::Deserialize(recv, retCode);
+ if (retCode == AUTH_PASSWD_API_SUCCESS) {
+ Deserialization::Deserialize(recv, *current_attempts);
+ Deserialization::Deserialize(recv, *max_attempts);
+ Deserialization::Deserialize(recv, *valid_secs);
+ }
- if(retCode == AUTH_PASSWD_API_SUCCESS) {
- Deserialization::Deserialize(recv, *current_attempts);
- Deserialization::Deserialize(recv, *max_attempts);
- Deserialization::Deserialize(recv, *valid_secs);
- }
-
- return retCode;
- });
+ return retCode;
+ });
}
AUTH_PASSWD_API
-int auth_passwd_check_passwd_reused(password_type passwd_type,
- const char *passwd,
- int *is_reused)
+int auth_passwd_check_passwd_reused(password_type passwd_type,
+ const char *passwd,
+ int *is_reused)
{
- using namespace AuthPasswd;
+ using namespace AuthPasswd;
+ return try_catch([&] {
+ if (NULL == passwd || NULL == is_reused) {
+ LogError("Wrong input param");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
- return try_catch([&] {
- if (NULL == passwd || NULL == is_reused) {
- LogError("Wrong input param");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
+ MessageBuffer send, recv;
- MessageBuffer send, recv;
+ Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_CHK_PASSWD_REUSED));
+ Serialization::Serialize(send, passwd_type);
+ Serialization::Serialize(send, std::string(passwd));
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_CHK_PASSWD_REUSED));
- Serialization::Serialize(send, passwd_type);
- Serialization::Serialize(send, std::string(passwd));
+ int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- if (AUTH_PASSWD_API_SUCCESS != retCode) {
- LogDebug("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
+ if (AUTH_PASSWD_API_SUCCESS != retCode) {
+ LogDebug("Error in sendToServer. Error code: " << retCode);
+ return retCode;
+ }
- Deserialization::Deserialize(recv, retCode);
+ Deserialization::Deserialize(recv, retCode);
- if (AUTH_PASSWD_API_SUCCESS == retCode) {
- Deserialization::Deserialize(recv, *is_reused);
- }
+ if (AUTH_PASSWD_API_SUCCESS == retCode)
+ Deserialization::Deserialize(recv, *is_reused);
- return retCode;
- });
+ return retCode;
+ });
}
AUTH_PASSWD_API
int auth_passwd_set_passwd(password_type passwd_type,
- const char *cur_passwd,
- const char *new_passwd)
+ const char *cur_passwd,
+ const char *new_passwd)
{
- using namespace AuthPasswd;
+ using namespace AuthPasswd;
+ return try_catch([&] {
+ if (!cur_passwd)
+ cur_passwd = NO_PASSWORD;
- return try_catch([&] {
- if (!cur_passwd) {
- cur_passwd = NO_PASSWORD;
- }
+ if (isPasswordIncorrect(new_passwd) || strlen(cur_passwd) > MAX_PASSWORD_LEN) {
+ LogError("Wrong input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
- if (isPasswordIncorrect(new_passwd) || strlen(cur_passwd) > MAX_PASSWORD_LEN) {
- LogError("Wrong input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
+ if (!new_passwd)
+ new_passwd = NO_PASSWORD;
- if (!new_passwd) {
- new_passwd = NO_PASSWORD;
- }
+ MessageBuffer send, recv;
- MessageBuffer send, recv;
+ Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PASSWD));
+ Serialization::Serialize(send, passwd_type);
+ Serialization::Serialize(send, std::string(cur_passwd));
+ Serialization::Serialize(send, std::string(new_passwd));
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PASSWD));
- Serialization::Serialize(send, passwd_type);
- Serialization::Serialize(send, std::string(cur_passwd));
- Serialization::Serialize(send, std::string(new_passwd));
+ int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- if (AUTH_PASSWD_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
+ if (AUTH_PASSWD_API_SUCCESS != retCode) {
+ LogError("Error in sendToServer. Error code: " << retCode);
+ return retCode;
+ }
- Deserialization::Deserialize(recv, retCode);
+ Deserialization::Deserialize(recv, retCode);
- return retCode;
- });
+ return retCode;
+ });
}
AUTH_PASSWD_API
int auth_passwd_set_passwd_recovery(const char *cur_recovery_passwd,
- const char *new_normal_passwd)
+ const char *new_normal_passwd)
{
- using namespace AuthPasswd;
-
- return try_catch([&] {
- if (!new_normal_passwd || isPasswordIncorrect(new_normal_passwd) ||
- !cur_recovery_passwd || isPasswordIncorrect(cur_recovery_passwd)) {
+ using namespace AuthPasswd;
+ return try_catch([&] {
+ if (!new_normal_passwd || isPasswordIncorrect(new_normal_passwd) ||
+ !cur_recovery_passwd || isPasswordIncorrect(cur_recovery_passwd)) {
+ LogError("Wrong input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
- LogError("Wrong input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
+ MessageBuffer send, recv;
- MessageBuffer send, recv;
+ Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PASSWD_RECOVERY));
+ Serialization::Serialize(send, std::string(cur_recovery_passwd));
+ Serialization::Serialize(send, std::string(new_normal_passwd));
- Serialization::Serialize(send, static_cast<int>(PasswordHdrs::HDR_SET_PASSWD_RECOVERY));
- Serialization::Serialize(send, std::string(cur_recovery_passwd));
- Serialization::Serialize(send, std::string(new_normal_passwd));
+ int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- int retCode = sendToServer(SERVICE_SOCKET_PASSWD_SET, send.Pop(), recv);
- if (AUTH_PASSWD_API_SUCCESS != retCode) {
- LogError("Error in sendToServer. Error code: " << retCode);
- return retCode;
- }
+ if (AUTH_PASSWD_API_SUCCESS != retCode) {
+ LogError("Error in sendToServer. Error code: " << retCode);
+ return retCode;
+ }
- Deserialization::Deserialize(recv, retCode);
+ Deserialization::Deserialize(recv, retCode);
- return retCode;
- });
+ return retCode;
+ });
}
#define AUTH_PASSWD_API __attribute__((visibility("default")))
extern "C" {
- struct msghdr;
+ struct msghdr;
}
namespace AuthPasswd {
int sendToServerWithFd(int fd, const RawBuffer &send, MessageBuffer &recv);
-int sendToServer(char const * const interface, const RawBuffer &send, MessageBuffer &recv);
+int sendToServer(char const *const interface, const RawBuffer &send, MessageBuffer &recv);
/*
* sendToServerAncData is special case when we want to receive file descriptor
* This function should be called _ONLY_ in this particular case.
*
*/
-int sendToServerAncData(char const * const interface, const RawBuffer &send, struct msghdr &hdr);
+int sendToServerAncData(char const *const interface, const RawBuffer &send, struct msghdr &hdr);
/*
* Decorator function that performs frequently repeated exception handling in
* SS client API functions. Accepts lambda expression as an argument.
*/
-int try_catch(const std::function<int()>& func);
+int try_catch(const std::function<int()> &func);
class SockRAII {
public:
- SockRAII()
- : m_sock(-1)
- {}
+ SockRAII() : m_sock(-1) {}
- ~SockRAII() {
- if (m_sock > -1 )
- close(m_sock);
- }
+ ~SockRAII() {
+ if (m_sock > -1)
+ close(m_sock);
+ }
- int Connect(char const * const interface);
+ int Connect(char const *const interface);
- int Get() const {
- return m_sock;
- }
+ int Get() const {
+ return m_sock;
+ }
private:
- int m_sock;
+ int m_sock;
};
} // namespace AuthPasswd
namespace AuthPasswd {
COMMON_API
-std::string errnoToString(int err) {
- char buffer[MAX_BUF] = {};
-
+std::string errnoToString(int err)
+{
+ char buffer[MAX_BUF] = {};
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE
- if (0 == strerror_r(err, buffer, MAX_BUF))
- return std::string(buffer);
+
+ if (0 == strerror_r(err, buffer, MAX_BUF))
+ return std::string(buffer);
+
#else
- char *result = strerror_r(err, buffer, MAX_BUF);
- if (result)
- return std::string(result);
+ char *result = strerror_r(err, buffer, MAX_BUF);
+
+ if (result)
+ return std::string(result);
+
#endif
- return std::string();
+ return std::string();
}
} // namespace AuthPasswd
namespace AuthPasswd {
struct ConnectionInfo {
- InterfaceID interfaceID;
- MessageBuffer buffer;
+ InterfaceID interfaceID;
+ MessageBuffer buffer;
};
typedef std::map<int, ConnectionInfo> ConnectionInfoMap;
class COMMON_API MessageBuffer : public AuthPasswd::IStream {
public:
- class Exception {
- public:
- DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
- DECLARE_EXCEPTION_TYPE(Base, OutOfData)
- };
+ class Exception {
+ public:
+ DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
+ DECLARE_EXCEPTION_TYPE(Base, OutOfData)
+ };
- MessageBuffer()
- : m_bytesLeft(0)
- {}
+ MessageBuffer() : m_bytesLeft(0) {}
- void Push(const RawBuffer &data);
+ void Push(const RawBuffer &data);
- RawBuffer Pop();
+ RawBuffer Pop();
- bool Ready();
+ bool Ready();
- virtual void Read(size_t num, void *bytes);
+ virtual void Read(size_t num, void *bytes);
- virtual void Write(size_t num, const void *bytes);
+ virtual void Write(size_t num, const void *bytes);
protected:
+ inline void CountBytesLeft() {
+ if (m_bytesLeft > 0)
+ return; // we already counted m_bytesLeft nothing to do
- inline void CountBytesLeft() {
- if (m_bytesLeft > 0)
- return; // we already counted m_bytesLeft nothing to do
+ if (m_buffer.Size() < sizeof(size_t))
+ return; // we cannot count m_bytesLeft because buffer is too small
- if (m_buffer.Size() < sizeof(size_t))
- return; // we cannot count m_bytesLeft because buffer is too small
+ m_buffer.FlattenConsume(&m_bytesLeft, sizeof(size_t));
+ }
- m_buffer.FlattenConsume(&m_bytesLeft, sizeof(size_t));
- }
-
- size_t m_bytesLeft;
- BinaryQueue m_buffer;
+ size_t m_bytesLeft;
+ BinaryQueue m_buffer;
};
} // namespace AuthPasswd
extern const unsigned int PASSWORD_API_NO_EXPIRATION;
COMMON_API
-extern const char* NO_PASSWORD;
+extern const char *NO_PASSWORD;
COMMON_API
-extern const char* NO_PATTERN;
+extern const char *NO_PATTERN;
COMMON_API
-extern const char* NO_FORBIDDEND_PASSWORD;
+extern const char *NO_FORBIDDEND_PASSWORD;
COMMON_API
extern const std::string REGEX_QUALITY_ALPHANUMERIC;
struct COMMON_API Policy {
- Policy();
- ~Policy();
-
- std::string info(void) const;
-
- inline void setFlag(password_policy_type field)
- {
- flag |= (1 << field);
- }
-
- inline bool isFlagOn(password_policy_type field)
- {
- return (flag & (1 << field)) ? true : false;
- }
-
- // XOR-ed value of password_policy_type enum
- int flag;
-
- uid_t uid;
-
- // maximum number of attempts that user can try to check the password without success in serial
- unsigned int maxAttempts;
- // number of days that this password is valid
- unsigned int validPeriod;
- // recent number of passwords which user cannot reuse
- unsigned int historySize;
- // a min number of characters of password
- unsigned int minLength;
- // a min number of complex chars(non-alphabetic) in password
- unsigned int minComplexCharNumber;
- // Maximum count of the same character in the password
- unsigned int maxCharOccurrences;
- // Maximum numeric sequence length in the password
- // regardless descending order, ascending order or repetition
- unsigned int maxNumSeqLength;
- // password quality
- unsigned int qualityType;
-
- // password regular expression
- std::string pattern;
-
- // forbidden strings in password
- std::set<std::string> forbiddenPasswds;
+ Policy();
+ ~Policy();
+
+ std::string info(void) const;
+
+ inline void setFlag(password_policy_type field) {
+ flag |= (1 << field);
+ }
+
+ inline bool isFlagOn(password_policy_type field) {
+ return (flag & (1 << field)) ? true : false;
+ }
+
+ // XOR-ed value of password_policy_type enum
+ int flag;
+
+ uid_t uid;
+
+ // maximum number of attempts that user can try to check the password without success in serial
+ unsigned int maxAttempts;
+ // number of days that this password is valid
+ unsigned int validPeriod;
+ // recent number of passwords which user cannot reuse
+ unsigned int historySize;
+ // a min number of characters of password
+ unsigned int minLength;
+ // a min number of complex chars(non-alphabetic) in password
+ unsigned int minComplexCharNumber;
+ // Maximum count of the same character in the password
+ unsigned int maxCharOccurrences;
+ // Maximum numeric sequence length in the password
+ // regardless descending order, ascending order or repetition
+ unsigned int maxNumSeqLength;
+ // password quality
+ unsigned int qualityType;
+
+ // password regular expression
+ std::string pattern;
+
+ // forbidden strings in password
+ std::set<std::string> forbiddenPasswds;
};
struct COMMON_API PolicySerializable : public Policy, ISerializable {
- explicit PolicySerializable(const Policy &);
- explicit PolicySerializable(IStream &);
- void Serialize(IStream &) const;
+ explicit PolicySerializable(const Policy &);
+ explicit PolicySerializable(IStream &);
+ void Serialize(IStream &) const;
};
}
namespace AuthPasswd {
COMMON_API
-extern char const * const SERVICE_SOCKET_PASSWD_CHECK;
+extern char const *const SERVICE_SOCKET_PASSWD_CHECK;
COMMON_API
-extern char const * const SERVICE_SOCKET_PASSWD_SET;
+extern char const *const SERVICE_SOCKET_PASSWD_SET;
COMMON_API
-extern char const * const SERVICE_SOCKET_PASSWD_RESET;
+extern char const *const SERVICE_SOCKET_PASSWD_RESET;
COMMON_API
-extern char const * const SERVICE_SOCKET_PASSWD_POLICY;
+extern char const *const SERVICE_SOCKET_PASSWD_POLICY;
enum class PasswordHdrs {
- HDR_CHK_PASSWD,
- HDR_CHK_PASSWD_STATE,
- HDR_CHK_PASSWD_REUSED,
- HDR_SET_PASSWD,
- HDR_SET_PASSWD_RECOVERY,
- HDR_RST_PASSWD,
- HDR_SET_PASSWD_POLICY,
- HDR_DIS_PASSWD_POLICY
+ HDR_CHK_PASSWD,
+ HDR_CHK_PASSWD_STATE,
+ HDR_CHK_PASSWD_REUSED,
+ HDR_SET_PASSWD,
+ HDR_SET_PASSWD_RECOVERY,
+ HDR_RST_PASSWD,
+ HDR_SET_PASSWD_POLICY,
+ HDR_DIS_PASSWD_POLICY
};
} // namespace AuthPasswd
namespace AuthPasswd {
-void MessageBuffer::Push(const RawBuffer &data) {
- m_buffer.AppendCopy(&data[0], data.size());
+void MessageBuffer::Push(const RawBuffer &data)
+{
+ m_buffer.AppendCopy(&data[0], data.size());
}
-RawBuffer MessageBuffer::Pop() {
- size_t size = m_buffer.Size();
- RawBuffer buffer;
- buffer.resize(size + sizeof(size_t));
- memcpy(&buffer[0], &size, sizeof(size_t));
- m_buffer.FlattenConsume(&buffer[sizeof(size_t)], size);
- return buffer;
+RawBuffer MessageBuffer::Pop()
+{
+ size_t size = m_buffer.Size();
+ RawBuffer buffer;
+ buffer.resize(size + sizeof(size_t));
+ memcpy(&buffer[0], &size, sizeof(size_t));
+ m_buffer.FlattenConsume(&buffer[sizeof(size_t)], size);
+ return buffer;
}
-bool MessageBuffer::Ready() {
- CountBytesLeft();
- if (m_bytesLeft == 0)
- return false;
- if (m_bytesLeft > m_buffer.Size())
- return false;
- return true;
+bool MessageBuffer::Ready()
+{
+ CountBytesLeft();
+
+ if (m_bytesLeft == 0)
+ return false;
+
+ if (m_bytesLeft > m_buffer.Size())
+ return false;
+
+ return true;
}
-void MessageBuffer::Read(size_t num, void *bytes) {
- CountBytesLeft();
- if (num > m_bytesLeft) {
- LogDebug("Protocol broken. OutOfData. Asked for: " << num << " Ready: " << m_bytesLeft << " Buffer.size(): " << m_buffer.Size());
- Throw(Exception::OutOfData);
- }
+void MessageBuffer::Read(size_t num, void *bytes)
+{
+ CountBytesLeft();
+
+ if (num > m_bytesLeft) {
+ LogDebug("Protocol broken. OutOfData. Asked for: " << num << " Ready: " << m_bytesLeft <<
+ " Buffer.size(): " << m_buffer.Size());
+ Throw(Exception::OutOfData);
+ }
- m_buffer.FlattenConsume(bytes, num);
- m_bytesLeft -= num;
+ m_buffer.FlattenConsume(bytes, num);
+ m_bytesLeft -= num;
}
-void MessageBuffer::Write(size_t num, const void *bytes) {
- m_buffer.AppendCopy(bytes, num);
+void MessageBuffer::Write(size_t num, const void *bytes)
+{
+ m_buffer.AppendCopy(bytes, num);
}
} // namespace AuthPasswd
const unsigned int PASSWORD_INFINITE_ATTEMPT_COUNT = 0;
const unsigned int PASSWORD_API_NO_EXPIRATION = 0xFFFFFFFF;
-const char* NO_PASSWORD = "";
-const char* NO_PATTERN = "";
-const char* NO_FORBIDDEND_PASSWORD = "";
+const char *NO_PASSWORD = "";
+const char *NO_PATTERN = "";
+const char *NO_FORBIDDEND_PASSWORD = "";
const std::string REGEX_QUALITY_UNSPECIFIED = "[.]*";
const std::string REGEX_QUALITY_SOMETHING = ".+";
const std::string REGEX_QUALITY_ALPHANUMERIC = "^[A-Za-z0-9]+$";
Policy::Policy() :
- flag(0),
- uid(0),
- maxAttempts(0),
- validPeriod(0),
- historySize(0),
- minLength(0),
- minComplexCharNumber(0),
- maxCharOccurrences(0),
- maxNumSeqLength(0),
- qualityType(AUTH_PWD_QUALITY_UNSPECIFIED),
- pattern(NO_PATTERN)
+ flag(0),
+ uid(0),
+ maxAttempts(0),
+ validPeriod(0),
+ historySize(0),
+ minLength(0),
+ minComplexCharNumber(0),
+ maxCharOccurrences(0),
+ maxNumSeqLength(0),
+ qualityType(AUTH_PWD_QUALITY_UNSPECIFIED),
+ pattern(NO_PATTERN)
{
}
std::string Policy::info() const
{
- std::stringstream ss;
- ss << "Uid: " << uid;
- ss << " flag: " << flag;
- ss << " maxAttempts: " << maxAttempts;
- ss << " validPeriod: " << validPeriod;
- ss << " historySize: " << historySize;
- ss << " minLength: " << minLength;
- ss << " minComplexCharNumber: " << minComplexCharNumber;
- ss << " maxCharOccurrences: " << maxCharOccurrences;
- ss << " maxNumSeqLength: " << maxNumSeqLength;
- ss << " qualityType: " << qualityType;
- ss << " pattern: " << pattern;
- ss << " forbiddenPasswd size: " << forbiddenPasswds.size();
- ss << " forbiddenPasswd items:";
- for (auto &item : forbiddenPasswds)
- ss << " " << item;
+ std::stringstream ss;
+ ss << "Uid: " << uid;
+ ss << " flag: " << flag;
+ ss << " maxAttempts: " << maxAttempts;
+ ss << " validPeriod: " << validPeriod;
+ ss << " historySize: " << historySize;
+ ss << " minLength: " << minLength;
+ ss << " minComplexCharNumber: " << minComplexCharNumber;
+ ss << " maxCharOccurrences: " << maxCharOccurrences;
+ ss << " maxNumSeqLength: " << maxNumSeqLength;
+ ss << " qualityType: " << qualityType;
+ ss << " pattern: " << pattern;
+ ss << " forbiddenPasswd size: " << forbiddenPasswds.size();
+ ss << " forbiddenPasswd items:";
- return ss.str();
+ for (auto &item : forbiddenPasswds)
+ ss << " " << item;
+
+ return ss.str();
}
PolicySerializable::PolicySerializable(const Policy &policy) : Policy(policy)
PolicySerializable::PolicySerializable(IStream &stream)
{
- Deserialization::Deserialize(stream, flag);
- Deserialization::Deserialize(stream, uid);
- Deserialization::Deserialize(stream, maxAttempts);
- Deserialization::Deserialize(stream, validPeriod);
- Deserialization::Deserialize(stream, historySize);
- Deserialization::Deserialize(stream, minLength);
- Deserialization::Deserialize(stream, minComplexCharNumber);
- Deserialization::Deserialize(stream, maxCharOccurrences);
- Deserialization::Deserialize(stream, maxNumSeqLength);
- Deserialization::Deserialize(stream, qualityType);
- Deserialization::Deserialize(stream, pattern);
- Deserialization::Deserialize(stream, forbiddenPasswds);
+ Deserialization::Deserialize(stream, flag);
+ Deserialization::Deserialize(stream, uid);
+ Deserialization::Deserialize(stream, maxAttempts);
+ Deserialization::Deserialize(stream, validPeriod);
+ Deserialization::Deserialize(stream, historySize);
+ Deserialization::Deserialize(stream, minLength);
+ Deserialization::Deserialize(stream, minComplexCharNumber);
+ Deserialization::Deserialize(stream, maxCharOccurrences);
+ Deserialization::Deserialize(stream, maxNumSeqLength);
+ Deserialization::Deserialize(stream, qualityType);
+ Deserialization::Deserialize(stream, pattern);
+ Deserialization::Deserialize(stream, forbiddenPasswds);
}
void PolicySerializable::Serialize(IStream &stream) const
{
- Serialization::Serialize(stream, flag);
- Serialization::Serialize(stream, uid);
- Serialization::Serialize(stream, maxAttempts);
- Serialization::Serialize(stream, validPeriod);
- Serialization::Serialize(stream, historySize);
- Serialization::Serialize(stream, minLength);
- Serialization::Serialize(stream, minComplexCharNumber);
- Serialization::Serialize(stream, maxCharOccurrences);
- Serialization::Serialize(stream, maxNumSeqLength);
- Serialization::Serialize(stream, qualityType);
- Serialization::Serialize(stream, pattern);
- Serialization::Serialize(stream, forbiddenPasswds);
+ Serialization::Serialize(stream, flag);
+ Serialization::Serialize(stream, uid);
+ Serialization::Serialize(stream, maxAttempts);
+ Serialization::Serialize(stream, validPeriod);
+ Serialization::Serialize(stream, historySize);
+ Serialization::Serialize(stream, minLength);
+ Serialization::Serialize(stream, minComplexCharNumber);
+ Serialization::Serialize(stream, maxCharOccurrences);
+ Serialization::Serialize(stream, maxNumSeqLength);
+ Serialization::Serialize(stream, qualityType);
+ Serialization::Serialize(stream, pattern);
+ Serialization::Serialize(stream, forbiddenPasswds);
}
} // namespace AuthPasswd
namespace AuthPasswd {
-char const * const SERVICE_SOCKET_PASSWD_CHECK = RUN_DIR "/." SOCK_PASSWD_CHECK;
-char const * const SERVICE_SOCKET_PASSWD_SET = RUN_DIR "/." SOCK_PASSWD_SET;
-char const * const SERVICE_SOCKET_PASSWD_RESET = RUN_DIR "/." SOCK_PASSWD_RESET;
-char const * const SERVICE_SOCKET_PASSWD_POLICY = RUN_DIR "/." SOCK_PASSWD_POLICY;
+char const *const SERVICE_SOCKET_PASSWD_CHECK = RUN_DIR "/." SOCK_PASSWD_CHECK;
+char const *const SERVICE_SOCKET_PASSWD_SET = RUN_DIR "/." SOCK_PASSWD_SET;
+char const *const SERVICE_SOCKET_PASSWD_RESET = RUN_DIR "/." SOCK_PASSWD_RESET;
+char const *const SERVICE_SOCKET_PASSWD_POLICY = RUN_DIR "/." SOCK_PASSWD_POLICY;
} // namespace AuthPasswd
// Do not call directly
// Always use Assert macro
AUTHPASSWD_NORETURN void AssertProc(const char *condition,
- const char *file,
- int line,
- const char *function);
+ const char *file,
+ int line,
+ const char *function);
} // namespace AuthPasswd
#define Assert(Condition) do { if (!(Condition)) { AuthPasswd::AssertProc(#Condition, \
- __FILE__, \
- __LINE__, \
- __FUNCTION__); \
- } } while (0)
+ __FILE__, \
+ __LINE__, \
+ __FUNCTION__); \
+ } } while (0)
#endif // AUTH_PASSWD_ASSERT_H
*/
class COMMON_API BinaryQueue {
public:
- class Exception {
- public:
- DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
- DECLARE_EXCEPTION_TYPE(Base, OutOfData)
- };
-
- typedef void (*BufferDeleter)(const void *buffer, size_t bufferSize,
- void *userParam);
- static void BufferDeleterFree(const void *buffer,
- size_t bufferSize,
- void *userParam);
-
- class BucketVisitor {
- public:
- /**
- * Destructor
- */
- virtual ~BucketVisitor();
-
- /**
- * Visit bucket
- *
- * @return none
- * @param[in] buffer Constant pointer to bucket data buffer
- * @param[in] bufferSize Number of bytes in bucket
- */
- virtual void OnVisitBucket(const void *buffer, size_t bufferSize) = 0;
- };
+ class Exception {
+ public:
+ DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
+ DECLARE_EXCEPTION_TYPE(Base, OutOfData)
+ };
+
+ typedef void (*BufferDeleter)(const void *buffer, size_t bufferSize,
+ void *userParam);
+ static void BufferDeleterFree(const void *buffer,
+ size_t bufferSize,
+ void *userParam);
+
+ class BucketVisitor {
+ public:
+ /**
+ * Destructor
+ */
+ virtual ~BucketVisitor();
+
+ /**
+ * Visit bucket
+ *
+ * @return none
+ * @param[in] buffer Constant pointer to bucket data buffer
+ * @param[in] bufferSize Number of bytes in bucket
+ */
+ virtual void OnVisitBucket(const void *buffer, size_t bufferSize) = 0;
+ };
private:
- struct Bucket : private Noncopyable {
- const void *buffer;
- const void *ptr;
- size_t size;
- size_t left;
+ struct Bucket : private Noncopyable {
+ const void *buffer;
+ const void *ptr;
+ size_t size;
+ size_t left;
- BufferDeleter deleter;
- void *param;
+ BufferDeleter deleter;
+ void *param;
- Bucket(const void *buffer,
- size_t bufferSize,
- BufferDeleter deleter,
- void *userParam);
- virtual ~Bucket();
- };
+ Bucket(const void *buffer,
+ size_t bufferSize,
+ BufferDeleter deleter,
+ void *userParam);
+ virtual ~Bucket();
+ };
- typedef std::list<Bucket *> BucketList;
- BucketList m_buckets;
- size_t m_size;
+ typedef std::list<Bucket *> BucketList;
+ BucketList m_buckets;
+ size_t m_size;
- static void DeleteBucket(Bucket *bucket);
+ static void DeleteBucket(Bucket *bucket);
- class BucketVisitorCall {
- private:
- BucketVisitor *m_visitor;
+ class BucketVisitorCall {
+ private:
+ BucketVisitor *m_visitor;
- public:
- BucketVisitorCall(BucketVisitor *visitor);
- virtual ~BucketVisitorCall();
+ public:
+ BucketVisitorCall(BucketVisitor *visitor);
+ virtual ~BucketVisitorCall();
- void operator()(Bucket *bucket) const;
- };
+ void operator()(Bucket *bucket) const;
+ };
public:
- /**
- * Construct empty binary queue
- */
- BinaryQueue();
-
- /**
- * Construct binary queue via bare copy of other binary queue
- *
- * @param[in] other Other binary queue to copy from
- * @warning One cannot assume that bucket structure is preserved during copy
- */
- BinaryQueue(const BinaryQueue &other);
-
- /**
- * Destructor
- */
- virtual ~BinaryQueue();
-
- /**
- * Construct binary queue via bare copy of other binary queue
- *
- * @param[in] other Other binary queue to copy from
- * @warning One cannot assume that bucket structure is preserved during copy
- */
- const BinaryQueue &operator=(const BinaryQueue &other);
-
- /**
- * Append copy of @a bufferSize bytes from memory pointed by @a buffer
- * to the end of binary queue. Uses default deleter based on free.
- *
- * @return none
- * @param[in] buffer Pointer to buffer to copy data from
- * @param[in] bufferSize Number of bytes to copy
- * @exception std::bad_alloc Cannot allocate memory to hold additional data
- * @see BinaryQueue::BufferDeleterFree
- */
- void AppendCopy(const void *buffer, size_t bufferSize);
-
- /**
- * Append @a bufferSize bytes from memory pointed by @a buffer
- * to the end of binary queue. Uses custom provided deleter.
- * Responsibility for deleting provided buffer is transfered to BinaryQueue.
- *
- * @return none
- * @param[in] buffer Pointer to data buffer
- * @param[in] bufferSize Number of bytes available in buffer
- * @param[in] deleter Pointer to deleter procedure used to free provided
- * buffer
- * @param[in] userParam User parameter passed to deleter routine
- * @exception std::bad_alloc Cannot allocate memory to hold additional data
- */
- void AppendUnmanaged(
- const void *buffer,
- size_t bufferSize,
- BufferDeleter deleter =
- &BinaryQueue::BufferDeleterFree,
- void *userParam = NULL);
-
- /**
- * Append copy of other binary queue to the end of this binary queue
- *
- * @return none
- * @param[in] other Constant reference to other binary queue to copy data
- * from
- * @exception std::bad_alloc Cannot allocate memory to hold additional data
- * @warning One cannot assume that bucket structure is preserved during copy
- */
- void AppendCopyFrom(const BinaryQueue &other);
-
- /**
- * Move bytes from other binary queue to the end of this binary queue.
- * This also removes all bytes from other binary queue.
- * This method is designed to be as fast as possible (only pointer swaps)
- * and is suggested over making copies of binary queues.
- * Bucket structure is preserved after operation.
- *
- * @return none
- * @param[in] other Reference to other binary queue to move data from
- * @exception std::bad_alloc Cannot allocate memory to hold additional data
- */
- void AppendMoveFrom(BinaryQueue &other);
-
- /**
- * Append copy of binary queue to the end of other binary queue
- *
- * @return none
- * @param[in] other Constant reference to other binary queue to copy data to
- * @exception std::bad_alloc Cannot allocate memory to hold additional data
- * @warning One cannot assume that bucket structure is preserved during copy
- */
- void AppendCopyTo(BinaryQueue &other) const;
-
- /**
- * Move bytes from binary queue to the end of other binary queue.
- * This also removes all bytes from binary queue.
- * This method is designed to be as fast as possible (only pointer swaps)
- * and is suggested over making copies of binary queues.
- * Bucket structure is preserved after operation.
- *
- * @return none
- * @param[in] other Reference to other binary queue to move data to
- * @exception std::bad_alloc Cannot allocate memory to hold additional data
- */
- void AppendMoveTo(BinaryQueue &other);
-
- /**
- * Retrieve total size of all data contained in binary queue
- *
- * @return Number of bytes in binary queue
- */
- size_t Size() const;
-
- /**
- * Remove all data from binary queue
- *
- * @return none
- */
- void Clear();
-
- /**
- * Check if binary queue is empty
- *
- * @return true if binary queue is empty, false otherwise
- */
- bool Empty() const;
-
- /**
- * Remove @a size bytes from beginning of binary queue
- *
- * @return none
- * @param[in] size Number of bytes to remove
- * @exception BinaryQueue::Exception::OutOfData Number of bytes is larger
- * than available bytes in binary queue
- */
- void Consume(size_t size);
-
- /**
- * Retrieve @a bufferSize bytes from beginning of binary queue and copy them
- * to user supplied buffer
- *
- * @return none
- * @param[in] buffer Pointer to user buffer to receive bytes
- * @param[in] bufferSize Size of user buffer pointed by @a buffer
- * @exception BinaryQueue::Exception::OutOfData Number of bytes to flatten
- * is larger than available bytes in binary queue
- */
- void Flatten(void *buffer, size_t bufferSize) const;
-
- /**
- * Retrieve @a bufferSize bytes from beginning of binary queue, copy them
- * to user supplied buffer, and remove from binary queue
- *
- * @return none
- * @param[in] buffer Pointer to user buffer to receive bytes
- * @param[in] bufferSize Size of user buffer pointed by @a buffer
- * @exception BinaryQueue::Exception::OutOfData Number of bytes to flatten
- * is larger than available bytes in binary queue
- */
- void FlattenConsume(void *buffer, size_t bufferSize);
-
- /**
- * Visit each buffer with data using visitor object
- *
- * @return none
- * @param[in] visitor Pointer to bucket visitor
- * @see BinaryQueue::BucketVisitor
- */
- void VisitBuckets(BucketVisitor *visitor) const;
-
- /**
- * IAbstractInput interface
- */
- virtual BinaryQueueAutoPtr Read(size_t size);
-
- /**
- * IAbstractOutput interface
- */
- virtual size_t Write(const BinaryQueue &buffer, size_t bufferSize);
+ /**
+ * Construct empty binary queue
+ */
+ BinaryQueue();
+
+ /**
+ * Construct binary queue via bare copy of other binary queue
+ *
+ * @param[in] other Other binary queue to copy from
+ * @warning One cannot assume that bucket structure is preserved during copy
+ */
+ BinaryQueue(const BinaryQueue &other);
+
+ /**
+ * Destructor
+ */
+ virtual ~BinaryQueue();
+
+ /**
+ * Construct binary queue via bare copy of other binary queue
+ *
+ * @param[in] other Other binary queue to copy from
+ * @warning One cannot assume that bucket structure is preserved during copy
+ */
+ const BinaryQueue &operator=(const BinaryQueue &other);
+
+ /**
+ * Append copy of @a bufferSize bytes from memory pointed by @a buffer
+ * to the end of binary queue. Uses default deleter based on free.
+ *
+ * @return none
+ * @param[in] buffer Pointer to buffer to copy data from
+ * @param[in] bufferSize Number of bytes to copy
+ * @exception std::bad_alloc Cannot allocate memory to hold additional data
+ * @see BinaryQueue::BufferDeleterFree
+ */
+ void AppendCopy(const void *buffer, size_t bufferSize);
+
+ /**
+ * Append @a bufferSize bytes from memory pointed by @a buffer
+ * to the end of binary queue. Uses custom provided deleter.
+ * Responsibility for deleting provided buffer is transfered to BinaryQueue.
+ *
+ * @return none
+ * @param[in] buffer Pointer to data buffer
+ * @param[in] bufferSize Number of bytes available in buffer
+ * @param[in] deleter Pointer to deleter procedure used to free provided
+ * buffer
+ * @param[in] userParam User parameter passed to deleter routine
+ * @exception std::bad_alloc Cannot allocate memory to hold additional data
+ */
+ void AppendUnmanaged(
+ const void *buffer,
+ size_t bufferSize,
+ BufferDeleter deleter =
+ &BinaryQueue::BufferDeleterFree,
+ void *userParam = NULL);
+
+ /**
+ * Append copy of other binary queue to the end of this binary queue
+ *
+ * @return none
+ * @param[in] other Constant reference to other binary queue to copy data
+ * from
+ * @exception std::bad_alloc Cannot allocate memory to hold additional data
+ * @warning One cannot assume that bucket structure is preserved during copy
+ */
+ void AppendCopyFrom(const BinaryQueue &other);
+
+ /**
+ * Move bytes from other binary queue to the end of this binary queue.
+ * This also removes all bytes from other binary queue.
+ * This method is designed to be as fast as possible (only pointer swaps)
+ * and is suggested over making copies of binary queues.
+ * Bucket structure is preserved after operation.
+ *
+ * @return none
+ * @param[in] other Reference to other binary queue to move data from
+ * @exception std::bad_alloc Cannot allocate memory to hold additional data
+ */
+ void AppendMoveFrom(BinaryQueue &other);
+
+ /**
+ * Append copy of binary queue to the end of other binary queue
+ *
+ * @return none
+ * @param[in] other Constant reference to other binary queue to copy data to
+ * @exception std::bad_alloc Cannot allocate memory to hold additional data
+ * @warning One cannot assume that bucket structure is preserved during copy
+ */
+ void AppendCopyTo(BinaryQueue &other) const;
+
+ /**
+ * Move bytes from binary queue to the end of other binary queue.
+ * This also removes all bytes from binary queue.
+ * This method is designed to be as fast as possible (only pointer swaps)
+ * and is suggested over making copies of binary queues.
+ * Bucket structure is preserved after operation.
+ *
+ * @return none
+ * @param[in] other Reference to other binary queue to move data to
+ * @exception std::bad_alloc Cannot allocate memory to hold additional data
+ */
+ void AppendMoveTo(BinaryQueue &other);
+
+ /**
+ * Retrieve total size of all data contained in binary queue
+ *
+ * @return Number of bytes in binary queue
+ */
+ size_t Size() const;
+
+ /**
+ * Remove all data from binary queue
+ *
+ * @return none
+ */
+ void Clear();
+
+ /**
+ * Check if binary queue is empty
+ *
+ * @return true if binary queue is empty, false otherwise
+ */
+ bool Empty() const;
+
+ /**
+ * Remove @a size bytes from beginning of binary queue
+ *
+ * @return none
+ * @param[in] size Number of bytes to remove
+ * @exception BinaryQueue::Exception::OutOfData Number of bytes is larger
+ * than available bytes in binary queue
+ */
+ void Consume(size_t size);
+
+ /**
+ * Retrieve @a bufferSize bytes from beginning of binary queue and copy them
+ * to user supplied buffer
+ *
+ * @return none
+ * @param[in] buffer Pointer to user buffer to receive bytes
+ * @param[in] bufferSize Size of user buffer pointed by @a buffer
+ * @exception BinaryQueue::Exception::OutOfData Number of bytes to flatten
+ * is larger than available bytes in binary queue
+ */
+ void Flatten(void *buffer, size_t bufferSize) const;
+
+ /**
+ * Retrieve @a bufferSize bytes from beginning of binary queue, copy them
+ * to user supplied buffer, and remove from binary queue
+ *
+ * @return none
+ * @param[in] buffer Pointer to user buffer to receive bytes
+ * @param[in] bufferSize Size of user buffer pointed by @a buffer
+ * @exception BinaryQueue::Exception::OutOfData Number of bytes to flatten
+ * is larger than available bytes in binary queue
+ */
+ void FlattenConsume(void *buffer, size_t bufferSize);
+
+ /**
+ * Visit each buffer with data using visitor object
+ *
+ * @return none
+ * @param[in] visitor Pointer to bucket visitor
+ * @see BinaryQueue::BucketVisitor
+ */
+ void VisitBuckets(BucketVisitor *visitor) const;
+
+ /**
+ * IAbstractInput interface
+ */
+ virtual BinaryQueueAutoPtr Read(size_t size);
+
+ /**
+ * IAbstractOutput interface
+ */
+ virtual size_t Write(const BinaryQueue &buffer, size_t bufferSize);
};
} // namespace AuthPasswd
namespace AuthPasswd {
namespace Colors {
namespace Text {
-extern const char* BOLD_GREEN_BEGIN;
-extern const char* BOLD_GREEN_END;
-extern const char* PURPLE_BEGIN;
-extern const char* PURPLE_END;
-extern const char* RED_BEGIN;
-extern const char* RED_END;
-extern const char* GREEN_BEGIN;
-extern const char* GREEN_END;
-extern const char* CYAN_BEGIN;
-extern const char* CYAN_END;
-extern const char* BOLD_RED_BEGIN;
-extern const char* BOLD_RED_END;
-extern const char* BOLD_YELLOW_BEGIN;
-extern const char* BOLD_YELLOW_END;
-extern const char* BOLD_GOLD_BEGIN;
-extern const char* BOLD_GOLD_END;
-extern const char* BOLD_WHITE_BEGIN;
-extern const char* BOLD_WHITE_END;
+extern const char *BOLD_GREEN_BEGIN;
+extern const char *BOLD_GREEN_END;
+extern const char *PURPLE_BEGIN;
+extern const char *PURPLE_END;
+extern const char *RED_BEGIN;
+extern const char *RED_END;
+extern const char *GREEN_BEGIN;
+extern const char *GREEN_END;
+extern const char *CYAN_BEGIN;
+extern const char *CYAN_END;
+extern const char *BOLD_RED_BEGIN;
+extern const char *BOLD_RED_END;
+extern const char *BOLD_YELLOW_BEGIN;
+extern const char *BOLD_YELLOW_END;
+extern const char *BOLD_GOLD_BEGIN;
+extern const char *BOLD_GOLD_END;
+extern const char *BOLD_WHITE_BEGIN;
+extern const char *BOLD_WHITE_END;
} //namespace Text
namespace Html {
-extern const char* BOLD_GREEN_BEGIN;
-extern const char* BOLD_GREEN_END;
-extern const char* PURPLE_BEGIN;
-extern const char* PURPLE_END;
-extern const char* RED_BEGIN;
-extern const char* RED_END;
-extern const char* GREEN_BEGIN;
-extern const char* GREEN_END;
-extern const char* CYAN_BEGIN;
-extern const char* CYAN_END;
-extern const char* BOLD_RED_BEGIN;
-extern const char* BOLD_RED_END;
-extern const char* BOLD_YELLOW_BEGIN;
-extern const char* BOLD_YELLOW_END;
-extern const char* BOLD_GOLD_BEGIN;
-extern const char* BOLD_GOLD_END;
-extern const char* BOLD_WHITE_BEGIN;
-extern const char* BOLD_WHITE_END;
+extern const char *BOLD_GREEN_BEGIN;
+extern const char *BOLD_GREEN_END;
+extern const char *PURPLE_BEGIN;
+extern const char *PURPLE_END;
+extern const char *RED_BEGIN;
+extern const char *RED_END;
+extern const char *GREEN_BEGIN;
+extern const char *GREEN_END;
+extern const char *CYAN_BEGIN;
+extern const char *CYAN_END;
+extern const char *BOLD_RED_BEGIN;
+extern const char *BOLD_RED_END;
+extern const char *BOLD_YELLOW_BEGIN;
+extern const char *BOLD_YELLOW_END;
+extern const char *BOLD_GOLD_BEGIN;
+extern const char *BOLD_GOLD_END;
+extern const char *BOLD_WHITE_BEGIN;
+extern const char *BOLD_WHITE_END;
} //namespace Html
} //namespace Colors
} //namespace AuthPasswd
namespace AuthPasswd {
void LogUnhandledException(const std::string &str);
void LogUnhandledException(const std::string &str,
- const char *filename,
- int line,
- const char *function);
+ const char *filename,
+ int line,
+ const char *function);
}
namespace AuthPasswd {
class COMMON_API Exception {
private:
- static unsigned int m_exceptionCount;
- static Exception* m_lastException;
- static void (*m_terminateHandler)();
-
- static void AddRef(Exception* exception)
- {
- if (!m_exceptionCount) {
- m_terminateHandler = std::set_terminate(&TerminateHandler);
- }
-
- ++m_exceptionCount;
- m_lastException = exception;
- }
-
- static void UnRef(Exception* e)
- {
- if (m_lastException == e) {
- m_lastException = NULL;
- }
-
- --m_exceptionCount;
-
- if (!m_exceptionCount) {
- std::set_terminate(m_terminateHandler);
- m_terminateHandler = NULL;
- }
- }
-
- static void TerminateHandler()
- {
- if (m_lastException != NULL) {
- DisplayKnownException(*m_lastException);
- abort();
- } else {
- DisplayUnknownException();
- abort();
- }
- }
-
- Exception *m_reason;
- std::string m_path;
- std::string m_function;
- int m_line;
+ static unsigned int m_exceptionCount;
+ static Exception *m_lastException;
+ static void (*m_terminateHandler)();
+
+ static void AddRef(Exception *exception) {
+ if (!m_exceptionCount)
+ m_terminateHandler = std::set_terminate(&TerminateHandler);
+
+ ++m_exceptionCount;
+ m_lastException = exception;
+ }
+
+ static void UnRef(Exception *e) {
+ if (m_lastException == e)
+ m_lastException = NULL;
+
+ --m_exceptionCount;
+
+ if (!m_exceptionCount) {
+ std::set_terminate(m_terminateHandler);
+ m_terminateHandler = NULL;
+ }
+ }
+
+ static void TerminateHandler() {
+ if (m_lastException != NULL) {
+ DisplayKnownException(*m_lastException);
+ abort();
+ } else {
+ DisplayUnknownException();
+ abort();
+ }
+ }
+
+ Exception *m_reason;
+ std::string m_path;
+ std::string m_function;
+ int m_line;
protected:
- std::string m_message;
- std::string m_className;
+ std::string m_message;
+ std::string m_className;
public:
- static std::string KnownExceptionToString(const Exception &e)
- {
- std::ostringstream message;
- message <<
- "\033[1;5;31m\n=== Unhandled AuthPasswd exception occurred ===\033[m\n\n";
- message << "\033[1;33mException trace:\033[m\n\n";
- message << e.DumpToString();
- message << "\033[1;31m\n=== Will now abort ===\033[m\n";
-
- return message.str();
- }
-
- static std::string UnknownExceptionToString()
- {
- std::ostringstream message;
- message <<
- "\033[1;5;31m\n=== Unhandled non-AuthPasswd exception occurred ===\033[m\n\n";
- message << "\033[1;31m\n=== Will now abort ===\033[m\n";
-
- return message.str();
- }
-
- static void DisplayKnownException(const Exception& e)
- {
- LogUnhandledException(KnownExceptionToString(e).c_str());
- }
-
- static void DisplayUnknownException()
- {
- LogUnhandledException(UnknownExceptionToString().c_str());
- }
-
- Exception(const Exception &other)
- {
- // Deep copy
- if (other.m_reason != NULL) {
- m_reason = new Exception(*other.m_reason);
- } else {
- m_reason = NULL;
- }
-
- m_message = other.m_message;
- m_path = other.m_path;
- m_function = other.m_function;
- m_line = other.m_line;
-
- m_className = other.m_className;
-
- AddRef(this);
- }
-
- const Exception &operator =(const Exception &other)
- {
- if (this == &other) {
- return *this;
- }
-
- // Deep copy
- if (other.m_reason != NULL) {
- m_reason = new Exception(*other.m_reason);
- } else {
- m_reason = NULL;
- }
-
- m_message = other.m_message;
- m_path = other.m_path;
- m_function = other.m_function;
- m_line = other.m_line;
-
- m_className = other.m_className;
-
- AddRef(this);
-
- return *this;
- }
-
- Exception(const char *path,
- const char *function,
- int line,
- const std::string &message) :
- m_reason(NULL),
- m_path(path),
- m_function(function),
- m_line(line),
- m_message(message)
- {
- AddRef(this);
- }
-
- Exception(const char *path,
- const char *function,
- int line,
- const Exception &reason,
- const std::string &message) :
- m_reason(new Exception(reason)),
- m_path(path),
- m_function(function),
- m_line(line),
- m_message(message)
- {
- AddRef(this);
- }
-
- virtual ~Exception() throw()
- {
- if (m_reason != NULL) {
- delete m_reason;
- m_reason = NULL;
- }
-
- UnRef(this);
- }
-
- void Dump() const
- {
- // Show reason first
- if (m_reason != NULL) {
- m_reason->Dump();
- }
-
- // Afterward, dump exception
- const char *file = strchr(m_path.c_str(), '/');
-
- if (file == NULL) {
- file = m_path.c_str();
- } else {
- ++file;
- }
-
- printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
- file, m_line,
- m_function.c_str(),
- m_className.c_str(),
- m_message.empty() ? "<EMPTY>" : m_message.c_str());
- }
-
- std::string DumpToString() const
- {
- std::string ret;
- if (m_reason != NULL) {
- ret = m_reason->DumpToString();
- }
-
- const char *file = strchr(m_path.c_str(), '/');
-
- if (file == NULL) {
- file = m_path.c_str();
- } else {
- ++file;
- }
-
- char buf[1024];
- snprintf(buf,
- sizeof(buf),
- "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
- file,
- m_line,
- m_function.c_str(),
- m_className.c_str(),
- m_message.empty() ? "<EMPTY>" : m_message.c_str());
-
- buf[sizeof(buf) - 1] = '\n';
- ret += buf;
-
- return ret;
- }
-
- Exception *GetReason() const
- {
- return m_reason;
- }
-
- std::string GetPath() const
- {
- return m_path;
- }
-
- std::string GetFunction() const
- {
- return m_function;
- }
-
- int GetLine() const
- {
- return m_line;
- }
-
- std::string GetMessage() const
- {
- return m_message;
- }
-
- std::string GetClassName() const
- {
- return m_className;
- }
+ static std::string KnownExceptionToString(const Exception &e) {
+ std::ostringstream message;
+ message <<
+ "\033[1;5;31m\n=== Unhandled AuthPasswd exception occurred ===\033[m\n\n";
+ message << "\033[1;33mException trace:\033[m\n\n";
+ message << e.DumpToString();
+ message << "\033[1;31m\n=== Will now abort ===\033[m\n";
+ return message.str();
+ }
+
+ static std::string UnknownExceptionToString() {
+ std::ostringstream message;
+ message <<
+ "\033[1;5;31m\n=== Unhandled non-AuthPasswd exception occurred ===\033[m\n\n";
+ message << "\033[1;31m\n=== Will now abort ===\033[m\n";
+ return message.str();
+ }
+
+ static void DisplayKnownException(const Exception &e) {
+ LogUnhandledException(KnownExceptionToString(e).c_str());
+ }
+
+ static void DisplayUnknownException() {
+ LogUnhandledException(UnknownExceptionToString().c_str());
+ }
+
+ Exception(const Exception &other) {
+ // Deep copy
+ if (other.m_reason != NULL)
+ m_reason = new Exception(*other.m_reason);
+ else
+ m_reason = NULL;
+
+ m_message = other.m_message;
+ m_path = other.m_path;
+ m_function = other.m_function;
+ m_line = other.m_line;
+ m_className = other.m_className;
+ AddRef(this);
+ }
+
+ const Exception &operator =(const Exception &other) {
+ if (this == &other)
+ return *this;
+
+ // Deep copy
+ if (other.m_reason != NULL)
+ m_reason = new Exception(*other.m_reason);
+ else
+ m_reason = NULL;
+
+ m_message = other.m_message;
+ m_path = other.m_path;
+ m_function = other.m_function;
+ m_line = other.m_line;
+ m_className = other.m_className;
+ AddRef(this);
+ return *this;
+ }
+
+ Exception(const char *path,
+ const char *function,
+ int line,
+ const std::string &message) :
+ m_reason(NULL),
+ m_path(path),
+ m_function(function),
+ m_line(line),
+ m_message(message) {
+ AddRef(this);
+ }
+
+ Exception(const char *path,
+ const char *function,
+ int line,
+ const Exception &reason,
+ const std::string &message) :
+ m_reason(new Exception(reason)),
+ m_path(path),
+ m_function(function),
+ m_line(line),
+ m_message(message) {
+ AddRef(this);
+ }
+
+ virtual ~Exception() throw() {
+ if (m_reason != NULL) {
+ delete m_reason;
+ m_reason = NULL;
+ }
+
+ UnRef(this);
+ }
+
+ void Dump() const {
+ // Show reason first
+ if (m_reason != NULL)
+ m_reason->Dump();
+
+ // Afterward, dump exception
+ const char *file = strchr(m_path.c_str(), '/');
+
+ if (file == NULL)
+ file = m_path.c_str();
+ else
+ ++file;
+
+ printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
+ file, m_line,
+ m_function.c_str(),
+ m_className.c_str(),
+ m_message.empty() ? "<EMPTY>" : m_message.c_str());
+ }
+
+ std::string DumpToString() const {
+ std::string ret;
+
+ if (m_reason != NULL)
+ ret = m_reason->DumpToString();
+
+ const char *file = strchr(m_path.c_str(), '/');
+
+ if (file == NULL)
+ file = m_path.c_str();
+ else
+ ++file;
+
+ char buf[1024];
+ snprintf(buf,
+ sizeof(buf),
+ "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
+ file,
+ m_line,
+ m_function.c_str(),
+ m_className.c_str(),
+ m_message.empty() ? "<EMPTY>" : m_message.c_str());
+ buf[sizeof(buf) - 1] = '\n';
+ ret += buf;
+ return ret;
+ }
+
+ Exception *GetReason() const {
+ return m_reason;
+ }
+
+ std::string GetPath() const {
+ return m_path;
+ }
+
+ std::string GetFunction() const {
+ return m_function;
+ }
+
+ int GetLine() const {
+ return m_line;
+ }
+
+ std::string GetMessage() const {
+ return m_message;
+ }
+
+ std::string GetClassName() const {
+ return m_className;
+ }
};
} // namespace AuthPasswd
#define Try try
#define Throw(ClassName) \
- throw ClassName(__FILE__, __FUNCTION__, __LINE__)
+ throw ClassName(__FILE__, __FUNCTION__, __LINE__)
-#define ThrowMsg(ClassName, Message) \
- do \
- { \
- std::ostringstream dplLoggingStream; \
- dplLoggingStream << Message; \
- throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str()); \
- } while (0)
+#define ThrowMsg(ClassName, Message) \
+ do { \
+ std::ostringstream dplLoggingStream; \
+ dplLoggingStream << Message; \
+ throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str()); \
+ } while (0)
#define ReThrow(ClassName) \
- throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception)
+ throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception)
-#define ReThrowMsg(ClassName, Message) \
- throw ClassName(__FILE__, \
- __FUNCTION__, \
- __LINE__, \
- _rethrown_exception, \
- Message)
+#define ReThrowMsg(ClassName, Message) \
+ throw ClassName(__FILE__, \
+ __FUNCTION__, \
+ __LINE__, \
+ _rethrown_exception, \
+ Message)
#define Catch(ClassName) \
- catch (const ClassName &_rethrown_exception)
-
-#define DECLARE_EXCEPTION_TYPE(BaseClass, Class) \
- class Class : \
- public BaseClass \
- { \
- public: \
- Class(const char *path, \
- const char *function, \
- int line, \
- const std::string & message = std::string()) : \
- BaseClass(path, function, line, message) \
- { \
- BaseClass::m_className = #Class; \
- } \
- \
- Class(const char *path, \
- const char *function, \
- int line, \
- const AuthPasswd::Exception & reason, \
- const std::string & message = std::string()) : \
- BaseClass(path, function, line, reason, message) \
- { \
- BaseClass::m_className = #Class; \
- } \
- };
+ catch (const ClassName &_rethrown_exception)
+
+#define DECLARE_EXCEPTION_TYPE(BaseClass, Class) \
+ class Class : public BaseClass { \
+ public: \
+ Class(const char *path, \
+ const char *function, \
+ int line, \
+ const std::string & message = std::string()) : \
+ BaseClass(path, function, line, message) { \
+ BaseClass::m_className = #Class; \
+ } \
+ Class(const char *path, \
+ const char *function, \
+ int line, \
+ const AuthPasswd::Exception & reason, \
+ const std::string & message = std::string()) : \
+ BaseClass(path, function, line, reason, message) { \
+ BaseClass::m_className = #Class; \
+ } \
+ };
#define UNHANDLED_EXCEPTION_HANDLER_BEGIN try
-#define UNHANDLED_EXCEPTION_HANDLER_END \
- catch (const AuthPasswd::Exception &exception) \
- { \
- std::ostringstream msg; \
- msg << AuthPasswd::Exception::KnownExceptionToString(exception); \
- AuthPasswd::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \
- abort(); \
- } \
- catch (std::exception& e) \
- { \
- std::ostringstream msg; \
- msg << e.what(); \
- msg << "\n"; \
- msg << AuthPasswd::Exception::UnknownExceptionToString(); \
- AuthPasswd::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \
- abort(); \
- } \
- catch (...) \
- { \
- std::ostringstream msg; \
- msg << AuthPasswd::Exception::UnknownExceptionToString(); \
- AuthPasswd::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \
- abort(); \
- }
+#define UNHANDLED_EXCEPTION_HANDLER_END \
+ catch (const AuthPasswd::Exception &exception) { \
+ std::ostringstream msg; \
+ msg << AuthPasswd::Exception::KnownExceptionToString(exception); \
+ AuthPasswd::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \
+ abort(); \
+ } catch (std::exception& e) { \
+ std::ostringstream msg; \
+ msg << e.what(); \
+ msg << "\n"; \
+ msg << AuthPasswd::Exception::UnknownExceptionToString(); \
+ AuthPasswd::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \
+ abort(); \
+ } catch (...) { \
+ std::ostringstream msg; \
+ msg << AuthPasswd::Exception::UnknownExceptionToString(); \
+ AuthPasswd::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \
+ abort(); \
+ }
namespace AuthPasswd {
namespace CommonException {
* important messages.
*/
DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from
- // underlying libraries or
- // kernel
+// underlying libraries or
+// kernel
}
}
template<typename T>
class FstreamAccessors : T::__filebuf_type {
- typedef FstreamAccessors<T> MyType;
+ typedef FstreamAccessors<T> MyType;
public:
- static int GetFd(T &strm) {
- return static_cast<MyType *>(strm.rdbuf())->_M_file.fd();
- }
+ static int GetFd(T &strm)
+ {
+ return static_cast<MyType *>(strm.rdbuf())->_M_file.fd();
+ }
};
} // namespace DPL
namespace AuthPasswd {
class Noncopyable {
public:
- Noncopyable() {}
- virtual ~Noncopyable() {}
+ Noncopyable() {}
+ virtual ~Noncopyable() {}
private:
- Noncopyable(const Noncopyable &);
- const Noncopyable &operator=(const Noncopyable &);
+ Noncopyable(const Noncopyable &);
+ const Noncopyable &operator=(const Noncopyable &);
};
} // namespace AuthPasswd
// Abstract data stream buffer
class IStream {
public:
- virtual void Read(size_t num, void * bytes) = 0;
- virtual void Write(size_t num, const void * bytes) = 0;
- virtual ~IStream(){}
+ virtual void Read(size_t num, void *bytes) = 0;
+ virtual void Write(size_t num, const void *bytes) = 0;
+ virtual ~IStream() {}
};
// Serializable interface
class ISerializable {
public:
- ISerializable() {}
- ISerializable(IStream&) {}
- virtual void Serialize(IStream &) const = 0;
- virtual ~ISerializable() {}
+ ISerializable() {}
+ ISerializable(IStream &) {}
+ virtual void Serialize(IStream &) const = 0;
+ virtual ~ISerializable() {}
};
struct Serialization {
- // serialization
- // normal functions
-
- // ISerializable objects
- static void Serialize(IStream& stream, const ISerializable& object)
- {
- object.Serialize(stream);
- }
- static void Serialize(IStream& stream, const ISerializable* const object)
- {
- object->Serialize(stream);
- }
-
- // char
- static void Serialize(IStream& stream, const char value)
- {
- stream.Write(sizeof(value), &value);
- }
- static void Serialize(IStream& stream, const char* const value)
- {
- stream.Write(sizeof(*value), value);
- }
-
- // unsigned char
- static void Serialize(IStream& stream, const unsigned char value)
- {
- stream.Write(sizeof(value), &value);
- }
- static void Serialize(IStream& stream, const unsigned char* const value)
- {
- stream.Write(sizeof(*value), value);
- }
-
- // unsigned int
- static void Serialize(IStream& stream, const unsigned value)
- {
- stream.Write(sizeof(value), &value);
- }
- static void Serialize(IStream& stream, const unsigned* const value)
- {
- stream.Write(sizeof(*value), value);
- }
-
- // int
- static void Serialize(IStream& stream, const int value)
- {
- stream.Write(sizeof(value), &value);
- }
- static void Serialize(IStream& stream, const int* const value)
- {
- stream.Write(sizeof(*value), value);
- }
-
- // bool
- static void Serialize(IStream& stream, const bool value)
- {
- stream.Write(sizeof(value), &value);
- }
- static void Serialize(IStream& stream, const bool* const value)
- {
- stream.Write(sizeof(*value), value);
- }
-
- // time_t
- static void Serialize(IStream& stream, const time_t value)
- {
- stream.Write(sizeof(value), &value);
- }
- static void Serialize(IStream& stream, const time_t* const value)
- {
- stream.Write(sizeof(*value), value);
- }
-
- // std::string
- static void Serialize(IStream& stream, const std::string& str)
- {
- int length = str.size();
- stream.Write(sizeof(length), &length);
- stream.Write(length, str.c_str());
- }
- static void Serialize(IStream& stream, const std::string* const str)
- {
- int length = str->size();
- stream.Write(sizeof(length), &length);
- stream.Write(length, str->c_str());
- }
-
- // STL templates
-
- // std::list
- template <typename T>
- static void Serialize(IStream& stream, const std::list<T>& list)
- {
- int length = list.size();
- stream.Write(sizeof(length), &length);
- for (typename std::list<T>::const_iterator list_iter = list.begin();
- list_iter != list.end(); list_iter++)
- {
- Serialize(stream, *list_iter);
- }
- }
- template <typename T>
- static void Serialize(IStream& stream, const std::list<T>* const list)
- {
- Serialize(stream, *list);
- }
-
- // std::vector
- template <typename T>
- static void Serialize(IStream& stream, const std::vector<T>& vec)
- {
- int length = vec.size();
- stream.Write(sizeof(length), &length);
- for (typename std::vector<T>::const_iterator vec_iter = vec.begin();
- vec_iter != vec.end(); vec_iter++)
- {
- Serialize(stream, *vec_iter);
- }
- }
- template <typename T>
- static void Serialize(IStream& stream, const std::vector<T>* const vec)
- {
- Serialize(stream, *vec);
- }
-
- // std::set
- template <typename T>
- static void Serialize(IStream& stream, const std::set<T>& set)
- {
- size_t length = set.size();
- stream.Write(sizeof(length), &length);
- for (const auto &item : set) {
- Serialize(stream, item);
- }
- }
-
- // std::pair
- template <typename A, typename B>
- static void Serialize(IStream& stream, const std::pair<A, B>& p)
- {
- Serialize(stream, p.first);
- Serialize(stream, p.second);
- }
- template <typename A, typename B>
- static void Serialize(IStream& stream, const std::pair<A, B>* const p)
- {
- Serialize(stream, *p);
- }
-
- // std::map
- template <typename K, typename T>
- static void Serialize(IStream& stream, const std::map<K, T>& map)
- {
- int length = map.size();
- stream.Write(sizeof(length), &length);
- typename std::map<K, T>::const_iterator it;
- for (it = map.begin(); it != map.end(); ++it) {
- Serialize(stream, (*it).first);
- Serialize(stream, (*it).second);
- }
- }
- template <typename K, typename T>
- static void Serialize(IStream& stream, const std::map<K, T>* const map)
- {
- Serialize(stream, *map);
- }
-
- // std::unique_ptr
- template <typename T>
- static void Serialize(IStream& stream, const std::unique_ptr<T>& p)
- {
- Serialize(stream, *p);
- }
-
- // std::shared_ptr
- template <typename T>
- static void Serialize(IStream& stream, const std::shared_ptr<T>& p)
- {
- Serialize(stream, *p);
- }
+ // serialization
+ // normal functions
+
+ // ISerializable objects
+ static void Serialize(IStream &stream, const ISerializable &object) {
+ object.Serialize(stream);
+ }
+ static void Serialize(IStream &stream, const ISerializable *const object) {
+ object->Serialize(stream);
+ }
+
+ // char
+ static void Serialize(IStream &stream, const char value) {
+ stream.Write(sizeof(value), &value);
+ }
+ static void Serialize(IStream &stream, const char *const value) {
+ stream.Write(sizeof(*value), value);
+ }
+
+ // unsigned char
+ static void Serialize(IStream &stream, const unsigned char value) {
+ stream.Write(sizeof(value), &value);
+ }
+ static void Serialize(IStream &stream, const unsigned char *const value) {
+ stream.Write(sizeof(*value), value);
+ }
+
+ // unsigned int
+ static void Serialize(IStream &stream, const unsigned value) {
+ stream.Write(sizeof(value), &value);
+ }
+ static void Serialize(IStream &stream, const unsigned *const value) {
+ stream.Write(sizeof(*value), value);
+ }
+
+ // int
+ static void Serialize(IStream &stream, const int value) {
+ stream.Write(sizeof(value), &value);
+ }
+ static void Serialize(IStream &stream, const int *const value) {
+ stream.Write(sizeof(*value), value);
+ }
+
+ // bool
+ static void Serialize(IStream &stream, const bool value) {
+ stream.Write(sizeof(value), &value);
+ }
+ static void Serialize(IStream &stream, const bool *const value) {
+ stream.Write(sizeof(*value), value);
+ }
+
+ // time_t
+ static void Serialize(IStream &stream, const time_t value) {
+ stream.Write(sizeof(value), &value);
+ }
+ static void Serialize(IStream &stream, const time_t *const value) {
+ stream.Write(sizeof(*value), value);
+ }
+
+ // std::string
+ static void Serialize(IStream &stream, const std::string &str) {
+ int length = str.size();
+ stream.Write(sizeof(length), &length);
+ stream.Write(length, str.c_str());
+ }
+ static void Serialize(IStream &stream, const std::string *const str) {
+ int length = str->size();
+ stream.Write(sizeof(length), &length);
+ stream.Write(length, str->c_str());
+ }
+
+ // STL templates
+
+ // std::list
+ template <typename T>
+ static void Serialize(IStream &stream, const std::list<T> &list) {
+ int length = list.size();
+ stream.Write(sizeof(length), &length);
+
+ for (typename std::list<T>::const_iterator list_iter = list.begin();
+ list_iter != list.end(); list_iter++)
+ Serialize(stream, *list_iter);
+ }
+ template <typename T>
+ static void Serialize(IStream &stream, const std::list<T> *const list) {
+ Serialize(stream, *list);
+ }
+
+ // std::vector
+ template <typename T>
+ static void Serialize(IStream &stream, const std::vector<T> &vec) {
+ int length = vec.size();
+ stream.Write(sizeof(length), &length);
+
+ for (typename std::vector<T>::const_iterator vec_iter = vec.begin();
+ vec_iter != vec.end(); vec_iter++)
+ Serialize(stream, *vec_iter);
+ }
+ template <typename T>
+ static void Serialize(IStream &stream, const std::vector<T> *const vec) {
+ Serialize(stream, *vec);
+ }
+
+ // std::set
+ template <typename T>
+ static void Serialize(IStream &stream, const std::set<T> &set) {
+ size_t length = set.size();
+ stream.Write(sizeof(length), &length);
+
+ for (const auto &item : set)
+ Serialize(stream, item);
+ }
+
+ // std::pair
+ template <typename A, typename B>
+ static void Serialize(IStream &stream, const std::pair<A, B> &p) {
+ Serialize(stream, p.first);
+ Serialize(stream, p.second);
+ }
+ template <typename A, typename B>
+ static void Serialize(IStream &stream, const std::pair<A, B> *const p) {
+ Serialize(stream, *p);
+ }
+
+ // std::map
+ template <typename K, typename T>
+ static void Serialize(IStream &stream, const std::map<K, T> &map) {
+ int length = map.size();
+ stream.Write(sizeof(length), &length);
+ typename std::map<K, T>::const_iterator it;
+
+ for (it = map.begin(); it != map.end(); ++it) {
+ Serialize(stream, (*it).first);
+ Serialize(stream, (*it).second);
+ }
+ }
+ template <typename K, typename T>
+ static void Serialize(IStream &stream, const std::map<K, T> *const map) {
+ Serialize(stream, *map);
+ }
+
+ // std::unique_ptr
+ template <typename T>
+ static void Serialize(IStream &stream, const std::unique_ptr<T> &p) {
+ Serialize(stream, *p);
+ }
+
+ // std::shared_ptr
+ template <typename T>
+ static void Serialize(IStream &stream, const std::shared_ptr<T> &p) {
+ Serialize(stream, *p);
+ }
}; // struct Serialization
struct Deserialization {
- // deserialization
- // normal functions
-
- // ISerializable objects
- // T instead of ISerializable is needed to call proper constructor
- template <typename T>
- static void Deserialize(IStream& stream, T& object)
- {
- object = T(stream);
- }
- template <typename T>
- static void Deserialize(IStream& stream, T*& object)
- {
- object = new T(stream);
- }
-
- // char
- static void Deserialize(IStream& stream, char& value)
- {
- stream.Read(sizeof(value), &value);
- }
- static void Deserialize(IStream& stream, char*& value)
- {
- value = new char;
- stream.Read(sizeof(*value), value);
- }
-
- // unsigned char
- static void Deserialize(IStream& stream, unsigned char& value)
- {
- stream.Read(sizeof(value), &value);
- }
- static void Deserialize(IStream& stream, unsigned char*& value)
- {
- value = new unsigned char;
- stream.Read(sizeof(*value), value);
- }
-
- // unsigned int
- static void Deserialize(IStream& stream, unsigned& value)
- {
- stream.Read(sizeof(value), &value);
- }
- static void Deserialize(IStream& stream, unsigned*& value)
- {
- value = new unsigned;
- stream.Read(sizeof(*value), value);
- }
-
- // int
- static void Deserialize(IStream& stream, int& value)
- {
- stream.Read(sizeof(value), &value);
- }
- static void Deserialize(IStream& stream, int*& value)
- {
- value = new int;
- stream.Read(sizeof(*value), value);
- }
-
- // bool
- static void Deserialize(IStream& stream, bool& value)
- {
- stream.Read(sizeof(value), &value);
- }
- static void Deserialize(IStream& stream, bool*& value)
- {
- value = new bool;
- stream.Read(sizeof(*value), value);
- }
-
- // time_t
- static void Deserialize(IStream& stream, time_t& value)
- {
- stream.Read(sizeof(value), &value);
- }
- static void Deserialize(IStream& stream, time_t*& value)
- {
- value = new time_t;
- stream.Read(sizeof(*value), value);
- }
-
- // std::string
- static void Deserialize(IStream& stream, std::string& str)
- {
- int length;
- stream.Read(sizeof(length), &length);
- char * buf = new char[length + 1];
- stream.Read(length, buf);
- buf[length] = 0;
- str = std::string(buf);
- delete[] buf;
- }
- static void Deserialize(IStream& stream, std::string*& str)
- {
- int length;
- stream.Read(sizeof(length), &length);
- char * buf = new char[length + 1];
- stream.Read(length, buf);
- buf[length] = 0;
- str = new std::string(buf);
- delete[] buf;
- }
-
- // STL templates
-
- // std::list
- template <typename T>
- static void Deserialize(IStream& stream, std::list<T>& list)
- {
- int length;
- stream.Read(sizeof(length), &length);
- for (int i = 0; i < length; ++i) {
- T obj;
- Deserialize(stream, obj);
- list.push_back(std::move(obj));
- }
- }
- template <typename T>
- static void Deserialize(IStream& stream, std::list<T>*& list)
- {
- list = new std::list<T>;
- Deserialize(stream, *list);
- }
-
- // std::vector
- template <typename T>
- static void Deserialize(IStream& stream, std::vector<T>& vec)
- {
- int length;
- stream.Read(sizeof(length), &length);
- for (int i = 0; i < length; ++i) {
- T obj;
- Deserialize(stream, obj);
- vec.push_back(std::move(obj));
- }
- }
- template <typename T>
- static void Deserialize(IStream& stream, std::vector<T>*& vec)
- {
- vec = new std::vector<T>;
- Deserialize(stream, *vec);
- }
-
- // std::set
- template <typename T>
- static void Deserialize(IStream& stream, std::set<T>& set)
- {
- size_t length;
- stream.Read(sizeof(length), &length);
- for (size_t i = 0; i < length; ++i) {
- T obj;
- Deserialize(stream, obj);
- set.insert(std::move(obj));
- }
- }
-
- // std::pair
- template <typename A, typename B>
- static void Deserialize(IStream& stream, std::pair<A, B>& p)
- {
- Deserialize(stream, p.first);
- Deserialize(stream, p.second);
- }
- template <typename A, typename B>
- static void Deserialize(IStream& stream, std::pair<A, B>*& p)
- {
- p = new std::pair<A, B>;
- Deserialize(stream, *p);
- }
-
- // std::map
- template <typename K, typename T>
- static void Deserialize(IStream& stream, std::map<K, T>& map)
- {
- int length;
- stream.Read(sizeof(length), &length);
- for (int i = 0; i < length; ++i) {
- K key;
- T obj;
- Deserialize(stream, key);
- Deserialize(stream, obj);
- map[key] = std::move(obj);
- }
- }
- template <typename K, typename T>
- static void Deserialize(IStream& stream, std::map<K, T>*& map)
- {
- map = new std::map<K, T>;
- Deserialize(stream, *map);
- }
+ // deserialization
+ // normal functions
+
+ // ISerializable objects
+ // T instead of ISerializable is needed to call proper constructor
+ template <typename T>
+ static void Deserialize(IStream &stream, T &object) {
+ object = T(stream);
+ }
+ template <typename T>
+ static void Deserialize(IStream &stream, T *&object) {
+ object = new T(stream);
+ }
+
+ // char
+ static void Deserialize(IStream &stream, char &value) {
+ stream.Read(sizeof(value), &value);
+ }
+ static void Deserialize(IStream &stream, char *&value) {
+ value = new char;
+ stream.Read(sizeof(*value), value);
+ }
+
+ // unsigned char
+ static void Deserialize(IStream &stream, unsigned char &value) {
+ stream.Read(sizeof(value), &value);
+ }
+ static void Deserialize(IStream &stream, unsigned char *&value) {
+ value = new unsigned char;
+ stream.Read(sizeof(*value), value);
+ }
+
+ // unsigned int
+ static void Deserialize(IStream &stream, unsigned &value) {
+ stream.Read(sizeof(value), &value);
+ }
+ static void Deserialize(IStream &stream, unsigned *&value) {
+ value = new unsigned;
+ stream.Read(sizeof(*value), value);
+ }
+
+ // int
+ static void Deserialize(IStream &stream, int &value) {
+ stream.Read(sizeof(value), &value);
+ }
+ static void Deserialize(IStream &stream, int *&value) {
+ value = new int;
+ stream.Read(sizeof(*value), value);
+ }
+
+ // bool
+ static void Deserialize(IStream &stream, bool &value) {
+ stream.Read(sizeof(value), &value);
+ }
+ static void Deserialize(IStream &stream, bool *&value) {
+ value = new bool;
+ stream.Read(sizeof(*value), value);
+ }
+
+ // time_t
+ static void Deserialize(IStream &stream, time_t &value) {
+ stream.Read(sizeof(value), &value);
+ }
+ static void Deserialize(IStream &stream, time_t *&value) {
+ value = new time_t;
+ stream.Read(sizeof(*value), value);
+ }
+
+ // std::string
+ static void Deserialize(IStream &stream, std::string &str) {
+ int length;
+ stream.Read(sizeof(length), &length);
+ char *buf = new char[length + 1];
+ stream.Read(length, buf);
+ buf[length] = 0;
+ str = std::string(buf);
+ delete[] buf;
+ }
+ static void Deserialize(IStream &stream, std::string *&str) {
+ int length;
+ stream.Read(sizeof(length), &length);
+ char *buf = new char[length + 1];
+ stream.Read(length, buf);
+ buf[length] = 0;
+ str = new std::string(buf);
+ delete[] buf;
+ }
+
+ // STL templates
+
+ // std::list
+ template <typename T>
+ static void Deserialize(IStream &stream, std::list<T> &list) {
+ int length;
+ stream.Read(sizeof(length), &length);
+
+ for (int i = 0; i < length; ++i) {
+ T obj;
+ Deserialize(stream, obj);
+ list.push_back(std::move(obj));
+ }
+ }
+ template <typename T>
+ static void Deserialize(IStream &stream, std::list<T> *&list) {
+ list = new std::list<T>;
+ Deserialize(stream, *list);
+ }
+
+ // std::vector
+ template <typename T>
+ static void Deserialize(IStream &stream, std::vector<T> &vec) {
+ int length;
+ stream.Read(sizeof(length), &length);
+
+ for (int i = 0; i < length; ++i) {
+ T obj;
+ Deserialize(stream, obj);
+ vec.push_back(std::move(obj));
+ }
+ }
+ template <typename T>
+ static void Deserialize(IStream &stream, std::vector<T> *&vec) {
+ vec = new std::vector<T>;
+ Deserialize(stream, *vec);
+ }
+
+ // std::set
+ template <typename T>
+ static void Deserialize(IStream &stream, std::set<T> &set) {
+ size_t length;
+ stream.Read(sizeof(length), &length);
+
+ for (size_t i = 0; i < length; ++i) {
+ T obj;
+ Deserialize(stream, obj);
+ set.insert(std::move(obj));
+ }
+ }
+
+ // std::pair
+ template <typename A, typename B>
+ static void Deserialize(IStream &stream, std::pair<A, B> &p) {
+ Deserialize(stream, p.first);
+ Deserialize(stream, p.second);
+ }
+ template <typename A, typename B>
+ static void Deserialize(IStream &stream, std::pair<A, B> *&p) {
+ p = new std::pair<A, B>;
+ Deserialize(stream, *p);
+ }
+
+ // std::map
+ template <typename K, typename T>
+ static void Deserialize(IStream &stream, std::map<K, T> &map) {
+ int length;
+ stream.Read(sizeof(length), &length);
+
+ for (int i = 0; i < length; ++i) {
+ K key;
+ T obj;
+ Deserialize(stream, key);
+ Deserialize(stream, obj);
+ map[key] = std::move(obj);
+ }
+ }
+ template <typename K, typename T>
+ static void Deserialize(IStream &stream, std::map<K, T> *&map) {
+ map = new std::map<K, T>;
+ Deserialize(stream, *map);
+ }
}; // struct Deserialization
} // namespace AuthPasswd
namespace AuthPasswd {
template<typename Class>
class Singleton :
- private Class
-{
- //
- // Note:
- //
- // To remove posibility of instantiating directly Class,
- // make Class' default constructor protected
- //
+ private Class {
+ //
+ // Note:
+ //
+ // To remove posibility of instantiating directly Class,
+ // make Class' default constructor protected
+ //
- private:
- Singleton()
- {}
+private:
+ Singleton() {}
- static Singleton &InternalInstance();
+ static Singleton &InternalInstance();
- public:
- virtual ~Singleton()
- {}
+public:
+ virtual ~Singleton() {}
- static Class &Instance();
+ static Class &Instance();
};
} // namespace AuthPasswd
namespace AuthPasswd {
template<typename Class>
-Singleton<Class>& Singleton<Class>::InternalInstance()
+Singleton<Class> &Singleton<Class>::InternalInstance()
{
- static Singleton<Class> instance;
- return instance;
+ static Singleton<Class> instance;
+ return instance;
}
template<typename Class>
Class &Singleton<Class>::Instance()
{
- Singleton<Class>& instance = Singleton<Class>::InternalInstance();
- return instance;
+ Singleton<Class> &instance = Singleton<Class>::InternalInstance();
+ return instance;
}
} // namespace AuthPasswd
#define IMPLEMENT_SINGLETON(Type) \
- template AuthPasswd::Singleton<Type>&AuthPasswd::Singleton<Type>::InternalInstance(); \
- template Type & AuthPasswd::Singleton<Type>::Instance(); \
+ template AuthPasswd::Singleton<Type>&AuthPasswd::Singleton<Type>::InternalInstance(); \
+ template Type & AuthPasswd::Singleton<Type>::Instance(); \
#endif // AUTHPASSWD_SINGLETON_IMPL_H
#ifndef AUTHPASSWD_SINGLETON_SAFE_IMPL_H
#define AUTHPASSWD_SINGLETON_SAFE_IMPL_H
-#define IMPLEMENT_SAFE_SINGLETON(Class) \
- namespace AuthPasswd { \
- template<> \
- Singleton<Class>&Singleton<Class>::InternalInstance() \
- { \
- static Singleton<Class> instance; \
- return instance; \
- } \
- \
- template<> \
- Class & Singleton<Class>::Instance() \
- { \
- Singleton<Class>& instance = Singleton<Class>::InternalInstance(); \
- return instance; \
- } \
- \
- template Singleton<Class>&Singleton<Class>::InternalInstance(); \
- template Class & Singleton<Class>::Instance(); \
- } // namespace AuthPasswd
+#define IMPLEMENT_SAFE_SINGLETON(Class) \
+ namespace AuthPasswd { \
+ template<> \
+ Singleton<Class>&Singleton<Class>::InternalInstance() { \
+ static Singleton<Class> instance; \
+ return instance; \
+ } \
+ template<> \
+ Class & Singleton<Class>::Instance() { \
+ Singleton<Class>& instance = Singleton<Class>::InternalInstance(); \
+ return instance; \
+ } \
+ template Singleton<Class>&Singleton<Class>::InternalInstance(); \
+ template Class & Singleton<Class>::Instance(); \
+ } // namespace AuthPasswd
#endif // AUTHPASSWD_SINGLETON_SAFE_IMPL_H
namespace AuthPasswd {
COMMON_API
void AssertProc(const char *condition,
- const char *file,
- int line,
- const char *function)
+ const char *file,
+ int line,
+ const char *function)
{
-#define INTERNAL_LOG(message) \
- do \
- { \
- std::ostringstream platformLog; \
- platformLog << message; \
- AuthPasswd::Log::LogSystemSingleton::Instance().Pedantic( \
- platformLog.str().c_str(), \
- __FILE__, __LINE__, __FUNCTION__); \
- } \
- while (0)
+#define INTERNAL_LOG(message) \
+ do { \
+ std::ostringstream platformLog; \
+ platformLog << message; \
+ AuthPasswd::Log::LogSystemSingleton::Instance().Pedantic( \
+ platformLog.str().c_str(), \
+ __FILE__, __LINE__, __FUNCTION__); \
+ } while (0)
- // Try to log failed assertion to log system
- Try
- {
- INTERNAL_LOG(
- "################################################################################");
- INTERNAL_LOG(
- "### AuthPasswd assertion failed! ###");
- INTERNAL_LOG(
- "################################################################################");
- INTERNAL_LOG("### Condition: " << condition);
- INTERNAL_LOG("### File: " << file);
- INTERNAL_LOG("### Line: " << line);
- INTERNAL_LOG("### Function: " << function);
- INTERNAL_LOG(
- "################################################################################");
- } catch (Exception) {
- // Just ignore possible double errors
- }
+ // Try to log failed assertion to log system
+ Try {
+ INTERNAL_LOG(
+ "################################################################################");
+ INTERNAL_LOG(
+ "### AuthPasswd assertion failed! ###");
+ INTERNAL_LOG(
+ "################################################################################");
+ INTERNAL_LOG("### Condition: " << condition);
+ INTERNAL_LOG("### File: " << file);
+ INTERNAL_LOG("### Line: " << line);
+ INTERNAL_LOG("### Function: " << function);
+ INTERNAL_LOG(
+ "################################################################################");
+ } catch (Exception) {
+ // Just ignore possible double errors
+ }
- // Fail with c-library abort
- abort();
+ // Fail with c-library abort
+ abort();
}
} // namespace AuthPasswd
namespace AuthPasswd {
BinaryQueue::BinaryQueue() :
- m_size(0)
+ m_size(0)
{}
BinaryQueue::BinaryQueue(const BinaryQueue &other) :
- m_size(0)
+ m_size(0)
{
- AppendCopyFrom(other);
+ AppendCopyFrom(other);
}
BinaryQueue::~BinaryQueue()
{
- // Remove all remainig buckets
- Clear();
+ // Remove all remainig buckets
+ Clear();
}
const BinaryQueue &BinaryQueue::operator=(const BinaryQueue &other)
{
- if (this != &other) {
- Clear();
- AppendCopyFrom(other);
- }
+ if (this != &other) {
+ Clear();
+ AppendCopyFrom(other);
+ }
- return *this;
+ return *this;
}
void BinaryQueue::AppendCopyFrom(const BinaryQueue &other)
{
- // To speed things up, always copy as one bucket
- void *bufferCopy = malloc(other.m_size);
-
- if (bufferCopy == NULL) {
- throw std::bad_alloc();
- }
-
- try {
- other.Flatten(bufferCopy, other.m_size);
- AppendUnmanaged(bufferCopy, other.m_size, &BufferDeleterFree, NULL);
- } catch (const std::bad_alloc &) {
- // Free allocated memory
- free(bufferCopy);
- throw;
- }
+ // To speed things up, always copy as one bucket
+ void *bufferCopy = malloc(other.m_size);
+
+ if (bufferCopy == NULL)
+ throw std::bad_alloc();
+
+ try {
+ other.Flatten(bufferCopy, other.m_size);
+ AppendUnmanaged(bufferCopy, other.m_size, &BufferDeleterFree, NULL);
+ } catch (const std::bad_alloc &) {
+ // Free allocated memory
+ free(bufferCopy);
+ throw;
+ }
}
void BinaryQueue::AppendMoveFrom(BinaryQueue &other)
{
- // Copy all buckets
- std::copy(other.m_buckets.begin(),
- other.m_buckets.end(), std::back_inserter(m_buckets));
- m_size += other.m_size;
-
- // Clear other, but do not free memory
- other.m_buckets.clear();
- other.m_size = 0;
+ // Copy all buckets
+ std::copy(other.m_buckets.begin(),
+ other.m_buckets.end(), std::back_inserter(m_buckets));
+ m_size += other.m_size;
+ // Clear other, but do not free memory
+ other.m_buckets.clear();
+ other.m_size = 0;
}
void BinaryQueue::AppendCopyTo(BinaryQueue &other) const
{
- other.AppendCopyFrom(*this);
+ other.AppendCopyFrom(*this);
}
void BinaryQueue::AppendMoveTo(BinaryQueue &other)
{
- other.AppendMoveFrom(*this);
+ other.AppendMoveFrom(*this);
}
void BinaryQueue::Clear()
{
- std::for_each(m_buckets.begin(), m_buckets.end(), &DeleteBucket);
- m_buckets.clear();
- m_size = 0;
+ std::for_each(m_buckets.begin(), m_buckets.end(), &DeleteBucket);
+ m_buckets.clear();
+ m_size = 0;
}
-void BinaryQueue::AppendCopy(const void* buffer, size_t bufferSize)
+void BinaryQueue::AppendCopy(const void *buffer, size_t bufferSize)
{
- // Create data copy with malloc/free
- void *bufferCopy = malloc(bufferSize);
-
- // Check if allocation succeded
- if (bufferCopy == NULL) {
- throw std::bad_alloc();
- }
-
- // Copy user data
- memcpy(bufferCopy, buffer, bufferSize);
-
- try {
- // Try to append new bucket
- AppendUnmanaged(bufferCopy, bufferSize, &BufferDeleterFree, NULL);
- } catch (const std::bad_alloc &) {
- // Free allocated memory
- free(bufferCopy);
- throw;
- }
+ // Create data copy with malloc/free
+ void *bufferCopy = malloc(bufferSize);
+
+ // Check if allocation succeded
+ if (bufferCopy == NULL)
+ throw std::bad_alloc();
+
+ // Copy user data
+ memcpy(bufferCopy, buffer, bufferSize);
+
+ try {
+ // Try to append new bucket
+ AppendUnmanaged(bufferCopy, bufferSize, &BufferDeleterFree, NULL);
+ } catch (const std::bad_alloc &) {
+ // Free allocated memory
+ free(bufferCopy);
+ throw;
+ }
}
-void BinaryQueue::AppendUnmanaged(const void* buffer,
- size_t bufferSize,
- BufferDeleter deleter,
- void* userParam)
+void BinaryQueue::AppendUnmanaged(const void *buffer,
+ size_t bufferSize,
+ BufferDeleter deleter,
+ void *userParam)
{
- // Do not attach empty buckets
- if (bufferSize == 0) {
- deleter(buffer, bufferSize, userParam);
- return;
- }
-
- // Just add new bucket with selected deleter
- Bucket *bucket = new Bucket(buffer, bufferSize, deleter, userParam);
- try {
- m_buckets.push_back(bucket);
- } catch (const std::bad_alloc &) {
- delete bucket;
- throw;
- }
-
- // Increase total queue size
- m_size += bufferSize;
+ // Do not attach empty buckets
+ if (bufferSize == 0) {
+ deleter(buffer, bufferSize, userParam);
+ return;
+ }
+
+ // Just add new bucket with selected deleter
+ Bucket *bucket = new Bucket(buffer, bufferSize, deleter, userParam);
+
+ try {
+ m_buckets.push_back(bucket);
+ } catch (const std::bad_alloc &) {
+ delete bucket;
+ throw;
+ }
+
+ // Increase total queue size
+ m_size += bufferSize;
}
size_t BinaryQueue::Size() const
{
- return m_size;
+ return m_size;
}
bool BinaryQueue::Empty() const
{
- return m_size == 0;
+ return m_size == 0;
}
void BinaryQueue::Consume(size_t size)
{
- // Check parameters
- if (size > m_size) {
- Throw(Exception::OutOfData);
- }
-
- size_t bytesLeft = size;
-
- // Consume data and/or remove buckets
- while (bytesLeft > 0) {
- // Get consume size
- size_t count = std::min(bytesLeft, m_buckets.front()->left);
-
- m_buckets.front()->ptr =
- static_cast<const char *>(m_buckets.front()->ptr) + count;
- m_buckets.front()->left -= count;
- bytesLeft -= count;
- m_size -= count;
-
- if (m_buckets.front()->left == 0) {
- DeleteBucket(m_buckets.front());
- m_buckets.pop_front();
- }
- }
+ // Check parameters
+ if (size > m_size)
+ Throw(Exception::OutOfData);
+
+ size_t bytesLeft = size;
+
+ // Consume data and/or remove buckets
+ while (bytesLeft > 0) {
+ // Get consume size
+ size_t count = std::min(bytesLeft, m_buckets.front()->left);
+ m_buckets.front()->ptr =
+ static_cast<const char *>(m_buckets.front()->ptr) + count;
+ m_buckets.front()->left -= count;
+ bytesLeft -= count;
+ m_size -= count;
+
+ if (m_buckets.front()->left == 0) {
+ DeleteBucket(m_buckets.front());
+ m_buckets.pop_front();
+ }
+ }
}
void BinaryQueue::Flatten(void *buffer, size_t bufferSize) const
{
- // Check parameters
- if (bufferSize == 0) {
- return;
- }
-
- if (bufferSize > m_size) {
- Throw(Exception::OutOfData);
- }
-
- size_t bytesLeft = bufferSize;
- void *ptr = buffer;
- BucketList::const_iterator bucketIterator = m_buckets.begin();
- Assert(m_buckets.end() != bucketIterator);
-
- // Flatten data
- while (bytesLeft > 0) {
- // Get consume size
- size_t count = std::min(bytesLeft, (*bucketIterator)->left);
-
- // Copy data to user pointer
- memcpy(ptr, (*bucketIterator)->ptr, count);
-
- // Update flattened bytes count
- bytesLeft -= count;
- ptr = static_cast<char *>(ptr) + count;
-
- // Take next bucket
- ++bucketIterator;
- }
+ // Check parameters
+ if (bufferSize == 0)
+ return;
+
+ if (bufferSize > m_size)
+ Throw(Exception::OutOfData);
+
+ size_t bytesLeft = bufferSize;
+ void *ptr = buffer;
+ BucketList::const_iterator bucketIterator = m_buckets.begin();
+ Assert(m_buckets.end() != bucketIterator);
+
+ // Flatten data
+ while (bytesLeft > 0) {
+ // Get consume size
+ size_t count = std::min(bytesLeft, (*bucketIterator)->left);
+ // Copy data to user pointer
+ memcpy(ptr, (*bucketIterator)->ptr, count);
+ // Update flattened bytes count
+ bytesLeft -= count;
+ ptr = static_cast<char *>(ptr) + count;
+ // Take next bucket
+ ++bucketIterator;
+ }
}
void BinaryQueue::FlattenConsume(void *buffer, size_t bufferSize)
{
- // FIXME: Optimize
- Flatten(buffer, bufferSize);
- Consume(bufferSize);
+ // FIXME: Optimize
+ Flatten(buffer, bufferSize);
+ Consume(bufferSize);
}
void BinaryQueue::DeleteBucket(BinaryQueue::Bucket *bucket)
{
- delete bucket;
+ delete bucket;
}
-void BinaryQueue::BufferDeleterFree(const void* data,
- size_t dataSize,
- void* userParam)
+void BinaryQueue::BufferDeleterFree(const void *data,
+ size_t dataSize,
+ void *userParam)
{
- (void)dataSize;
- (void)userParam;
-
- // Default free deleter
- free(const_cast<void *>(data));
+ (void)dataSize;
+ (void)userParam;
+ // Default free deleter
+ free(const_cast<void *>(data));
}
-BinaryQueue::Bucket::Bucket(const void* data,
- size_t dataSize,
- BufferDeleter dataDeleter,
- void* userParam) :
- buffer(data),
- ptr(data),
- size(dataSize),
- left(dataSize),
- deleter(dataDeleter),
- param(userParam)
+BinaryQueue::Bucket::Bucket(const void *data,
+ size_t dataSize,
+ BufferDeleter dataDeleter,
+ void *userParam) :
+ buffer(data),
+ ptr(data),
+ size(dataSize),
+ left(dataSize),
+ deleter(dataDeleter),
+ param(userParam)
{
- Assert(data != NULL);
- Assert(deleter != NULL);
+ Assert(data != NULL);
+ Assert(deleter != NULL);
}
BinaryQueue::Bucket::~Bucket()
{
- // Invoke deleter on bucket data
- deleter(buffer, size, param);
+ // Invoke deleter on bucket data
+ deleter(buffer, size, param);
}
BinaryQueue::BucketVisitor::~BucketVisitor()
{}
BinaryQueue::BucketVisitorCall::BucketVisitorCall(BucketVisitor *visitor) :
- m_visitor(visitor)
+ m_visitor(visitor)
{}
BinaryQueue::BucketVisitorCall::~BucketVisitorCall()
void BinaryQueue::BucketVisitorCall::operator()(Bucket *bucket) const
{
- m_visitor->OnVisitBucket(bucket->ptr, bucket->left);
+ m_visitor->OnVisitBucket(bucket->ptr, bucket->left);
}
void BinaryQueue::VisitBuckets(BucketVisitor *visitor) const
{
- Assert(visitor != NULL);
-
- // Visit all buckets
- std::for_each(m_buckets.begin(), m_buckets.end(), BucketVisitorCall(visitor));
+ Assert(visitor != NULL);
+ // Visit all buckets
+ std::for_each(m_buckets.begin(), m_buckets.end(), BucketVisitorCall(visitor));
}
BinaryQueueAutoPtr BinaryQueue::Read(size_t size)
{
- // Simulate input stream
- size_t available = std::min(size, m_size);
-
- std::unique_ptr<void, std::function<void(void*)>>
- bufferCopy(malloc(available), free);
-
- if (!bufferCopy.get()) {
- throw std::bad_alloc();
- }
-
- BinaryQueueAutoPtr result(new BinaryQueue());
-
- Flatten(bufferCopy.get(), available);
- result->AppendUnmanaged(
- bufferCopy.release(), available, &BufferDeleterFree, NULL);
- Consume(available);
-
- return result;
+ // Simulate input stream
+ size_t available = std::min(size, m_size);
+ std::unique_ptr<void, std::function<void(void *)>>
+ bufferCopy(malloc(available), free);
+
+ if (!bufferCopy.get())
+ throw std::bad_alloc();
+
+ BinaryQueueAutoPtr result(new BinaryQueue());
+ Flatten(bufferCopy.get(), available);
+ result->AppendUnmanaged(
+ bufferCopy.release(), available, &BufferDeleterFree, NULL);
+ Consume(available);
+ return result;
}
size_t BinaryQueue::Write(const BinaryQueue &buffer, size_t bufferSize)
{
- // Simulate output stream
- AppendCopyFrom(buffer);
- return bufferSize;
+ // Simulate output stream
+ AppendCopyFrom(buffer);
+ return bufferSize;
}
} // namespace AuthPasswd
namespace AuthPasswd {
namespace Colors {
namespace Text {
-const char* BOLD_GREEN_BEGIN = "\033[1;32m";
-const char* BOLD_GREEN_END = "\033[m";
-const char* RED_BEGIN = "\033[0;31m";
-const char* RED_END = "\033[m";
-const char* PURPLE_BEGIN = "\033[0;35m";
-const char* PURPLE_END = "\033[m";
-const char* GREEN_BEGIN = "\033[0;32m";
-const char* GREEN_END = "\033[m";
-const char* CYAN_BEGIN = "\033[0;36m";
-const char* CYAN_END = "\033[m";
-const char* BOLD_RED_BEGIN = "\033[1;31m";
-const char* BOLD_RED_END = "\033[m";
-const char* BOLD_YELLOW_BEGIN = "\033[1;33m";
-const char* BOLD_YELLOW_END = "\033[m";
-const char* BOLD_GOLD_BEGIN = "\033[0;33m";
-const char* BOLD_GOLD_END = "\033[m";
-const char* BOLD_WHITE_BEGIN = "\033[1;37m";
-const char* BOLD_WHITE_END = "\033[m";
+const char *BOLD_GREEN_BEGIN = "\033[1;32m";
+const char *BOLD_GREEN_END = "\033[m";
+const char *RED_BEGIN = "\033[0;31m";
+const char *RED_END = "\033[m";
+const char *PURPLE_BEGIN = "\033[0;35m";
+const char *PURPLE_END = "\033[m";
+const char *GREEN_BEGIN = "\033[0;32m";
+const char *GREEN_END = "\033[m";
+const char *CYAN_BEGIN = "\033[0;36m";
+const char *CYAN_END = "\033[m";
+const char *BOLD_RED_BEGIN = "\033[1;31m";
+const char *BOLD_RED_END = "\033[m";
+const char *BOLD_YELLOW_BEGIN = "\033[1;33m";
+const char *BOLD_YELLOW_END = "\033[m";
+const char *BOLD_GOLD_BEGIN = "\033[0;33m";
+const char *BOLD_GOLD_END = "\033[m";
+const char *BOLD_WHITE_BEGIN = "\033[1;37m";
+const char *BOLD_WHITE_END = "\033[m";
} //namespace Text
namespace Html {
-const char* BOLD_GREEN_BEGIN = "<font color=\"green\"><b>";
-const char* BOLD_GREEN_END = "</b></font>";
-const char* PURPLE_BEGIN = "<font color=\"purple\"><b>";
-const char* PURPLE_END = "</b></font>";
-const char* RED_BEGIN = "<font color=\"red\"><b>";
-const char* RED_END = "</b></font>";
-const char* GREEN_BEGIN = "<font color=\"green\">";
-const char* GREEN_END = "</font>";
-const char* CYAN_BEGIN = "<font color=\"cyan\">";
-const char* CYAN_END = "</font>";
-const char* BOLD_RED_BEGIN = "<font color=\"red\"><b>";
-const char* BOLD_RED_END = "</b></font>";
-const char* BOLD_YELLOW_BEGIN = "<font color=\"yellow\"><b>";
-const char* BOLD_YELLOW_END = "</b></font>";
-const char* BOLD_GOLD_BEGIN = "<font color=\"gold\"><b>";
-const char* BOLD_GOLD_END = "</b></font>";
-const char* BOLD_WHITE_BEGIN = "<font color=\"white\"><b>";
-const char* BOLD_WHITE_END = "</b></font>";
+const char *BOLD_GREEN_BEGIN = "<font color=\"green\"><b>";
+const char *BOLD_GREEN_END = "</b></font>";
+const char *PURPLE_BEGIN = "<font color=\"purple\"><b>";
+const char *PURPLE_END = "</b></font>";
+const char *RED_BEGIN = "<font color=\"red\"><b>";
+const char *RED_END = "</b></font>";
+const char *GREEN_BEGIN = "<font color=\"green\">";
+const char *GREEN_END = "</font>";
+const char *CYAN_BEGIN = "<font color=\"cyan\">";
+const char *CYAN_END = "</font>";
+const char *BOLD_RED_BEGIN = "<font color=\"red\"><b>";
+const char *BOLD_RED_END = "</b></font>";
+const char *BOLD_YELLOW_BEGIN = "<font color=\"yellow\"><b>";
+const char *BOLD_YELLOW_END = "</b></font>";
+const char *BOLD_GOLD_BEGIN = "<font color=\"gold\"><b>";
+const char *BOLD_GOLD_END = "</b></font>";
+const char *BOLD_WHITE_BEGIN = "<font color=\"white\"><b>";
+const char *BOLD_WHITE_END = "</b></font>";
} //namespace Html
} //namespace Colors
} //namespace AuthPasswd
#include <cstdio>
namespace AuthPasswd {
-Exception* Exception::m_lastException = NULL;
+Exception *Exception::m_lastException = NULL;
unsigned int Exception::m_exceptionCount = 0;
void (*Exception::m_terminateHandler)() = NULL;
COMMON_API
void LogUnhandledException(const std::string &str)
{
- // Logging to console
- printf("%s\n", str.c_str());
-
- // Logging to dlog
- LogPedantic(str);
+ // Logging to console
+ printf("%s\n", str.c_str());
+ // Logging to dlog
+ LogPedantic(str);
}
COMMON_API
void LogUnhandledException(const std::string &str,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- // Logging to console
- std::ostringstream msg;
- msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " <<
- function << " ===\033[m";
- msg << str;
- printf("%s\n", msg.str().c_str());
-
- // Logging to dlog
- AuthPasswd::Log::LogSystemSingleton::Instance().Error(
- str.c_str(), filename, line, function);
+ // Logging to console
+ std::ostringstream msg;
+ msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " <<
+ function << " ===\033[m";
+ msg << str;
+ printf("%s\n", msg.str().c_str());
+ // Logging to dlog
+ AuthPasswd::Log::LogSystemSingleton::Instance().Error(
+ str.c_str(), filename, line, function);
}
} // namespace AuthPasswd
namespace AuthPasswd {
namespace Log {
-class AbstractLogProvider
-{
- public:
- virtual ~AbstractLogProvider() {}
+class AbstractLogProvider {
+public:
+ virtual ~AbstractLogProvider() {}
- virtual void SetTag(const char *tag);
+ virtual void SetTag(const char *tag);
- virtual void Debug(const char *message,
- const char *fileName,
- int line,
- const char *function) = 0;
- virtual void Info(const char *message,
- const char *fileName,
- int line,
- const char *function) = 0;
- virtual void Warning(const char *message,
- const char *fileName,
- int line,
- const char *function) = 0;
- virtual void Error(const char *message,
- const char *fileName,
- int line,
- const char *function) = 0;
- virtual void Pedantic(const char *message,
- const char *fileName,
- int line,
- const char *function) = 0;
- virtual void SecureDebug(const char *message,
- const char *fileName,
- int line,
- const char *function) = 0;
- virtual void SecureInfo(const char *message,
- const char *fileName,
- int line,
- const char *function) = 0;
- virtual void SecureWarning(const char *message,
- const char *fileName,
- int line,
- const char *function) = 0;
- virtual void SecureError(const char *message,
- const char *fileName,
- int line,
- const char *function) = 0;
+ virtual void Debug(const char *message,
+ const char *fileName,
+ int line,
+ const char *function) = 0;
+ virtual void Info(const char *message,
+ const char *fileName,
+ int line,
+ const char *function) = 0;
+ virtual void Warning(const char *message,
+ const char *fileName,
+ int line,
+ const char *function) = 0;
+ virtual void Error(const char *message,
+ const char *fileName,
+ int line,
+ const char *function) = 0;
+ virtual void Pedantic(const char *message,
+ const char *fileName,
+ int line,
+ const char *function) = 0;
+ virtual void SecureDebug(const char *message,
+ const char *fileName,
+ int line,
+ const char *function) = 0;
+ virtual void SecureInfo(const char *message,
+ const char *fileName,
+ int line,
+ const char *function) = 0;
+ virtual void SecureWarning(const char *message,
+ const char *fileName,
+ int line,
+ const char *function) = 0;
+ virtual void SecureError(const char *message,
+ const char *fileName,
+ int line,
+ const char *function) = 0;
- protected:
- static const char *LocateSourceFileName(const char *filename);
+protected:
+ static const char *LocateSourceFileName(const char *filename);
};
}
} // namespace AuthPasswd
namespace AuthPasswd {
namespace Log {
class DLOGLogProvider :
- public AbstractLogProvider
-{
- private:
- std::unique_ptr<char[]> m_tag;
+ public AbstractLogProvider {
+private:
+ std::unique_ptr<char[]> m_tag;
- static std::string FormatMessage(const char *message,
- const char *filename,
- int line,
- const char *function);
+ static std::string FormatMessage(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
- public:
- DLOGLogProvider();
- virtual ~DLOGLogProvider();
+public:
+ DLOGLogProvider();
+ virtual ~DLOGLogProvider();
- virtual void Debug(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void Info(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void Warning(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void Error(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void Pedantic(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void SecureDebug(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void SecureInfo(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void SecureWarning(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void SecureError(const char *message,
- const char *fileName,
- int line,
- const char *function);
+ virtual void Debug(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void Info(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void Warning(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void Error(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void Pedantic(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void SecureDebug(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void SecureInfo(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void SecureWarning(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void SecureError(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
- // Set global Tag according to DLOG
- void SetTag(const char *tag);
+ // Set global Tag according to DLOG
+ void SetTag(const char *tag);
};
} // namespace Log
*/
class COMMON_API LogSystem : private Noncopyable {
private:
- typedef std::list<AbstractLogProvider *> AbstractLogProviderPtrList;
- AbstractLogProviderPtrList m_providers;
+ typedef std::list<AbstractLogProvider *> AbstractLogProviderPtrList;
+ AbstractLogProviderPtrList m_providers;
- bool m_isLoggingEnabled;
+ bool m_isLoggingEnabled;
public:
- bool IsLoggingEnabled() const;
- LogSystem();
- virtual ~LogSystem();
-
- /**
- * Log debug message
- */
- void Debug(const char *message,
- const char *filename,
- int line,
- const char *function);
-
- /**
- * Log info message
- */
- void Info(const char *message,
- const char *filename,
- int line,
- const char *function);
-
- /**
- * Log warning message
- */
- void Warning(const char *message,
- const char *filename,
- int line,
- const char *function);
-
- /**
- * Log error message
- */
- void Error(const char *message,
- const char *filename,
- int line,
- const char *function);
-
- /**
- * Log pedantic message
- */
- void Pedantic(const char *message,
- const char *filename,
- int line,
- const char *function);
-
- /**
- * Log pedantic message with secure macro
- */
- void SecureDebug(const char *message,
- const char *filename,
- int line,
- const char *function);
-
- /**
- * Log info message with secure macro
- */
- void SecureInfo(const char *message,
- const char *filename,
- int line,
- const char *function);
-
- /**
- * Log warning message with secure macro
- */
- void SecureWarning(const char *message,
- const char *filename,
- int line,
- const char *function);
-
- /**
- * Log error message with secure macro
- */
- void SecureError(const char *message,
- const char *filename,
- int line,
- const char *function);
-
- /**
- * Set default's DLOG provider Tag
- */
- void SetTag(const char *tag);
-
- /**
- * Add abstract provider to providers list
- *
- * @notice Ownership is transfered to LogSystem and deleted upon exit
- */
- void AddProvider(AbstractLogProvider *provider);
-
- /**
- * Remove abstract provider from providers list
- */
- void RemoveProvider(AbstractLogProvider *provider);
+ bool IsLoggingEnabled() const;
+ LogSystem();
+ virtual ~LogSystem();
+
+ /**
+ * Log debug message
+ */
+ void Debug(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
+
+ /**
+ * Log info message
+ */
+ void Info(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
+
+ /**
+ * Log warning message
+ */
+ void Warning(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
+
+ /**
+ * Log error message
+ */
+ void Error(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
+
+ /**
+ * Log pedantic message
+ */
+ void Pedantic(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
+
+ /**
+ * Log pedantic message with secure macro
+ */
+ void SecureDebug(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
+
+ /**
+ * Log info message with secure macro
+ */
+ void SecureInfo(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
+
+ /**
+ * Log warning message with secure macro
+ */
+ void SecureWarning(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
+
+ /**
+ * Log error message with secure macro
+ */
+ void SecureError(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
+
+ /**
+ * Set default's DLOG provider Tag
+ */
+ void SetTag(const char *tag);
+
+ /**
+ * Add abstract provider to providers list
+ *
+ * @notice Ownership is transfered to LogSystem and deleted upon exit
+ */
+ void AddProvider(AbstractLogProvider *provider);
+
+ /**
+ * Remove abstract provider from providers list
+ */
+ void RemoveProvider(AbstractLogProvider *provider);
};
/*
*/
class COMMON_API NullStream {
public:
- NullStream() {}
+ NullStream() {}
- template <typename T>
- NullStream& operator<<(const T&)
- {
- return *this;
- }
+ template <typename T>
+ NullStream &operator<<(const T &)
+ {
+ return *this;
+ }
};
/**
//
/* avoid warnings about unused variables */
-#define DPL_MACRO_DUMMY_LOGGING(message, function) \
- do { \
- AuthPasswd::Log::NullStream ns; \
- ns << message; \
- } while (0)
-
-#define DPL_MACRO_FOR_LOGGING(message, function) \
-do \
-{ \
- if (AuthPasswd::Log::LogSystemSingleton::Instance().IsLoggingEnabled()) \
- { \
- std::ostringstream platformLog; \
- platformLog << message; \
- AuthPasswd::Log::LogSystemSingleton::Instance().function( \
- platformLog.str().c_str(), \
- __FILE__, __LINE__, __FUNCTION__); \
- } \
-} while (0)
+#define DPL_MACRO_DUMMY_LOGGING(message, function) \
+ do { \
+ AuthPasswd::Log::NullStream ns; \
+ ns << message; \
+ } while (0)
+
+#define DPL_MACRO_FOR_LOGGING(message, function) \
+ do { \
+ if (AuthPasswd::Log::LogSystemSingleton::Instance().IsLoggingEnabled()) { \
+ std::ostringstream platformLog; \
+ platformLog << message; \
+ AuthPasswd::Log::LogSystemSingleton::Instance().function( \
+ platformLog.str().c_str(), \
+ __FILE__, __LINE__, __FUNCTION__); \
+ } \
+ } while (0)
/* Errors must be always logged. */
#define LogError(message) DPL_MACRO_FOR_LOGGING(message, Error)
#define LogSecureError(message) DPL_MACRO_FOR_LOGGING(message, SecureError)
#ifdef BUILD_TYPE_DEBUG
- #define LogDebug(message) DPL_MACRO_FOR_LOGGING(message, Debug)
- #define LogInfo(message) DPL_MACRO_FOR_LOGGING(message, Info)
- #define LogWarning(message) DPL_MACRO_FOR_LOGGING(message, Warning)
- #define LogPedantic(message) DPL_MACRO_FOR_LOGGING(message, Pedantic)
- #define LogSecureDebug(message) DPL_MACRO_FOR_LOGGING(message, SecureDebug)
- #define LogSecureInfo(message) DPL_MACRO_FOR_LOGGING(message, SecureInfo)
- #define LogSecureWarning(message) DPL_MACRO_FOR_LOGGING(message, SecureWarning)
+#define LogDebug(message) DPL_MACRO_FOR_LOGGING(message, Debug)
+#define LogInfo(message) DPL_MACRO_FOR_LOGGING(message, Info)
+#define LogWarning(message) DPL_MACRO_FOR_LOGGING(message, Warning)
+#define LogPedantic(message) DPL_MACRO_FOR_LOGGING(message, Pedantic)
+#define LogSecureDebug(message) DPL_MACRO_FOR_LOGGING(message, SecureDebug)
+#define LogSecureInfo(message) DPL_MACRO_FOR_LOGGING(message, SecureInfo)
+#define LogSecureWarning(message) DPL_MACRO_FOR_LOGGING(message, SecureWarning)
#else
- #define LogDebug(message) DPL_MACRO_DUMMY_LOGGING(message, Debug)
- #define LogInfo(message) DPL_MACRO_DUMMY_LOGGING(message, Info)
- #define LogWarning(message) DPL_MACRO_DUMMY_LOGGING(message, Warning)
- #define LogPedantic(message) DPL_MACRO_DUMMY_LOGGING(message, Pedantic)
- #define LogSecureDebug(message) DPL_MACRO_DUMMY_LOGGING(message, SecureDebug)
- #define LogSecureInfo(message) DPL_MACRO_DUMMY_LOGGING(message, SecureInfo)
- #define LogSecureWarning(message) DPL_MACRO_DUMMY_LOGGING(message, SecureWarning)
+#define LogDebug(message) DPL_MACRO_DUMMY_LOGGING(message, Debug)
+#define LogInfo(message) DPL_MACRO_DUMMY_LOGGING(message, Info)
+#define LogWarning(message) DPL_MACRO_DUMMY_LOGGING(message, Warning)
+#define LogPedantic(message) DPL_MACRO_DUMMY_LOGGING(message, Pedantic)
+#define LogSecureDebug(message) DPL_MACRO_DUMMY_LOGGING(message, SecureDebug)
+#define LogSecureInfo(message) DPL_MACRO_DUMMY_LOGGING(message, SecureInfo)
+#define LogSecureWarning(message) DPL_MACRO_DUMMY_LOGGING(message, SecureWarning)
#endif // BUILD_TYPE_DEBUG
#endif // AUTHPASSWD_LOG_H
namespace AuthPasswd {
namespace Log {
class OldStyleLogProvider :
- public AbstractLogProvider
-{
- private:
- bool m_showDebug;
- bool m_showInfo;
- bool m_showWarning;
- bool m_showError;
- bool m_showPedantic;
- bool m_printStdErr;
+ public AbstractLogProvider {
+private:
+ bool m_showDebug;
+ bool m_showInfo;
+ bool m_showWarning;
+ bool m_showError;
+ bool m_showPedantic;
+ bool m_printStdErr;
- static std::string FormatMessage(const char *message,
- const char *filename,
- int line,
- const char *function);
+ static std::string FormatMessage(const char *message,
+ const char *filename,
+ int line,
+ const char *function);
- public:
- OldStyleLogProvider(bool showDebug,
- bool showInfo,
- bool showWarning,
- bool showError,
- bool showPedantic);
- OldStyleLogProvider(bool showDebug,
- bool showInfo,
- bool showWarning,
- bool showError,
- bool showPedantic,
- bool printStdErr);
- virtual ~OldStyleLogProvider() {}
+public:
+ OldStyleLogProvider(bool showDebug,
+ bool showInfo,
+ bool showWarning,
+ bool showError,
+ bool showPedantic);
+ OldStyleLogProvider(bool showDebug,
+ bool showInfo,
+ bool showWarning,
+ bool showError,
+ bool showPedantic,
+ bool printStdErr);
+ virtual ~OldStyleLogProvider() {}
- virtual void Debug(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void Info(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void Warning(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void Error(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void Pedantic(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void SecureDebug(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void SecureInfo(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void SecureWarning(const char *message,
- const char *fileName,
- int line,
- const char *function);
- virtual void SecureError(const char *message,
- const char *fileName,
- int line,
- const char *function);
+ virtual void Debug(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void Info(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void Warning(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void Error(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void Pedantic(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void SecureDebug(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void SecureInfo(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void SecureWarning(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
+ virtual void SecureError(const char *message,
+ const char *fileName,
+ int line,
+ const char *function);
};
}
} // namespace AuthPasswd
const char *AbstractLogProvider::LocateSourceFileName(const char *filename)
{
- const char *ptr = strrchr(filename, '/');
- return ptr != NULL ? ptr + 1 : filename;
+ const char *ptr = strrchr(filename, '/');
+ return ptr != NULL ? ptr + 1 : filename;
}
}
}
namespace AuthPasswd {
namespace Log {
std::string DLOGLogProvider::FormatMessage(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- std::ostringstream val;
-
- val << std::string("[") <<
- LocateSourceFileName(filename) << std::string(":") << line <<
- std::string("] ") << function << std::string("(): ") << message;
-
- return val.str();
+ std::ostringstream val;
+ val << std::string("[") <<
+ LocateSourceFileName(filename) << std::string(":") << line <<
+ std::string("] ") << function << std::string("(): ") << message;
+ return val.str();
}
DLOGLogProvider::DLOGLogProvider()
void DLOGLogProvider::SetTag(const char *tag)
{
- size_t size = strlen(tag)+1;
- char *buff = new (std::nothrow) char[size];
- if (buff)
- memcpy(buff, tag, size);
- m_tag.reset(buff);
+ size_t size = strlen(tag) + 1;
+ char *buff = new(std::nothrow) char[size];
+
+ if (buff)
+ memcpy(buff, tag, size);
+
+ m_tag.reset(buff);
}
void DLOGLogProvider::Debug(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- SLOG(LOG_DEBUG, m_tag.get(), "%s",
- FormatMessage(message, filename, line, function).c_str());
+ SLOG(LOG_DEBUG, m_tag.get(), "%s",
+ FormatMessage(message, filename, line, function).c_str());
}
void DLOGLogProvider::Info(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- SLOG(LOG_INFO, m_tag.get(), "%s",
- FormatMessage(message, filename, line, function).c_str());
+ SLOG(LOG_INFO, m_tag.get(), "%s",
+ FormatMessage(message, filename, line, function).c_str());
}
void DLOGLogProvider::Warning(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- SLOG(LOG_WARN, m_tag.get(), "%s",
- FormatMessage(message, filename, line, function).c_str());
+ SLOG(LOG_WARN, m_tag.get(), "%s",
+ FormatMessage(message, filename, line, function).c_str());
}
void DLOGLogProvider::Error(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- SLOG(LOG_ERROR, m_tag.get(), "%s",
- FormatMessage(message, filename, line, function).c_str());
+ SLOG(LOG_ERROR, m_tag.get(), "%s",
+ FormatMessage(message, filename, line, function).c_str());
}
void DLOGLogProvider::Pedantic(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- SLOG(LOG_DEBUG, "AuthPasswd", "%s", FormatMessage(message,
- filename,
- line,
- function).c_str());
+ SLOG(LOG_DEBUG, "AuthPasswd", "%s", FormatMessage(message,
+ filename,
+ line,
+ function).c_str());
}
void DLOGLogProvider::SecureDebug(const char *message UNUSED,
- const char *filename UNUSED,
- int line UNUSED,
- const char *function UNUSED)
+ const char *filename UNUSED,
+ int line UNUSED,
+ const char *function UNUSED)
{
- SECURE_SLOG(LOG_DEBUG, m_tag.get(), "%s",
- FormatMessage(message, filename, line, function).c_str());
+ SECURE_SLOG(LOG_DEBUG, m_tag.get(), "%s",
+ FormatMessage(message, filename, line, function).c_str());
}
void DLOGLogProvider::SecureInfo(const char *message UNUSED,
- const char *filename UNUSED,
- int line UNUSED,
- const char *function UNUSED)
+ const char *filename UNUSED,
+ int line UNUSED,
+ const char *function UNUSED)
{
- SECURE_SLOG(LOG_INFO, m_tag.get(), "%s",
- FormatMessage(message, filename, line, function).c_str());
+ SECURE_SLOG(LOG_INFO, m_tag.get(), "%s",
+ FormatMessage(message, filename, line, function).c_str());
}
void DLOGLogProvider::SecureWarning(const char *message UNUSED,
- const char *filename UNUSED,
- int line UNUSED,
- const char *function UNUSED)
+ const char *filename UNUSED,
+ int line UNUSED,
+ const char *function UNUSED)
{
- SECURE_SLOG(LOG_WARN, m_tag.get(), "%s",
- FormatMessage(message, filename, line, function).c_str());
+ SECURE_SLOG(LOG_WARN, m_tag.get(), "%s",
+ FormatMessage(message, filename, line, function).c_str());
}
void DLOGLogProvider::SecureError(const char *message UNUSED,
- const char *filename UNUSED,
- int line UNUSED,
- const char *function UNUSED)
+ const char *filename UNUSED,
+ int line UNUSED,
+ const char *function UNUSED)
{
- SECURE_SLOG(LOG_ERROR, m_tag.get(), "%s",
- FormatMessage(message, filename, line, function).c_str());
+ SECURE_SLOG(LOG_ERROR, m_tag.get(), "%s",
+ FormatMessage(message, filename, line, function).c_str());
}
} // nemespace Log
namespace AuthPasswd {
namespace Log {
-namespace // anonymous
-{
+namespace { // anonymous
#ifdef BUILD_TYPE_DEBUG
const char *OLD_STYLE_LOGS_ENV_NAME = "DPL_USE_OLD_STYLE_LOGS";
const char *OLD_STYLE_PEDANTIC_LOGS_ENV_NAME =
- "DPL_USE_OLD_STYLE_PEDANTIC_LOGS";
+ "DPL_USE_OLD_STYLE_PEDANTIC_LOGS";
const char *OLD_STYLE_LOGS_MASK_ENV_NAME = "DPL_USE_OLD_STYLE_LOGS_MASK";
#endif // BUILD_TYPE_DEBUG
const char *AUTH_PASSWD_LOG_OFF = "DPL_LOG_OFF";
bool LogSystem::IsLoggingEnabled() const
{
- return m_isLoggingEnabled;
+ return m_isLoggingEnabled;
}
LogSystem::LogSystem() :
- m_isLoggingEnabled(!getenv(AUTH_PASSWD_LOG_OFF))
+ m_isLoggingEnabled(!getenv(AUTH_PASSWD_LOG_OFF))
{
#ifdef BUILD_TYPE_DEBUG
- bool oldStyleLogs = false;
- bool oldStyleDebugLogs = true;
- bool oldStyleInfoLogs = true;
- bool oldStyleWarningLogs = true;
- bool oldStyleErrorLogs = true;
- bool oldStylePedanticLogs = false;
-
- // Check environment settings about pedantic logs
- const char *value = getenv(OLD_STYLE_LOGS_ENV_NAME);
-
- if (value != NULL && !strcmp(value, "1")) {
- oldStyleLogs = true;
- }
-
- value = getenv(OLD_STYLE_PEDANTIC_LOGS_ENV_NAME);
-
- if (value != NULL && !strcmp(value, "1")) {
- oldStylePedanticLogs = true;
- }
-
- value = getenv(OLD_STYLE_LOGS_MASK_ENV_NAME);
+ bool oldStyleLogs = false;
+ bool oldStyleDebugLogs = true;
+ bool oldStyleInfoLogs = true;
+ bool oldStyleWarningLogs = true;
+ bool oldStyleErrorLogs = true;
+ bool oldStylePedanticLogs = false;
+ // Check environment settings about pedantic logs
+ const char *value = getenv(OLD_STYLE_LOGS_ENV_NAME);
+
+ if (value != NULL && !strcmp(value, "1"))
+ oldStyleLogs = true;
+
+ value = getenv(OLD_STYLE_PEDANTIC_LOGS_ENV_NAME);
+
+ if (value != NULL && !strcmp(value, "1"))
+ oldStylePedanticLogs = true;
+
+ value = getenv(OLD_STYLE_LOGS_MASK_ENV_NAME);
+
+ if (value != NULL) {
+ size_t len = strlen(value);
+
+ if (len >= 1) {
+ if (value[0] == '0')
+ oldStyleDebugLogs = false;
+ else if (value[0] == '1')
+ oldStyleDebugLogs = true;
+ }
+
+ if (len >= 2) {
+ if (value[1] == '0')
+ oldStyleInfoLogs = false;
+ else if (value[1] == '1')
+ oldStyleInfoLogs = true;
+ }
+
+ if (len >= 3) {
+ if (value[2] == '0')
+ oldStyleWarningLogs = false;
+ else if (value[2] == '1')
+ oldStyleWarningLogs = true;
+ }
+
+ if (len >= 4) {
+ if (value[3] == '0')
+ oldStyleErrorLogs = false;
+ else if (value[3] == '1')
+ oldStyleErrorLogs = true;
+ }
+ }
+
+ // Setup default DLOG and old style logging
+ if (oldStyleLogs) {
+ // Old style
+ AddProvider(new OldStyleLogProvider(oldStyleDebugLogs,
+ oldStyleInfoLogs,
+ oldStyleWarningLogs,
+ oldStyleErrorLogs,
+ oldStylePedanticLogs));
+ } else {
+ // DLOG
+ AddProvider(new DLOGLogProvider());
+ }
- if (value != NULL) {
- size_t len = strlen(value);
-
- if (len >= 1) {
- if (value[0] == '0') {
- oldStyleDebugLogs = false;
- } else if (value[0] == '1') {
- oldStyleDebugLogs = true;
- }
- }
-
- if (len >= 2) {
- if (value[1] == '0') {
- oldStyleInfoLogs = false;
- } else if (value[1] == '1') {
- oldStyleInfoLogs = true;
- }
- }
-
- if (len >= 3) {
- if (value[2] == '0') {
- oldStyleWarningLogs = false;
- } else if (value[2] == '1') {
- oldStyleWarningLogs = true;
- }
- }
-
- if (len >= 4) {
- if (value[3] == '0') {
- oldStyleErrorLogs = false;
- } else if (value[3] == '1') {
- oldStyleErrorLogs = true;
- }
- }
- }
-
- // Setup default DLOG and old style logging
- if (oldStyleLogs) {
- // Old style
- AddProvider(new OldStyleLogProvider(oldStyleDebugLogs,
- oldStyleInfoLogs,
- oldStyleWarningLogs,
- oldStyleErrorLogs,
- oldStylePedanticLogs));
- } else {
- // DLOG
- AddProvider(new DLOGLogProvider());
- }
#else // BUILD_TYPE_DEBUG
- AddProvider(new DLOGLogProvider());
+ AddProvider(new DLOGLogProvider());
#endif // BUILD_TYPE_DEBUG
}
LogSystem::~LogSystem()
{
- // Delete all providers
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- delete *iterator;
- }
+ // Delete all providers
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ delete *iterator;
- m_providers.clear();
+ m_providers.clear();
}
-void LogSystem::SetTag(const char* tag)
+void LogSystem::SetTag(const char *tag)
{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->SetTag(tag);
- }
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->SetTag(tag);
}
void LogSystem::AddProvider(AbstractLogProvider *provider)
{
- m_providers.push_back(provider);
+ m_providers.push_back(provider);
}
void LogSystem::RemoveProvider(AbstractLogProvider *provider)
{
- m_providers.remove(provider);
+ m_providers.remove(provider);
}
void LogSystem::Debug(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->Debug(message, filename, line, function);
- }
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->Debug(message, filename, line, function);
}
void LogSystem::Info(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->Info(message, filename, line, function);
- }
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->Info(message, filename, line, function);
}
void LogSystem::Warning(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->Warning(message, filename, line, function);
- }
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->Warning(message, filename, line, function);
}
void LogSystem::Error(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->Error(message, filename, line, function);
- }
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->Error(message, filename, line, function);
}
void LogSystem::Pedantic(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->Pedantic(message, filename, line, function);
- }
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->Pedantic(message, filename, line, function);
}
void LogSystem::SecureInfo(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->SecureInfo(message, filename, line, function);
- }
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->SecureInfo(message, filename, line, function);
}
void LogSystem::SecureDebug(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->SecureDebug(message, filename, line, function);
- }
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->SecureDebug(message, filename, line, function);
}
void LogSystem::SecureError(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->SecureError(message, filename, line, function);
- }
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->SecureError(message, filename, line, function);
}
void LogSystem::SecureWarning(const char *message,
- const char *filename,
- int line,
- const char *function)
-{
- for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
- iterator != m_providers.end();
- ++iterator)
- {
- (*iterator)->SecureWarning(message, filename, line, function);
- }
+ const char *filename,
+ int line,
+ const char *function)
+{
+ for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+ iterator != m_providers.end();
+ ++iterator)
+ (*iterator)->SecureWarning(message, filename, line, function);
}
}
namespace AuthPasswd {
namespace Log {
-namespace // anonymous
-{
+namespace { // anonymous
using namespace AuthPasswd::Colors::Text;
const char *DEBUG_BEGIN = GREEN_BEGIN;
const char *DEBUG_END = GREEN_END;
std::string GetFormattedTime()
{
- timeval tv;
- tm localNowTime;
-
- gettimeofday(&tv, NULL);
- localtime_r(&tv.tv_sec, &localNowTime);
-
- char format[64];
- snprintf(format,
- sizeof(format),
- "%02i:%02i:%02i.%03i",
- localNowTime.tm_hour,
- localNowTime.tm_min,
- localNowTime.tm_sec,
- static_cast<int>(tv.tv_usec / 1000));
- return format;
+ timeval tv;
+ tm localNowTime;
+ gettimeofday(&tv, NULL);
+ localtime_r(&tv.tv_sec, &localNowTime);
+ char format[64];
+ snprintf(format,
+ sizeof(format),
+ "%02i:%02i:%02i.%03i",
+ localNowTime.tm_hour,
+ localNowTime.tm_min,
+ localNowTime.tm_sec,
+ static_cast<int>(tv.tv_usec / 1000));
+ return format;
}
} // namespace anonymous
std::string OldStyleLogProvider::FormatMessage(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- std::ostringstream val;
-
- val << std::string("[") << GetFormattedTime() << std::string("] [") <<
- static_cast<unsigned long>(pthread_self()) << "/" <<
- static_cast<int>(getpid()) << std::string("] [") <<
- LocateSourceFileName(filename) << std::string(":") << line <<
- std::string("] ") << function << std::string("(): ") << message;
-
- return val.str();
+ std::ostringstream val;
+ val << std::string("[") << GetFormattedTime() << std::string("] [") <<
+ static_cast<unsigned long>(pthread_self()) << "/" <<
+ static_cast<int>(getpid()) << std::string("] [") <<
+ LocateSourceFileName(filename) << std::string(":") << line <<
+ std::string("] ") << function << std::string("(): ") << message;
+ return val.str();
}
OldStyleLogProvider::OldStyleLogProvider(bool showDebug,
- bool showInfo,
- bool showWarning,
- bool showError,
- bool showPedantic) :
- m_showDebug(showDebug),
- m_showInfo(showInfo),
- m_showWarning(showWarning),
- m_showError(showError),
- m_showPedantic(showPedantic),
- m_printStdErr(false)
+ bool showInfo,
+ bool showWarning,
+ bool showError,
+ bool showPedantic) :
+ m_showDebug(showDebug),
+ m_showInfo(showInfo),
+ m_showWarning(showWarning),
+ m_showError(showError),
+ m_showPedantic(showPedantic),
+ m_printStdErr(false)
{}
OldStyleLogProvider::OldStyleLogProvider(bool showDebug,
- bool showInfo,
- bool showWarning,
- bool showError,
- bool showPedantic,
- bool printStdErr) :
- m_showDebug(showDebug),
- m_showInfo(showInfo),
- m_showWarning(showWarning),
- m_showError(showError),
- m_showPedantic(showPedantic),
- m_printStdErr(printStdErr)
+ bool showInfo,
+ bool showWarning,
+ bool showError,
+ bool showPedantic,
+ bool printStdErr) :
+ m_showDebug(showDebug),
+ m_showInfo(showInfo),
+ m_showWarning(showWarning),
+ m_showError(showError),
+ m_showPedantic(showPedantic),
+ m_printStdErr(printStdErr)
{}
void OldStyleLogProvider::Debug(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- if (m_showDebug) {
- if (m_printStdErr) {
- fprintf(stderr, "%s%s%s\n", DEBUG_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), DEBUG_END);
- } else {
- fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), DEBUG_END);
- }
- }
+ if (m_showDebug) {
+ if (m_printStdErr) {
+ fprintf(stderr, "%s%s%s\n", DEBUG_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), DEBUG_END);
+ } else {
+ fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), DEBUG_END);
+ }
+ }
}
void OldStyleLogProvider::Info(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- if (m_showInfo) {
- if (m_printStdErr) {
- fprintf(stderr, "%s%s%s\n", INFO_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), INFO_END);
- } else {
- fprintf(stdout, "%s%s%s\n", INFO_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), INFO_END);
- }
- }
+ if (m_showInfo) {
+ if (m_printStdErr) {
+ fprintf(stderr, "%s%s%s\n", INFO_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), INFO_END);
+ } else {
+ fprintf(stdout, "%s%s%s\n", INFO_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), INFO_END);
+ }
+ }
}
void OldStyleLogProvider::Warning(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- if (m_showWarning) {
- if (m_printStdErr) {
- fprintf(stderr, "%s%s%s\n", WARNING_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), WARNING_END);
- } else {
- fprintf(stdout, "%s%s%s\n", WARNING_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), WARNING_END);
- }
- }
+ if (m_showWarning) {
+ if (m_printStdErr) {
+ fprintf(stderr, "%s%s%s\n", WARNING_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), WARNING_END);
+ } else {
+ fprintf(stdout, "%s%s%s\n", WARNING_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), WARNING_END);
+ }
+ }
}
void OldStyleLogProvider::Error(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- if (m_showError) {
- if (m_printStdErr) {
- fprintf(stderr, "%s%s%s\n", ERROR_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), ERROR_END);
- } else {
- fprintf(stdout, "%s%s%s\n", ERROR_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), ERROR_END);
- }
- }
+ if (m_showError) {
+ if (m_printStdErr) {
+ fprintf(stderr, "%s%s%s\n", ERROR_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), ERROR_END);
+ } else {
+ fprintf(stdout, "%s%s%s\n", ERROR_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), ERROR_END);
+ }
+ }
}
void OldStyleLogProvider::Pedantic(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
- if (m_showPedantic) {
- if (m_printStdErr) {
- fprintf(stderr, "%s%s%s\n", PEDANTIC_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), PEDANTIC_END);
- } else {
- fprintf(stdout, "%s%s%s\n", PEDANTIC_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), PEDANTIC_END);
- }
- }
+ if (m_showPedantic) {
+ if (m_printStdErr) {
+ fprintf(stderr, "%s%s%s\n", PEDANTIC_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), PEDANTIC_END);
+ } else {
+ fprintf(stdout, "%s%s%s\n", PEDANTIC_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), PEDANTIC_END);
+ }
+ }
}
void OldStyleLogProvider::SecureDebug(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
#ifdef _SECURE_LOG
- if (m_showDebug) {
- if (m_printStdErr) {
- fprintf(stderr, "%s%s%s\n", DEBUG_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), DEBUG_END);
- } else {
- fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), DEBUG_END);
- }
- }
+
+ if (m_showDebug) {
+ if (m_printStdErr) {
+ fprintf(stderr, "%s%s%s\n", DEBUG_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), DEBUG_END);
+ } else {
+ fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), DEBUG_END);
+ }
+ }
+
#else
- (void)message;
- (void)filename;
- (void)line;
- (void)function;
+ (void)message;
+ (void)filename;
+ (void)line;
+ (void)function;
#endif
}
void OldStyleLogProvider::SecureInfo(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
#ifdef _SECURE_LOG
- if (m_showInfo) {
- if (m_printStdErr) {
- fprintf(stderr, "%s%s%s\n", INFO_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), INFO_END);
- } else {
- fprintf(stdout, "%s%s%s\n", INFO_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), INFO_END);
- }
- }
+
+ if (m_showInfo) {
+ if (m_printStdErr) {
+ fprintf(stderr, "%s%s%s\n", INFO_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), INFO_END);
+ } else {
+ fprintf(stdout, "%s%s%s\n", INFO_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), INFO_END);
+ }
+ }
+
#else
- (void)message;
- (void)filename;
- (void)line;
- (void)function;
+ (void)message;
+ (void)filename;
+ (void)line;
+ (void)function;
#endif
}
void OldStyleLogProvider::SecureWarning(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
#ifdef _SECURE_LOG
- if (m_showWarning) {
- if (m_printStdErr) {
- fprintf(stderr, "%s%s%s\n", WARNING_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), WARNING_END);
- } else {
- fprintf(stdout, "%s%s%s\n", WARNING_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), WARNING_END);
- }
- }
+
+ if (m_showWarning) {
+ if (m_printStdErr) {
+ fprintf(stderr, "%s%s%s\n", WARNING_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), WARNING_END);
+ } else {
+ fprintf(stdout, "%s%s%s\n", WARNING_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), WARNING_END);
+ }
+ }
+
#else
- (void)message;
- (void)filename;
- (void)line;
- (void)function;
+ (void)message;
+ (void)filename;
+ (void)line;
+ (void)function;
#endif
}
void OldStyleLogProvider::SecureError(const char *message,
- const char *filename,
- int line,
- const char *function)
+ const char *filename,
+ int line,
+ const char *function)
{
#ifdef _SECURE_LOG
- if (m_showError) {
- if (m_printStdErr) {
- fprintf(stderr, "%s%s%s\n", ERROR_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), ERROR_END);
- } else {
- fprintf(stdout, "%s%s%s\n", ERROR_BEGIN,
- FormatMessage(message, filename, line,
- function).c_str(), ERROR_END);
- }
- }
+
+ if (m_showError) {
+ if (m_printStdErr) {
+ fprintf(stderr, "%s%s%s\n", ERROR_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), ERROR_END);
+ } else {
+ fprintf(stdout, "%s%s%s\n", ERROR_BEGIN,
+ FormatMessage(message, filename, line,
+ function).c_str(), ERROR_END);
+ }
+ }
+
#else
- (void)message;
- (void)filename;
- (void)line;
- (void)function;
+ (void)message;
+ (void)filename;
+ (void)line;
+ (void)function;
#endif
}
#endif
int auth_passwd_reset_passwd(password_type passwd_type,
- uid_t uid,
- const char *new_passwd);
+ uid_t uid,
+ const char *new_passwd);
int auth_passwd_new_policy(policy_h **pp_policy);
typedef struct _policy_h policy_h;
typedef enum {
- POLICY_USER,
- POLICY_MAX_ATTEMPTS,
- POLICY_VALID_PERIOD,
- POLICY_HISTORY_SIZE,
- POLICY_MIN_LENGTH,
- POLICY_MIN_COMPLEX_CHAR_NUMBER,
- POLICY_MAX_CHAR_OCCURRENCES,
- POLICY_MAX_NUMERIC_SEQ_LENGTH,
- POLICY_QUALITY_TYPE,
- POLICY_PATTERN,
- POLICY_FORBIDDEN_PASSWDS,
- POLICY_TYPE_FIRST = POLICY_MAX_ATTEMPTS,
- POLICY_TYPE_LAST = POLICY_FORBIDDEN_PASSWDS
+ POLICY_USER,
+ POLICY_MAX_ATTEMPTS,
+ POLICY_VALID_PERIOD,
+ POLICY_HISTORY_SIZE,
+ POLICY_MIN_LENGTH,
+ POLICY_MIN_COMPLEX_CHAR_NUMBER,
+ POLICY_MAX_CHAR_OCCURRENCES,
+ POLICY_MAX_NUMERIC_SEQ_LENGTH,
+ POLICY_QUALITY_TYPE,
+ POLICY_PATTERN,
+ POLICY_FORBIDDEN_PASSWDS,
+ POLICY_TYPE_FIRST = POLICY_MAX_ATTEMPTS,
+ POLICY_TYPE_LAST = POLICY_FORBIDDEN_PASSWDS
} password_policy_type;
typedef enum {
- AUTH_PWD_NORMAL,
- AUTH_PWD_RECOVERY
+ AUTH_PWD_NORMAL,
+ AUTH_PWD_RECOVERY
} password_type;
typedef enum {
- AUTH_PWD_QUALITY_UNSPECIFIED,
- AUTH_PWD_QUALITY_SOMETHING,
- AUTH_PWD_QUALITY_NUMERIC,
- AUTH_PWD_QUALITY_ALPHABETIC,
- AUTH_PWD_QUALITY_ALPHANUMERIC,
- AUTH_PWD_QUALITY_LAST = AUTH_PWD_QUALITY_ALPHANUMERIC
+ AUTH_PWD_QUALITY_UNSPECIFIED,
+ AUTH_PWD_QUALITY_SOMETHING,
+ AUTH_PWD_QUALITY_NUMERIC,
+ AUTH_PWD_QUALITY_ALPHABETIC,
+ AUTH_PWD_QUALITY_ALPHANUMERIC,
+ AUTH_PWD_QUALITY_LAST = AUTH_PWD_QUALITY_ALPHANUMERIC
} password_quality_type;
#ifdef __cplusplus
#endif
int auth_passwd_check_passwd(password_type passwd_type,
- const char *passwd,
- unsigned int *current_attempts,
- unsigned int *max_attempts,
- unsigned int *valid_secs);
+ const char *passwd,
+ unsigned int *current_attempts,
+ unsigned int *max_attempts,
+ unsigned int *valid_secs);
int auth_passwd_check_passwd_state(password_type passwd_type,
- unsigned int *current_attempts,
- unsigned int *max_attempts,
- unsigned int *valid_secs);
+ unsigned int *current_attempts,
+ unsigned int *max_attempts,
+ unsigned int *valid_secs);
int auth_passwd_check_passwd_reused(password_type passwd_type,
- const char *passwd,
- int *is_reused);
+ const char *passwd,
+ int *is_reused);
int auth_passwd_set_passwd(password_type passwd_type,
- const char *cur_passwd,
- const char *new_passwd);
+ const char *cur_passwd,
+ const char *new_passwd);
int auth_passwd_set_passwd_recovery(const char *cur_recovery_passwd,
- const char *new_normal_passwd);
+ const char *new_normal_passwd);
#ifdef __cplusplus
}
class SendMsgData::Internal {
public:
- Internal(int resultCode, int fileDesc)
- : m_resultCode(resultCode)
- , m_fileDesc(fileDesc)
- {
- memset(&m_hdr, 0, sizeof(msghdr));
- memset(m_cmsgbuf, 0, CMSG_SPACE(sizeof(int)));
-
- m_iov.iov_base = &m_resultCode;
- m_iov.iov_len = sizeof(m_resultCode);
-
- m_hdr.msg_iov = &m_iov;
- m_hdr.msg_iovlen = 1;
-
- if (fileDesc != -1) {
- m_hdr.msg_control = m_cmsgbuf;
- m_hdr.msg_controllen = CMSG_SPACE(sizeof(int));
-
- m_cmsg = CMSG_FIRSTHDR(&m_hdr);
- m_cmsg->cmsg_len = CMSG_LEN(sizeof(int));
- m_cmsg->cmsg_level = SOL_SOCKET;
- m_cmsg->cmsg_type = SCM_RIGHTS;
-
- memmove(CMSG_DATA(m_cmsg), &m_fileDesc, sizeof(int));
- }
- }
-
- msghdr* data() { return &m_hdr; }
+ Internal(int resultCode, int fileDesc) :
+ m_resultCode(resultCode),
+ m_fileDesc(fileDesc) {
+ memset(&m_hdr, 0, sizeof(msghdr));
+ memset(m_cmsgbuf, 0, CMSG_SPACE(sizeof(int)));
+ m_iov.iov_base = &m_resultCode;
+ m_iov.iov_len = sizeof(m_resultCode);
+ m_hdr.msg_iov = &m_iov;
+ m_hdr.msg_iovlen = 1;
+
+ if (fileDesc != -1) {
+ m_hdr.msg_control = m_cmsgbuf;
+ m_hdr.msg_controllen = CMSG_SPACE(sizeof(int));
+ m_cmsg = CMSG_FIRSTHDR(&m_hdr);
+ m_cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+ m_cmsg->cmsg_level = SOL_SOCKET;
+ m_cmsg->cmsg_type = SCM_RIGHTS;
+ memmove(CMSG_DATA(m_cmsg), &m_fileDesc, sizeof(int));
+ }
+ }
+
+ msghdr *data() {
+ return &m_hdr;
+ }
private:
- msghdr m_hdr;
- iovec m_iov;
- cmsghdr *m_cmsg;
- unsigned char m_cmsgbuf[CMSG_SPACE(sizeof(int))];
- int m_resultCode;
- int m_fileDesc;
+ msghdr m_hdr;
+ iovec m_iov;
+ cmsghdr *m_cmsg;
+ unsigned char m_cmsgbuf[CMSG_SPACE(sizeof(int))];
+ int m_resultCode;
+ int m_fileDesc;
};
-SendMsgData::SendMsgData()
- : m_resultCode(0)
- , m_fileDesc(-1)
- , m_flags(0)
- , m_pimpl(NULL)
+SendMsgData::SendMsgData() :
+ m_resultCode(0),
+ m_fileDesc(-1),
+ m_flags(0),
+ m_pimpl(NULL)
{}
-SendMsgData::SendMsgData(int resultCode, int fileDesc, int paramFlags)
- : m_resultCode(resultCode)
- , m_fileDesc(fileDesc)
- , m_flags(paramFlags)
- , m_pimpl(NULL)
+SendMsgData::SendMsgData(int resultCode, int fileDesc, int paramFlags) :
+ m_resultCode(resultCode),
+ m_fileDesc(fileDesc),
+ m_flags(paramFlags),
+ m_pimpl(NULL)
{}
-SendMsgData::SendMsgData(const SendMsgData &second)
- : m_resultCode(second.m_resultCode)
- , m_fileDesc(second.m_fileDesc)
- , m_flags(second.m_flags)
- , m_pimpl(NULL)
+SendMsgData::SendMsgData(const SendMsgData &second) :
+ m_resultCode(second.m_resultCode),
+ m_fileDesc(second.m_fileDesc),
+ m_flags(second.m_flags),
+ m_pimpl(NULL)
{}
-SendMsgData::~SendMsgData() {
- delete m_pimpl;
+SendMsgData::~SendMsgData()
+{
+ delete m_pimpl;
}
-SendMsgData& SendMsgData::operator=(const SendMsgData &second) {
- m_resultCode = second.m_resultCode;
- m_fileDesc = second.m_fileDesc;
- m_flags = second.m_flags;
- delete m_pimpl;
- m_pimpl = NULL;
- return *this;
+SendMsgData &SendMsgData::operator=(const SendMsgData &second)
+{
+ m_resultCode = second.m_resultCode;
+ m_fileDesc = second.m_fileDesc;
+ m_flags = second.m_flags;
+ delete m_pimpl;
+ m_pimpl = NULL;
+ return *this;
}
-msghdr* SendMsgData::getMsghdr() {
- if (!m_pimpl)
- m_pimpl = new Internal(m_resultCode, m_fileDesc);
- return m_pimpl->data();
+msghdr *SendMsgData::getMsghdr()
+{
+ if (!m_pimpl)
+ m_pimpl = new Internal(m_resultCode, m_fileDesc);
+
+ return m_pimpl->data();
}
-int SendMsgData::flags() {
- return m_flags;
+int SendMsgData::flags()
+{
+ return m_flags;
}
} // namespace AuthPasswd
-
namespace AuthPasswd {
struct GenericEvent {
- virtual ~GenericEvent(){}
+ virtual ~GenericEvent() {}
};
} // namespace AuthPasswd
#include <generic-event.h>
extern "C" {
-struct msghdr;
+ struct msghdr;
} // extern "C"
namespace AuthPasswd {
typedef int InterfaceID;
struct ConnectionID {
- int sock; // This is decriptor used for connection
- int counter; // Unique handler per socket
- inline bool operator<(const ConnectionID &second) const {
- return counter < second.counter;
- }
- inline bool operator==(const ConnectionID &second) const {
- return counter == second.counter;
- }
- inline bool operator!=(const ConnectionID &second) const {
- return counter != second.counter;
- }
+ int sock; // This is decriptor used for connection
+ int counter; // Unique handler per socket
+ inline bool operator<(const ConnectionID &second) const {
+ return counter < second.counter;
+ }
+
+ inline bool operator==(const ConnectionID &second) const {
+ return counter == second.counter;
+ }
+
+ inline bool operator!=(const ConnectionID &second) const {
+ return counter != second.counter;
+ }
};
typedef std::vector<unsigned char> RawBuffer;
struct GenericSocketManager;
struct GenericSocketService {
- typedef std::string SmackLabel;
- typedef std::string ServiceHandlerPath;
- struct ServiceDescription {
- ServiceDescription(const char *paramPath,
- const char *paramSmackLabel,
- InterfaceID paramInterfaceID = 0,
- bool paramUseSendMsg = false)
- : type(SOCKET_SERVICE),
- interfaceID(paramInterfaceID),
- useSendMsg(paramUseSendMsg),
- smackLabel(paramSmackLabel),
- serviceHandlerPath(paramPath),
- fileDesc(-1)
- {}
-
- ServiceDescription(int fileDesc,
- InterfaceID paramInterfaceID = 0,
- bool paramUseSendMsg = false)
- : type(FILE_DESC_SERVICE),
- interfaceID(paramInterfaceID),
- useSendMsg(paramUseSendMsg),
- fileDesc(fileDesc)
- {}
-
- enum ServiceType {
- SOCKET_SERVICE = 0,
- FILE_DESC_SERVICE
- };
- ServiceType type;
- InterfaceID interfaceID; // All data from serviceHandlerPath will be marked with this interfaceHandler
- bool useSendMsg;
-
- // if a socket service
- SmackLabel smackLabel; // Smack label for socket
- ServiceHandlerPath serviceHandlerPath; // Path to file
-
- // if a file descriptor
- int fileDesc;
- };
-
- typedef std::vector<ServiceDescription> ServiceDescriptionVector;
-
- struct AcceptEvent : public GenericEvent {
- ConnectionID connectionID;
- InterfaceID interfaceID;
- };
-
- struct WriteEvent : public GenericEvent {
- ConnectionID connectionID;
- size_t size;
- size_t left;
- };
-
- struct ReadEvent : public GenericEvent {
- ConnectionID connectionID;
- RawBuffer rawBuffer;
- InterfaceID interfaceID;
- };
-
- struct CloseEvent : public GenericEvent {
- ConnectionID connectionID;
- };
-
- virtual void SetSocketManager(GenericSocketManager *manager) {
- m_serviceManager = manager;
- }
-
- virtual ServiceDescriptionVector GetServiceDescription() = 0;
-
- virtual void Start() = 0;
- virtual void Stop() = 0;
-
- virtual void Event(const AcceptEvent &event) = 0;
- virtual void Event(const WriteEvent &event) = 0;
- virtual void Event(const ReadEvent &event) = 0;
- virtual void Event(const CloseEvent &event) = 0;
-
- GenericSocketService() : m_serviceManager(NULL) {}
- virtual ~GenericSocketService(){}
+ typedef std::string SmackLabel;
+ typedef std::string ServiceHandlerPath;
+ struct ServiceDescription {
+ ServiceDescription(const char *paramPath,
+ const char *paramSmackLabel,
+ InterfaceID paramInterfaceID = 0,
+ bool paramUseSendMsg = false) :
+ type(SOCKET_SERVICE),
+ interfaceID(paramInterfaceID),
+ useSendMsg(paramUseSendMsg),
+ smackLabel(paramSmackLabel),
+ serviceHandlerPath(paramPath),
+ fileDesc(-1) {}
+
+ ServiceDescription(int fileDesc,
+ InterfaceID paramInterfaceID = 0,
+ bool paramUseSendMsg = false) :
+ type(FILE_DESC_SERVICE),
+ interfaceID(paramInterfaceID),
+ useSendMsg(paramUseSendMsg),
+ fileDesc(fileDesc) {}
+
+ enum ServiceType {
+ SOCKET_SERVICE = 0,
+ FILE_DESC_SERVICE
+ };
+ ServiceType type;
+ InterfaceID
+ interfaceID; // All data from serviceHandlerPath will be marked with this interfaceHandler
+ bool useSendMsg;
+
+ // if a socket service
+ SmackLabel smackLabel; // Smack label for socket
+ ServiceHandlerPath serviceHandlerPath; // Path to file
+
+ // if a file descriptor
+ int fileDesc;
+ };
+
+ typedef std::vector<ServiceDescription> ServiceDescriptionVector;
+
+ struct AcceptEvent : public GenericEvent {
+ ConnectionID connectionID;
+ InterfaceID interfaceID;
+ };
+
+ struct WriteEvent : public GenericEvent {
+ ConnectionID connectionID;
+ size_t size;
+ size_t left;
+ };
+
+ struct ReadEvent : public GenericEvent {
+ ConnectionID connectionID;
+ RawBuffer rawBuffer;
+ InterfaceID interfaceID;
+ };
+
+ struct CloseEvent : public GenericEvent {
+ ConnectionID connectionID;
+ };
+
+ virtual void SetSocketManager(GenericSocketManager *manager) {
+ m_serviceManager = manager;
+ }
+
+ virtual ServiceDescriptionVector GetServiceDescription() = 0;
+
+ virtual void Start() = 0;
+ virtual void Stop() = 0;
+
+ virtual void Event(const AcceptEvent &event) = 0;
+ virtual void Event(const WriteEvent &event) = 0;
+ virtual void Event(const ReadEvent &event) = 0;
+ virtual void Event(const CloseEvent &event) = 0;
+
+ GenericSocketService() : m_serviceManager(NULL) {}
+ virtual ~GenericSocketService() {}
+
protected:
- GenericSocketManager *m_serviceManager;
+ GenericSocketManager *m_serviceManager;
};
class SendMsgData {
public:
- class Internal;
+ class Internal;
+
+ SendMsgData();
+ SendMsgData(int resultCode, int fileDesc, int flags = 0);
+ SendMsgData(const SendMsgData &second);
+ SendMsgData &operator=(const SendMsgData &second);
+ virtual ~SendMsgData();
- SendMsgData();
- SendMsgData(int resultCode, int fileDesc, int flags = 0);
- SendMsgData(const SendMsgData &second);
- SendMsgData& operator=(const SendMsgData &second);
- virtual ~SendMsgData();
+ msghdr *getMsghdr();
+ int flags();
- msghdr* getMsghdr();
- int flags();
private:
- int m_resultCode;
- int m_fileDesc;
- int m_flags;
- Internal *m_pimpl;
+ int m_resultCode;
+ int m_fileDesc;
+ int m_flags;
+ Internal *m_pimpl;
};
struct GenericSocketManager {
- virtual void MainLoop() = 0;
- virtual void RegisterSocketService(GenericSocketService *ptr) = 0;
- virtual void Close(ConnectionID connectionID) = 0;
- virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer) = 0;
- virtual void Write(ConnectionID connectionID, const SendMsgData &sendMsgData) = 0;
- virtual ~GenericSocketManager(){}
+ virtual void MainLoop() = 0;
+ virtual void RegisterSocketService(GenericSocketService *ptr) = 0;
+ virtual void Close(ConnectionID connectionID) = 0;
+ virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer) = 0;
+ virtual void Write(ConnectionID connectionID, const SendMsgData &sendMsgData) = 0;
+ virtual ~GenericSocketManager() {}
};
} // namespace AuthPasswd
#include "generic-event.h"
-#define DEFINE_THREAD_EVENT(eventType) \
- void Event(const eventType &event) { \
- AuthPasswd::ServiceThread<ParentClassName>:: \
- Event(event, \
- this, \
- &ParentClassName::EventInternal##eventType); \
- } \
- void EventInternal##eventType(const eventType &event)
-
-#define DECLARE_THREAD_EVENT(eventType, methodName) \
- void Event(const eventType &event) { \
- AuthPasswd::ServiceThread<ParentClassName>:: \
- Event(event, \
- this, \
- &ParentClassName::methodName); \
- }
+#define DEFINE_THREAD_EVENT(eventType) \
+ void Event(const eventType &event) { \
+ AuthPasswd::ServiceThread<ParentClassName>:: \
+ Event(event, \
+ this, \
+ &ParentClassName::EventInternal##eventType); \
+ } \
+ void EventInternal##eventType(const eventType &event)
+
+#define DECLARE_THREAD_EVENT(eventType, methodName) \
+ void Event(const eventType &event) { \
+ AuthPasswd::ServiceThread<ParentClassName>:: \
+ Event(event, \
+ this, \
+ &ParentClassName::methodName); \
+ }
namespace AuthPasswd {
template <class Service>
class ServiceThread {
public:
- typedef Service ParentClassName;
- enum class State {
- NoThread,
- Work,
- };
-
- ServiceThread()
- : m_state(State::NoThread)
- , m_quit(false)
- {}
-
- void Create() {
- assert(m_state == State::NoThread);
- m_thread = std::thread(ThreadLoopStatic, this);
- m_state = State::Work;
- }
-
- void Join() {
- assert(m_state != State::NoThread);
- {
- std::lock_guard<std::mutex> lock(m_eventQueueMutex);
- m_quit = true;
- m_waitCondition.notify_one();
- }
- m_thread.join();
- m_state = State::NoThread;
- }
-
- virtual ~ServiceThread()
- {
- assert((m_state == State::NoThread) && "You must stop thread before destruction!");
-
- while (!m_eventQueue.empty()){
- auto front = m_eventQueue.front();
- delete front.eventPtr;
- m_eventQueue.pop();
- }
- }
-
- template <class T>
- void Event(const T &event,
- Service *servicePtr,
- void (Service::*serviceFunction)(const T &))
- {
- EventDescription description;
- description.serviceFunctionPtr =
- reinterpret_cast<void (Service::*)(void*)>(serviceFunction);
- description.servicePtr = servicePtr;
- description.eventFunctionPtr = &ServiceThread::EventCall<T>;
- description.eventPtr = new T(event);
- {
- std::lock_guard<std::mutex> lock(m_eventQueueMutex);
- m_eventQueue.push(description);
- }
- m_waitCondition.notify_one();
- }
+ typedef Service ParentClassName;
+ enum class State {
+ NoThread,
+ Work,
+ };
+
+ ServiceThread() : m_state(State::NoThread), m_quit(false) {}
+
+ void Create() {
+ assert(m_state == State::NoThread);
+ m_thread = std::thread(ThreadLoopStatic, this);
+ m_state = State::Work;
+ }
+
+ void Join() {
+ assert(m_state != State::NoThread);
+
+ do {
+ std::lock_guard<std::mutex> lock(m_eventQueueMutex);
+ m_quit = true;
+ m_waitCondition.notify_one();
+ } while (false);
+
+ m_thread.join();
+ m_state = State::NoThread;
+ }
+
+ virtual ~ServiceThread() {
+ assert((m_state == State::NoThread) && "You must stop thread before destruction!");
+
+ while (!m_eventQueue.empty()) {
+ auto front = m_eventQueue.front();
+ delete front.eventPtr;
+ m_eventQueue.pop();
+ }
+ }
+
+ template <class T>
+ void Event(const T &event,
+ Service *servicePtr,
+ void (Service::*serviceFunction)(const T &)) {
+ EventDescription description;
+ description.serviceFunctionPtr =
+ reinterpret_cast<void (Service::*)(void *)>(serviceFunction);
+ description.servicePtr = servicePtr;
+ description.eventFunctionPtr = &ServiceThread::EventCall<T>;
+ description.eventPtr = new T(event);
+
+ do {
+ std::lock_guard<std::mutex> lock(m_eventQueueMutex);
+ m_eventQueue.push(description);
+ } while (false);
+
+ m_waitCondition.notify_one();
+ }
protected:
-
- struct EventDescription {
- void (Service::*serviceFunctionPtr)(void *);
- Service *servicePtr;
- void (ServiceThread::*eventFunctionPtr)(const EventDescription &event);
- GenericEvent* eventPtr;
- };
-
- template <class T>
- void EventCall(const EventDescription &desc) {
- auto fun = reinterpret_cast<void (Service::*)(const T&)>(desc.serviceFunctionPtr);
- const T& eventLocale = *(static_cast<T*>(desc.eventPtr));
- (desc.servicePtr->*fun)(eventLocale);
- }
-
- static void ThreadLoopStatic(ServiceThread *ptr) {
- ptr->ThreadLoop();
- }
-
- void ThreadLoop(){
- for (;;) {
- EventDescription description = {NULL, NULL, NULL, NULL};
- {
- std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
- if (m_quit)
- return;
- if (!m_eventQueue.empty()) {
- description = m_eventQueue.front();
- m_eventQueue.pop();
- } else {
- m_waitCondition.wait(ulock);
- }
- }
-
- if (description.eventPtr != NULL) {
- UNHANDLED_EXCEPTION_HANDLER_BEGIN
- {
- (this->*description.eventFunctionPtr)(description);
- delete description.eventPtr;
- }
- UNHANDLED_EXCEPTION_HANDLER_END
- }
- }
- }
-
- std::thread m_thread;
- std::mutex m_eventQueueMutex;
- std::queue<EventDescription> m_eventQueue;
- std::condition_variable m_waitCondition;
-
- State m_state;
- bool m_quit;
+ struct EventDescription {
+ void (Service::*serviceFunctionPtr)(void *);
+ Service *servicePtr;
+ void (ServiceThread::*eventFunctionPtr)(const EventDescription &event);
+ GenericEvent *eventPtr;
+ };
+
+ template <class T>
+ void EventCall(const EventDescription &desc) {
+ auto fun = reinterpret_cast<void (Service::*)(const T &)>(desc.serviceFunctionPtr);
+ const T &eventLocale = *(static_cast<T *>(desc.eventPtr));
+ (desc.servicePtr->*fun)(eventLocale);
+ }
+
+ static void ThreadLoopStatic(ServiceThread *ptr) {
+ ptr->ThreadLoop();
+ }
+
+ void ThreadLoop() {
+ for (;;) {
+ EventDescription description = {NULL, NULL, NULL, NULL};
+ do {
+ std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
+
+ if (m_quit)
+ return;
+
+ if (!m_eventQueue.empty()) {
+ description = m_eventQueue.front();
+ m_eventQueue.pop();
+ } else {
+ m_waitCondition.wait(ulock);
+ }
+ } while (false);
+
+ if (description.eventPtr != NULL) {
+ UNHANDLED_EXCEPTION_HANDLER_BEGIN {
+ (this->*description.eventFunctionPtr)(description);
+ delete description.eventPtr;
+ }
+ UNHANDLED_EXCEPTION_HANDLER_END
+ }
+ }
+ }
+
+ std::thread m_thread;
+ std::mutex m_eventQueueMutex;
+ std::queue<EventDescription> m_eventQueue;
+ std::condition_variable m_waitCondition;
+
+ State m_state;
+ bool m_quit;
};
} // namespace AuthPasswd
class SocketManager : public GenericSocketManager {
public:
- class Exception {
- public:
- DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
- DECLARE_EXCEPTION_TYPE(Base, InitFailed)
- };
- SocketManager();
- virtual ~SocketManager();
- virtual void MainLoop();
- virtual void MainLoopStop();
-
- virtual void RegisterSocketService(GenericSocketService *service);
- virtual void Close(ConnectionID connectionID);
- virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer);
- virtual void Write(ConnectionID connectionID, const SendMsgData &sendMsgData);
+ class Exception {
+ public:
+ DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
+ DECLARE_EXCEPTION_TYPE(Base, InitFailed)
+ };
+ SocketManager();
+ virtual ~SocketManager();
+ virtual void MainLoop();
+ virtual void MainLoopStop();
+
+ virtual void RegisterSocketService(GenericSocketService *service);
+ virtual void Close(ConnectionID connectionID);
+ virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer);
+ virtual void Write(ConnectionID connectionID, const SendMsgData &sendMsgData);
protected:
- void CreateDomainSocket(
- GenericSocketService *service,
- const GenericSocketService::ServiceDescription &desc);
- int CreateDomainSocketHelp(
- const GenericSocketService::ServiceDescription &desc);
- int GetSocketFromSystemD(
- const GenericSocketService::ServiceDescription &desc);
-
- void ReadyForRead(int sock);
- void ReadyForWrite(int sock);
- void ReadyForWriteBuffer(int sock);
- void ReadyForSendMsg(int sock);
- void ReadyForAccept(int sock);
- void ProcessQueue(void);
- void NotifyMe(void);
- void CloseSocket(int sock);
-
- struct SocketDescription {
- bool isListen;
- bool isOpen;
- bool isTimeout;
- bool useSendMsg;
- InterfaceID interfaceID;
- GenericSocketService *service;
- time_t timeout;
- RawBuffer rawBuffer;
- std::queue<SendMsgData> sendMsgDataQueue;
- int counter;
-
- SocketDescription()
- : isListen(false)
- , isOpen(false)
- , isTimeout(false)
- , useSendMsg(false)
- , interfaceID(-1)
- , service(NULL)
- {}
- };
-
- SocketDescription& CreateDefaultReadSocketDescription(int sock, bool timeout, InterfaceID ifaceID = 0, GenericSocketService *service = NULL);
-
- typedef std::vector<SocketDescription> SocketDescriptionVector;
-
- struct WriteBuffer {
- ConnectionID connectionID;
- RawBuffer rawBuffer;
- };
-
- struct WriteData {
- ConnectionID connectionID;
- SendMsgData sendMsgData;
- };
-
- struct Timeout {
- time_t time;
- int sock;
- bool operator<(const Timeout &second) const {
- return time > second.time; // mininum first!
- }
- };
-
- SocketDescriptionVector m_socketDescriptionVector;
- fd_set m_readSet;
- fd_set m_writeSet;
- int m_maxDesc;
- bool m_working;
- std::mutex m_eventQueueMutex;
- std::queue<WriteBuffer> m_writeBufferQueue;
- std::queue<WriteData> m_writeDataQueue;
- std::queue<ConnectionID> m_closeQueue;
- int m_notifyMe[2];
- int m_counter;
- std::priority_queue<Timeout> m_timeoutQueue;
+ void CreateDomainSocket(
+ GenericSocketService *service,
+ const GenericSocketService::ServiceDescription &desc);
+ int CreateDomainSocketHelp(
+ const GenericSocketService::ServiceDescription &desc);
+ int GetSocketFromSystemD(
+ const GenericSocketService::ServiceDescription &desc);
+
+ void ReadyForRead(int sock);
+ void ReadyForWrite(int sock);
+ void ReadyForWriteBuffer(int sock);
+ void ReadyForSendMsg(int sock);
+ void ReadyForAccept(int sock);
+ void ProcessQueue(void);
+ void NotifyMe(void);
+ void CloseSocket(int sock);
+
+ struct SocketDescription {
+ bool isListen;
+ bool isOpen;
+ bool isTimeout;
+ bool useSendMsg;
+ InterfaceID interfaceID;
+ GenericSocketService *service;
+ time_t timeout;
+ RawBuffer rawBuffer;
+ std::queue<SendMsgData> sendMsgDataQueue;
+ int counter;
+
+ SocketDescription()
+ : isListen(false)
+ , isOpen(false)
+ , isTimeout(false)
+ , useSendMsg(false)
+ , interfaceID(-1)
+ , service(NULL)
+ {}
+ };
+
+ SocketDescription &CreateDefaultReadSocketDescription(int sock, bool timeout,
+ InterfaceID ifaceID = 0, GenericSocketService *service = NULL);
+
+ typedef std::vector<SocketDescription> SocketDescriptionVector;
+
+ struct WriteBuffer {
+ ConnectionID connectionID;
+ RawBuffer rawBuffer;
+ };
+
+ struct WriteData {
+ ConnectionID connectionID;
+ SendMsgData sendMsgData;
+ };
+
+ struct Timeout {
+ time_t time;
+ int sock;
+ bool operator<(const Timeout &second) const
+ {
+ return time > second.time; // mininum first!
+ }
+ };
+
+ SocketDescriptionVector m_socketDescriptionVector;
+ fd_set m_readSet;
+ fd_set m_writeSet;
+ int m_maxDesc;
+ bool m_working;
+ std::mutex m_eventQueueMutex;
+ std::queue<WriteBuffer> m_writeBufferQueue;
+ std::queue<WriteData> m_writeDataQueue;
+ std::queue<ConnectionID> m_closeQueue;
+ int m_notifyMe[2];
+ int m_counter;
+ std::priority_queue<Timeout> m_timeoutQueue;
};
} // namespace AuthPasswd
IMPLEMENT_SAFE_SINGLETON(AuthPasswd::Log::LogSystem);
#define REGISTER_SOCKET_SERVICE(manager, service) \
- registerSocketService<service>(manager, #service)
+ registerSocketService<service>(manager, #service)
template<typename T>
-void registerSocketService(AuthPasswd::SocketManager &manager, const std::string& serviceName)
+void registerSocketService(AuthPasswd::SocketManager &manager, const std::string &serviceName)
{
- T *service = NULL;
- try {
- service = new T();
- service->Start();
- manager.RegisterSocketService(service);
- service = NULL;
- } catch (const AuthPasswd::Exception &exception) {
- LogError("Error in creating service " << serviceName <<
- ", details:\n" << exception.DumpToString());
- } catch (const std::exception& e) {
- LogError("Error in creating service " << serviceName <<
- ", details:\n" << e.what());
- } catch (...) {
- LogError("Error in creating service " << serviceName <<
- ", unknown exception occured");
- }
- if (service)
- delete service;
+ T *service = NULL;
+
+ try {
+ service = new T();
+ service->Start();
+ manager.RegisterSocketService(service);
+ service = NULL;
+ } catch (const AuthPasswd::Exception &exception) {
+ LogError("Error in creating service " << serviceName <<
+ ", details:\n" << exception.DumpToString());
+ } catch (const std::exception &e) {
+ LogError("Error in creating service " << serviceName <<
+ ", details:\n" << e.what());
+ } catch (...) {
+ LogError("Error in creating service " << serviceName <<
+ ", unknown exception occured");
+ }
+
+ if (service)
+ delete service;
}
-int main(void) {
+int main(void)
+{
+ UNHANDLED_EXCEPTION_HANDLER_BEGIN {
+ AuthPasswd::Singleton<AuthPasswd::Log::LogSystem>::Instance().SetTag("AUTH_PASSWD");
- UNHANDLED_EXCEPTION_HANDLER_BEGIN
- {
- AuthPasswd::Singleton<AuthPasswd::Log::LogSystem>::Instance().SetTag("AUTH_PASSWD");
+ sigset_t mask;
+ sigemptyset(&mask);
+ sigaddset(&mask, SIGTERM);
+ sigaddset(&mask, SIGPIPE);
- sigset_t mask;
- sigemptyset(&mask);
- sigaddset(&mask, SIGTERM);
- sigaddset(&mask, SIGPIPE);
- if (-1 == pthread_sigmask(SIG_BLOCK, &mask, NULL)) {
- LogError("Error in pthread_sigmask");
- return 1;
- }
+ if (-1 == pthread_sigmask(SIG_BLOCK, &mask, NULL)) {
+ LogError("Error in pthread_sigmask");
+ return 1;
+ }
- LogInfo("Start!");
- AuthPasswd::SocketManager manager;
+ LogInfo("Start!");
+ AuthPasswd::SocketManager manager;
- REGISTER_SOCKET_SERVICE(manager, AuthPasswd::PasswordService);
+ REGISTER_SOCKET_SERVICE(manager, AuthPasswd::PasswordService);
- manager.MainLoop();
- }
- UNHANDLED_EXCEPTION_HANDLER_END
- return 0;
+ manager.MainLoop();
+ }
+ UNHANDLED_EXCEPTION_HANDLER_END
+ return 0;
}
-
int smack_runtime_check(void)
{
- static int smack_present = -1;
- if (-1 == smack_present) {
- if (NULL == smack_smackfs_path()) {
- LogDebug("no smack found on device");
- smack_present = 0;
- } else {
- LogDebug("found smack on device");
- smack_present = 1;
- }
- }
- return smack_present;
+ static int smack_present = -1;
+
+ if (-1 == smack_present) {
+ if (NULL == smack_smackfs_path()) {
+ LogDebug("no smack found on device");
+ smack_present = 0;
+ } else {
+ LogDebug("found smack on device");
+ smack_present = 1;
+ }
+ }
+
+ return smack_present;
}
int smack_check(void)
{
#ifndef SMACK_ENABLED
- return 0;
+ return 0;
#else
- return smack_runtime_check();
+ return smack_runtime_check();
#endif
}
namespace AuthPasswd {
struct DummyService : public GenericSocketService {
- ServiceDescriptionVector GetServiceDescription() {
- return ServiceDescriptionVector();
- }
+ ServiceDescriptionVector GetServiceDescription() {
+ return ServiceDescriptionVector();
+ }
- void Start() {}
- void Stop() {}
+ void Start() {}
+ void Stop() {}
- void Event(const AcceptEvent &event) { (void)event; }
- void Event(const WriteEvent &event) { (void)event; }
- void Event(const ReadEvent &event) { (void)event; }
- void Event(const CloseEvent &event) { (void)event; }
+ void Event(const AcceptEvent &) {}
+ void Event(const WriteEvent &) {}
+ void Event(const ReadEvent &) {}
+ void Event(const CloseEvent &) {}
};
struct SignalService : public GenericSocketService {
- int GetDescriptor() {
- LogInfo("set up");
- sigset_t mask;
- sigemptyset(&mask);
- sigaddset(&mask, SIGTERM);
- if (-1 == pthread_sigmask(SIG_BLOCK, &mask, NULL))
- return -1;
- return signalfd(-1, &mask, 0);
- }
-
- ServiceDescriptionVector GetServiceDescription() {
- return ServiceDescriptionVector();
- }
-
- void Start() {}
- void Stop() {}
-
- void Event(const AcceptEvent &event) { (void)event; } // not supported
- void Event(const WriteEvent &event) { (void)event; } // not supported
- void Event(const CloseEvent &event) { (void)event; } // not supported
-
- void Event(const ReadEvent &event) {
- LogDebug("Get signal information");
-
- if(sizeof(struct signalfd_siginfo) != event.rawBuffer.size()) {
- LogError("Wrong size of signalfd_siginfo struct. Expected: "
- << sizeof(signalfd_siginfo) << " Get: "
- << event.rawBuffer.size());
- return;
- }
-
- const signalfd_siginfo *siginfo = reinterpret_cast<const signalfd_siginfo*>(
- reinterpret_cast<const void*>(event.rawBuffer.data()));
-
- if (siginfo->ssi_signo == SIGTERM) {
- LogInfo("Got signal: SIGTERM");
- static_cast<SocketManager*>(m_serviceManager)->MainLoopStop();
- return;
- }
-
- LogInfo("This should not happend. Got signal: " << siginfo->ssi_signo);
- }
+ int GetDescriptor() {
+ LogInfo("set up");
+ sigset_t mask;
+ sigemptyset(&mask);
+ sigaddset(&mask, SIGTERM);
+
+ if (-1 == pthread_sigmask(SIG_BLOCK, &mask, NULL))
+ return -1;
+
+ return signalfd(-1, &mask, 0);
+ }
+
+ ServiceDescriptionVector GetServiceDescription() {
+ return ServiceDescriptionVector();
+ }
+
+ void Start() {}
+ void Stop() {}
+
+ void Event(const AcceptEvent &) {}
+ void Event(const WriteEvent &) {}
+ void Event(const CloseEvent &) {}
+
+ void Event(const ReadEvent &event) {
+ LogDebug("Get signal information");
+
+ if (sizeof(struct signalfd_siginfo) != event.rawBuffer.size()) {
+ LogError("Wrong size of signalfd_siginfo struct. Expected: "
+ << sizeof(signalfd_siginfo) << " Get: "
+ << event.rawBuffer.size());
+ return;
+ }
+
+ const signalfd_siginfo *siginfo = reinterpret_cast<const signalfd_siginfo *>(
+ reinterpret_cast<const void *>(event.rawBuffer.data()));
+
+ if (siginfo->ssi_signo == SIGTERM) {
+ LogInfo("Got signal: SIGTERM");
+ static_cast<SocketManager *>(m_serviceManager)->MainLoopStop();
+ return;
+ }
+
+ LogInfo("This should not happend. Got signal: " << siginfo->ssi_signo);
+ }
};
-SocketManager::SocketDescription&
-SocketManager::CreateDefaultReadSocketDescription(int sock, bool timeout, InterfaceID ifaceID /*= 0*/, GenericSocketService *service /* = NULL*/)
+SocketManager::SocketDescription &
+SocketManager::CreateDefaultReadSocketDescription(int sock, bool timeout,
+ InterfaceID ifaceID /*= 0*/, GenericSocketService *service /* = NULL*/)
{
- if ((int)m_socketDescriptionVector.size() <= sock)
- m_socketDescriptionVector.resize(sock+20);
-
- auto &desc = m_socketDescriptionVector[sock];
- desc.isListen = false;
- desc.isOpen = true;
- desc.interfaceID = ifaceID;
- desc.service = service;
- desc.counter = ++m_counter;
-
- if (timeout) {
- desc.timeout = time(NULL) + SOCKET_TIMEOUT;
- if (false == desc.isTimeout) {
- Timeout tm;
- tm.time = desc.timeout;
- tm.sock = sock;
- m_timeoutQueue.push(tm);
- }
- }
-
- desc.isTimeout = timeout;
-
- FD_SET(sock, &m_readSet);
- m_maxDesc = sock > m_maxDesc ? sock : m_maxDesc;
- return desc;
+ if ((int)m_socketDescriptionVector.size() <= sock)
+ m_socketDescriptionVector.resize(sock + 20);
+
+ auto &desc = m_socketDescriptionVector[sock];
+ desc.isListen = false;
+ desc.isOpen = true;
+ desc.interfaceID = ifaceID;
+ desc.service = service;
+ desc.counter = ++m_counter;
+
+ if (timeout) {
+ desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+
+ if (false == desc.isTimeout) {
+ Timeout tm;
+ tm.time = desc.timeout;
+ tm.sock = sock;
+ m_timeoutQueue.push(tm);
+ }
+ }
+
+ desc.isTimeout = timeout;
+ FD_SET(sock, &m_readSet);
+ m_maxDesc = sock > m_maxDesc ? sock : m_maxDesc;
+ return desc;
}
-SocketManager::SocketManager()
- : m_maxDesc(0)
- , m_counter(0)
+SocketManager::SocketManager() :
+ m_maxDesc(0),
+ m_counter(0)
{
- FD_ZERO(&m_readSet);
- FD_ZERO(&m_writeSet);
- if (-1 == pipe(m_notifyMe)) {
- int err = errno;
- ThrowMsg(Exception::InitFailed, "Error in pipe: " << errnoToString(err));
- }
- LogInfo("Pipe: Read desc: " << m_notifyMe[0] << " Write desc: " << m_notifyMe[1]);
-
- auto &desc = CreateDefaultReadSocketDescription(m_notifyMe[0], false);
- desc.service = new DummyService;
-
- // std::thread bases on pthread so this should work fine
- sigset_t set;
- sigemptyset(&set);
- sigaddset(&set, SIGPIPE);
- pthread_sigmask(SIG_BLOCK, &set, NULL);
-
- // add support for TERM signal (passed from systemd)
- auto *signalService = new SignalService;
- signalService->SetSocketManager(this);
- int filefd = signalService->GetDescriptor();
- if (-1 == filefd) {
- LogError("Error in SignalService.GetDescriptor()");
- delete signalService;
- } else {
- auto &desc2 = CreateDefaultReadSocketDescription(filefd, false);
- desc2.service = signalService;
- LogInfo("SignalService mounted on " << filefd << " descriptor");
- }
+ FD_ZERO(&m_readSet);
+ FD_ZERO(&m_writeSet);
+
+ if (-1 == pipe(m_notifyMe)) {
+ int err = errno;
+ ThrowMsg(Exception::InitFailed, "Error in pipe: " << errnoToString(err));
+ }
+
+ LogInfo("Pipe: Read desc: " << m_notifyMe[0] << " Write desc: " << m_notifyMe[1]);
+ auto &desc = CreateDefaultReadSocketDescription(m_notifyMe[0], false);
+ desc.service = new DummyService;
+ // std::thread bases on pthread so this should work fine
+ sigset_t set;
+ sigemptyset(&set);
+ sigaddset(&set, SIGPIPE);
+ pthread_sigmask(SIG_BLOCK, &set, NULL);
+ // add support for TERM signal (passed from systemd)
+ auto *signalService = new SignalService;
+ signalService->SetSocketManager(this);
+ int filefd = signalService->GetDescriptor();
+
+ if (-1 == filefd) {
+ LogError("Error in SignalService.GetDescriptor()");
+ delete signalService;
+ } else {
+ auto &desc2 = CreateDefaultReadSocketDescription(filefd, false);
+ desc2.service = signalService;
+ LogInfo("SignalService mounted on " << filefd << " descriptor");
+ }
}
-SocketManager::~SocketManager() {
- std::set<GenericSocketService*> serviceMap;
-
- // Find all services. Set is used to remove duplicates.
- // In this implementation, services are not able to react in any way.
- for (size_t i=0; i < m_socketDescriptionVector.size(); ++i)
- if (m_socketDescriptionVector[i].isOpen)
- serviceMap.insert(m_socketDescriptionVector[i].service);
-
- // Time to destroy all services.
- for(auto service : serviceMap) {
- LogDebug("delete " << (void*)(service));
- service->Stop();
- delete service;
- }
-
- for (size_t i = 0; i < m_socketDescriptionVector.size(); ++i)
- if (m_socketDescriptionVector[i].isOpen)
- close(i);
-
- // All socket except one were closed. Now pipe input must be closed.
- close(m_notifyMe[1]);
+SocketManager::~SocketManager()
+{
+ std::set<GenericSocketService *> serviceMap;
+
+ // Find all services. Set is used to remove duplicates.
+ // In this implementation, services are not able to react in any way.
+ for (size_t i = 0; i < m_socketDescriptionVector.size(); ++i)
+ if (m_socketDescriptionVector[i].isOpen)
+ serviceMap.insert(m_socketDescriptionVector[i].service);
+
+ // Time to destroy all services.
+ for (auto service : serviceMap) {
+ LogDebug("delete " << (void *)(service));
+ service->Stop();
+ delete service;
+ }
+
+ for (size_t i = 0; i < m_socketDescriptionVector.size(); ++i)
+ if (m_socketDescriptionVector[i].isOpen)
+ close(i);
+
+ // All socket except one were closed. Now pipe input must be closed.
+ close(m_notifyMe[1]);
}
-void SocketManager::ReadyForAccept(int sock) {
- struct sockaddr_un clientAddr;
- unsigned int clientLen = sizeof(clientAddr);
- int client = accept4(sock, (struct sockaddr*) &clientAddr, &clientLen, SOCK_NONBLOCK);
-// LogInfo("Accept on sock: " << sock << " Socket opended: " << client);
- if (-1 == client) {
- int err = errno;
- LogDebug("Error in accept: " << errnoToString(err));
- return;
- }
-
- auto &desc = CreateDefaultReadSocketDescription(client, false);
- desc.interfaceID = m_socketDescriptionVector[sock].interfaceID;
- desc.service = m_socketDescriptionVector[sock].service;
- desc.useSendMsg = m_socketDescriptionVector[sock].useSendMsg;
-
- GenericSocketService::AcceptEvent event;
- event.connectionID.sock = client;
- event.connectionID.counter = desc.counter;
- event.interfaceID = desc.interfaceID;
- desc.service->Event(event);
+void SocketManager::ReadyForAccept(int sock)
+{
+ struct sockaddr_un clientAddr;
+ unsigned int clientLen = sizeof(clientAddr);
+ int client = accept4(sock, (struct sockaddr *) &clientAddr, &clientLen, SOCK_NONBLOCK);
+
+ // LogInfo("Accept on sock: " << sock << " Socket opended: " << client);
+ if (-1 == client) {
+ int err = errno;
+ LogDebug("Error in accept: " << errnoToString(err));
+ return;
+ }
+
+ auto &desc = CreateDefaultReadSocketDescription(client, false);
+ desc.interfaceID = m_socketDescriptionVector[sock].interfaceID;
+ desc.service = m_socketDescriptionVector[sock].service;
+ desc.useSendMsg = m_socketDescriptionVector[sock].useSendMsg;
+ GenericSocketService::AcceptEvent event;
+ event.connectionID.sock = client;
+ event.connectionID.counter = desc.counter;
+ event.interfaceID = desc.interfaceID;
+ desc.service->Event(event);
}
-void SocketManager::ReadyForRead(int sock) {
- if (m_socketDescriptionVector[sock].isListen) {
- ReadyForAccept(sock);
- return;
- }
-
- auto &desc = m_socketDescriptionVector[sock];
- GenericSocketService::ReadEvent event;
- event.connectionID.sock = sock;
- event.connectionID.counter = m_socketDescriptionVector[sock].counter;
- event.interfaceID = desc.interfaceID;
- event.rawBuffer.resize(4096);
-
- desc.timeout = time(NULL) + SOCKET_TIMEOUT;
-
- ssize_t size = read(sock, &event.rawBuffer[0], 4096);
-
- if (size == 0) {
- CloseSocket(sock);
- } else if (size >= 0) {
- event.rawBuffer.resize(size);
- desc.service->Event(event);
- } else if (size == -1) {
- int err = errno;
- switch(err) {
- case EAGAIN:
- case EINTR:
- break;
- default:
- LogDebug("Reading sock error: " << errnoToString(err));
- CloseSocket(sock);
- }
- }
+void SocketManager::ReadyForRead(int sock)
+{
+ if (m_socketDescriptionVector[sock].isListen) {
+ ReadyForAccept(sock);
+ return;
+ }
+
+ auto &desc = m_socketDescriptionVector[sock];
+ GenericSocketService::ReadEvent event;
+ event.connectionID.sock = sock;
+ event.connectionID.counter = m_socketDescriptionVector[sock].counter;
+ event.interfaceID = desc.interfaceID;
+ event.rawBuffer.resize(4096);
+ desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+ ssize_t size = read(sock, &event.rawBuffer[0], 4096);
+
+ if (size == 0) {
+ CloseSocket(sock);
+ } else if (size >= 0) {
+ event.rawBuffer.resize(size);
+ desc.service->Event(event);
+ } else if (size == -1) {
+ int err = errno;
+
+ switch (err) {
+ case EAGAIN:
+ case EINTR:
+ break;
+
+ default:
+ LogDebug("Reading sock error: " << errnoToString(err));
+ CloseSocket(sock);
+ }
+ }
}
-void SocketManager::ReadyForSendMsg(int sock) {
- auto &desc = m_socketDescriptionVector[sock];
-
- if (desc.sendMsgDataQueue.empty()) {
- FD_CLR(sock, &m_writeSet);
- return;
- }
-
- auto data = desc.sendMsgDataQueue.front();
- ssize_t result = sendmsg(sock, data.getMsghdr(), data.flags());
-
- if (result == -1) {
- int err = errno;
- switch(err) {
- case EAGAIN:
- case EINTR:
- break;
- case EPIPE:
- default:
- LogDebug("Error during send: " << errnoToString(err));
- CloseSocket(sock);
- break;
- }
- return;
- } else {
- desc.sendMsgDataQueue.pop();
- }
-
- if (desc.sendMsgDataQueue.empty()) {
- FD_CLR(sock, &m_writeSet);
- }
-
- desc.timeout = time(NULL) + SOCKET_TIMEOUT;
-
- GenericSocketService::WriteEvent event;
- event.connectionID.sock = sock;
- event.connectionID.counter = desc.counter;
- event.size = result;
- event.left = desc.sendMsgDataQueue.size();
-
- desc.service->Event(event);
+void SocketManager::ReadyForSendMsg(int sock)
+{
+ auto &desc = m_socketDescriptionVector[sock];
+
+ if (desc.sendMsgDataQueue.empty()) {
+ FD_CLR(sock, &m_writeSet);
+ return;
+ }
+
+ auto data = desc.sendMsgDataQueue.front();
+ ssize_t result = sendmsg(sock, data.getMsghdr(), data.flags());
+
+ if (result == -1) {
+ int err = errno;
+
+ switch (err) {
+ case EAGAIN:
+ case EINTR:
+ break;
+
+ case EPIPE:
+ default:
+ LogDebug("Error during send: " << errnoToString(err));
+ CloseSocket(sock);
+ break;
+ }
+
+ return;
+ } else {
+ desc.sendMsgDataQueue.pop();
+ }
+
+ if (desc.sendMsgDataQueue.empty())
+ FD_CLR(sock, &m_writeSet);
+
+ desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+ GenericSocketService::WriteEvent event;
+ event.connectionID.sock = sock;
+ event.connectionID.counter = desc.counter;
+ event.size = result;
+ event.left = desc.sendMsgDataQueue.size();
+ desc.service->Event(event);
}
-void SocketManager::ReadyForWriteBuffer(int sock) {
- auto &desc = m_socketDescriptionVector[sock];
- size_t size = desc.rawBuffer.size();
- ssize_t result = write(sock, &desc.rawBuffer[0], size);
- if (result == -1) {
- int err = errno;
- switch(err) {
- case EAGAIN:
- case EINTR:
- // select will trigger write once again, nothing to do
- break;
- case EPIPE:
- default:
- LogDebug("Error during write: " << errnoToString(err));
- CloseSocket(sock);
- break;
- }
- return; // We do not want to propagate error to next layer
- }
-
- desc.rawBuffer.erase(desc.rawBuffer.begin(), desc.rawBuffer.begin()+result);
-
- desc.timeout = time(NULL) + SOCKET_TIMEOUT;
-
- if (desc.rawBuffer.empty())
- FD_CLR(sock, &m_writeSet);
-
- GenericSocketService::WriteEvent event;
- event.connectionID.sock = sock;
- event.connectionID.counter = desc.counter;
- event.size = result;
- event.left = desc.rawBuffer.size();
-
- desc.service->Event(event);
+void SocketManager::ReadyForWriteBuffer(int sock)
+{
+ auto &desc = m_socketDescriptionVector[sock];
+ size_t size = desc.rawBuffer.size();
+ ssize_t result = write(sock, &desc.rawBuffer[0], size);
+
+ if (result == -1) {
+ int err = errno;
+
+ switch (err) {
+ case EAGAIN:
+ case EINTR:
+ // select will trigger write once again, nothing to do
+ break;
+
+ case EPIPE:
+ default:
+ LogDebug("Error during write: " << errnoToString(err));
+ CloseSocket(sock);
+ break;
+ }
+
+ return; // We do not want to propagate error to next layer
+ }
+
+ desc.rawBuffer.erase(desc.rawBuffer.begin(), desc.rawBuffer.begin() + result);
+ desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+
+ if (desc.rawBuffer.empty())
+ FD_CLR(sock, &m_writeSet);
+
+ GenericSocketService::WriteEvent event;
+ event.connectionID.sock = sock;
+ event.connectionID.counter = desc.counter;
+ event.size = result;
+ event.left = desc.rawBuffer.size();
+ desc.service->Event(event);
}
-void SocketManager::ReadyForWrite(int sock) {
- m_socketDescriptionVector[sock].useSendMsg ?
- ReadyForSendMsg(sock) : ReadyForWriteBuffer(sock);
+void SocketManager::ReadyForWrite(int sock)
+{
+ m_socketDescriptionVector[sock].useSendMsg ?
+ ReadyForSendMsg(sock) : ReadyForWriteBuffer(sock);
}
-void SocketManager::MainLoop() {
- // remove evironment values passed by systemd
- // uncomment it after removing old authentication password code
- // sd_listen_fds(1);
-
- // Daemon is ready to work.
- sd_notify(0, "READY=1");
-
- m_working = true;
- while(m_working) {
- fd_set readSet = m_readSet;
- fd_set writeSet = m_writeSet;
-
- timeval localTempTimeout;
- timeval *ptrTimeout = &localTempTimeout;
-
- // I need to extract timeout from priority_queue.
- // Timeout in priority_queue may be deprecated.
- // I need to find some actual one.
- while(!m_timeoutQueue.empty()) {
- auto &top = m_timeoutQueue.top();
- auto &desc = m_socketDescriptionVector[top.sock];
-
- if (top.time == desc.timeout) {
- // This timeout matches timeout from socket.
- // It can be used.
- break;
- } else {
- // This socket was used after timeout in priority queue was set up.
- // We need to update timeout and find some useable one.
- Timeout tm = { desc.timeout , top.sock};
- m_timeoutQueue.pop();
- m_timeoutQueue.push(tm);
- }
- }
-
- if (m_timeoutQueue.empty()) {
- LogDebug("No usaable timeout found.");
- ptrTimeout = NULL; // select will wait without timeout
- } else {
- time_t currentTime = time(NULL);
- auto &pqTimeout = m_timeoutQueue.top();
-
- // 0 means that select won't block and socket will be closed ;-)
- ptrTimeout->tv_sec =
- currentTime < pqTimeout.time ? pqTimeout.time - currentTime : 0;
- ptrTimeout->tv_usec = 0;
-// LogDebug("Set up timeout: " << (int)ptrTimeout->tv_sec
-// << " seconds. Socket: " << pqTimeout.sock);
- }
-
- int ret = select(m_maxDesc+1, &readSet, &writeSet, NULL, ptrTimeout);
-
- if (0 == ret) { // timeout
- Assert(!m_timeoutQueue.empty());
-
- Timeout pqTimeout = m_timeoutQueue.top();
- m_timeoutQueue.pop();
-
- auto &desc = m_socketDescriptionVector[pqTimeout.sock];
-
- if (!desc.isTimeout || !desc.isOpen) {
- // Connection was closed. Timeout is useless...
- desc.isTimeout = false;
- continue;
- }
-
- if (pqTimeout.time < desc.timeout) {
- // Is it possible?
- // This socket was used after timeout. We need to update timeout.
- pqTimeout.time = desc.timeout;
- m_timeoutQueue.push(pqTimeout);
- continue;
- }
-
- // timeout from m_timeoutQueue matches with socket.timeout
- // and connection is open. Time to close it!
- // Putting new timeout in queue here is pointless.
- desc.isTimeout = false;
- CloseSocket(pqTimeout.sock);
-
- // All done. Now we should process next select ;-)
- continue;
- }
-
- if (-1 == ret) {
- switch(errno) {
- case EINTR:
- LogDebug("EINTR in select");
- break;
- default:
- int err = errno;
- LogError("Error in select: " << errnoToString(err));
- return;
- }
- continue;
- }
- for(int i = 0; i<m_maxDesc+1 && ret; ++i) {
- if (FD_ISSET(i, &readSet)) {
- ReadyForRead(i);
- --ret;
- }
- if (FD_ISSET(i, &writeSet)) {
- ReadyForWrite(i);
- --ret;
- }
- }
- ProcessQueue();
- }
+void SocketManager::MainLoop()
+{
+ // remove evironment values passed by systemd
+ // uncomment it after removing old authentication password code
+ // sd_listen_fds(1);
+ // Daemon is ready to work.
+ sd_notify(0, "READY=1");
+ m_working = true;
+
+ while (m_working) {
+ fd_set readSet = m_readSet;
+ fd_set writeSet = m_writeSet;
+ timeval localTempTimeout;
+ timeval *ptrTimeout = &localTempTimeout;
+
+ // I need to extract timeout from priority_queue.
+ // Timeout in priority_queue may be deprecated.
+ // I need to find some actual one.
+ while (!m_timeoutQueue.empty()) {
+ auto &top = m_timeoutQueue.top();
+ auto &desc = m_socketDescriptionVector[top.sock];
+
+ if (top.time == desc.timeout) {
+ // This timeout matches timeout from socket.
+ // It can be used.
+ break;
+ } else {
+ // This socket was used after timeout in priority queue was set up.
+ // We need to update timeout and find some useable one.
+ Timeout tm = { desc.timeout , top.sock};
+ m_timeoutQueue.pop();
+ m_timeoutQueue.push(tm);
+ }
+ }
+
+ if (m_timeoutQueue.empty()) {
+ LogDebug("No usaable timeout found.");
+ ptrTimeout = NULL; // select will wait without timeout
+ } else {
+ time_t currentTime = time(NULL);
+ auto &pqTimeout = m_timeoutQueue.top();
+ // 0 means that select won't block and socket will be closed ;-)
+ ptrTimeout->tv_sec =
+ currentTime < pqTimeout.time ? pqTimeout.time - currentTime : 0;
+ ptrTimeout->tv_usec = 0;
+ // LogDebug("Set up timeout: " << (int)ptrTimeout->tv_sec
+ // << " seconds. Socket: " << pqTimeout.sock);
+ }
+
+ int ret = select(m_maxDesc + 1, &readSet, &writeSet, NULL, ptrTimeout);
+
+ if (0 == ret) { // timeout
+ Assert(!m_timeoutQueue.empty());
+ Timeout pqTimeout = m_timeoutQueue.top();
+ m_timeoutQueue.pop();
+ auto &desc = m_socketDescriptionVector[pqTimeout.sock];
+
+ if (!desc.isTimeout || !desc.isOpen) {
+ // Connection was closed. Timeout is useless...
+ desc.isTimeout = false;
+ continue;
+ }
+
+ if (pqTimeout.time < desc.timeout) {
+ // Is it possible?
+ // This socket was used after timeout. We need to update timeout.
+ pqTimeout.time = desc.timeout;
+ m_timeoutQueue.push(pqTimeout);
+ continue;
+ }
+
+ // timeout from m_timeoutQueue matches with socket.timeout
+ // and connection is open. Time to close it!
+ // Putting new timeout in queue here is pointless.
+ desc.isTimeout = false;
+ CloseSocket(pqTimeout.sock);
+ // All done. Now we should process next select ;-)
+ continue;
+ }
+
+ if (-1 == ret) {
+ switch (errno) {
+ case EINTR:
+ LogDebug("EINTR in select");
+ break;
+
+ default:
+ int err = errno;
+ LogError("Error in select: " << errnoToString(err));
+ return;
+ }
+
+ continue;
+ }
+
+ for (int i = 0; i < m_maxDesc + 1 && ret; ++i) {
+ if (FD_ISSET(i, &readSet)) {
+ ReadyForRead(i);
+ --ret;
+ }
+
+ if (FD_ISSET(i, &writeSet)) {
+ ReadyForWrite(i);
+ --ret;
+ }
+ }
+
+ ProcessQueue();
+ }
}
void SocketManager::MainLoopStop()
{
- m_working = false;
- NotifyMe();
+ m_working = false;
+ NotifyMe();
}
int SocketManager::GetSocketFromSystemD(
- const GenericSocketService::ServiceDescription &desc)
+ const GenericSocketService::ServiceDescription &desc)
{
- int fd;
-
- // TODO optimalization - do it once in object constructor
- // and remember all information path->sockfd
- int n = sd_listen_fds(0);
-
- LogInfo("sd_listen_fds returns: " << n);
-
- if (n < 0) {
- LogError("Error in sd_listend_fds");
- ThrowMsg(Exception::InitFailed, "Error in sd_listend_fds");
- }
-
- for(fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; ++fd) {
- if (0 < sd_is_socket_unix(fd, SOCK_STREAM, 1,
- desc.serviceHandlerPath.c_str(), 0))
- {
- LogInfo("Useable socket " << desc.serviceHandlerPath <<
- " was passed by SystemD under descriptor " << fd);
-
- return fd;
- }
- }
- LogInfo("No useable sockets were passed by systemd.");
- return -1;
+ int fd;
+ // TODO optimalization - do it once in object constructor
+ // and remember all information path->sockfd
+ int n = sd_listen_fds(0);
+ LogInfo("sd_listen_fds returns: " << n);
+
+ if (n < 0) {
+ LogError("Error in sd_listend_fds");
+ ThrowMsg(Exception::InitFailed, "Error in sd_listend_fds");
+ }
+
+ for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; ++fd) {
+ if (0 < sd_is_socket_unix(fd, SOCK_STREAM, 1,
+ desc.serviceHandlerPath.c_str(), 0)) {
+ LogInfo("Useable socket " << desc.serviceHandlerPath <<
+ " was passed by SystemD under descriptor " << fd);
+ return fd;
+ }
+ }
+
+ LogInfo("No useable sockets were passed by systemd.");
+ return -1;
}
int SocketManager::CreateDomainSocketHelp(
- const GenericSocketService::ServiceDescription &desc)
+ const GenericSocketService::ServiceDescription &desc)
{
- int sockfd;
-
- GenericSocketService::ServiceHandlerPath::size_type maxlen =
- sizeof(static_cast<sockaddr_un*>(nullptr)->sun_path) /
- sizeof(GenericSocketService::ServiceHandlerPath::value_type);
- if(desc.serviceHandlerPath.size() >= maxlen) {
- LogError("Service handler path too long: " << desc.serviceHandlerPath.size());
- ThrowMsg(Exception::InitFailed,
- "Service handler path too long: " << desc.serviceHandlerPath.size());
- }
-
- if (-1 == (sockfd = socket(AF_UNIX, SOCK_STREAM, 0))) {
- int err = errno;
- LogError("Error in socket: " << errnoToString(err));
- ThrowMsg(Exception::InitFailed, "Error in socket: " << errnoToString(err));
- }
-
- if (smack_check()) {
- LogInfo("Set up smack label: " << desc.smackLabel);
-
- if (0 != smack_fsetlabel(sockfd, desc.smackLabel.c_str(), SMACK_LABEL_IPIN)) {
- LogError("Error in smack_fsetlabel");
- ThrowMsg(Exception::InitFailed, "Error in smack_fsetlabel");
- }
- } else {
- LogInfo("No smack on platform. Socket won't be securied with smack label!");
- }
-
- int flags;
- if (-1 == (flags = fcntl(sockfd, F_GETFL, 0)))
- flags = 0;
-
- if (-1 == fcntl(sockfd, F_SETFL, flags | O_NONBLOCK)) {
- int err = errno;
- close(sockfd);
- LogError("Error in fcntl: " << errnoToString(err));
- ThrowMsg(Exception::InitFailed, "Error in fcntl: " << errnoToString(err));
- }
-
- sockaddr_un serverAddress;
- memset(&serverAddress, 0, sizeof(serverAddress));
- serverAddress.sun_family = AF_UNIX;
- strncpy(serverAddress.sun_path, desc.serviceHandlerPath.c_str(), sizeof(serverAddress.sun_path) - 1);
- unlink(serverAddress.sun_path);
-
- mode_t originalUmask;
- originalUmask = umask(0);
-
- if (-1 == bind(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) {
- int err = errno;
- close(sockfd);
- LogError("Error in bind: " << errnoToString(err));
- ThrowMsg(Exception::InitFailed, "Error in bind: " << errnoToString(err));
- }
-
- umask(originalUmask);
-
- if (-1 == listen(sockfd, 5)) {
- int err = errno;
- close(sockfd);
- LogError("Error in listen: " << errnoToString(err));
- ThrowMsg(Exception::InitFailed, "Error in listen: " << errnoToString(err));
- }
-
- return sockfd;
+ int sockfd;
+ GenericSocketService::ServiceHandlerPath::size_type maxlen =
+ sizeof(static_cast<sockaddr_un *>(nullptr)->sun_path) /
+ sizeof(GenericSocketService::ServiceHandlerPath::value_type);
+
+ if (desc.serviceHandlerPath.size() >= maxlen) {
+ LogError("Service handler path too long: " << desc.serviceHandlerPath.size());
+ ThrowMsg(Exception::InitFailed,
+ "Service handler path too long: " << desc.serviceHandlerPath.size());
+ }
+
+ if (-1 == (sockfd = socket(AF_UNIX, SOCK_STREAM, 0))) {
+ int err = errno;
+ LogError("Error in socket: " << errnoToString(err));
+ ThrowMsg(Exception::InitFailed, "Error in socket: " << errnoToString(err));
+ }
+
+ if (smack_check()) {
+ LogInfo("Set up smack label: " << desc.smackLabel);
+
+ if (0 != smack_fsetlabel(sockfd, desc.smackLabel.c_str(), SMACK_LABEL_IPIN)) {
+ LogError("Error in smack_fsetlabel");
+ ThrowMsg(Exception::InitFailed, "Error in smack_fsetlabel");
+ }
+ } else
+ LogInfo("No smack on platform. Socket won't be securied with smack label!");
+
+ int flags;
+
+ if (-1 == (flags = fcntl(sockfd, F_GETFL, 0)))
+ flags = 0;
+
+ if (-1 == fcntl(sockfd, F_SETFL, flags | O_NONBLOCK)) {
+ int err = errno;
+ close(sockfd);
+ LogError("Error in fcntl: " << errnoToString(err));
+ ThrowMsg(Exception::InitFailed, "Error in fcntl: " << errnoToString(err));
+ }
+
+ sockaddr_un serverAddress;
+ memset(&serverAddress, 0, sizeof(serverAddress));
+ serverAddress.sun_family = AF_UNIX;
+ strncpy(serverAddress.sun_path, desc.serviceHandlerPath.c_str(),
+ sizeof(serverAddress.sun_path) - 1);
+ unlink(serverAddress.sun_path);
+ mode_t originalUmask;
+ originalUmask = umask(0);
+
+ if (-1 == bind(sockfd, (struct sockaddr *)&serverAddress, sizeof(serverAddress))) {
+ int err = errno;
+ close(sockfd);
+ LogError("Error in bind: " << errnoToString(err));
+ ThrowMsg(Exception::InitFailed, "Error in bind: " << errnoToString(err));
+ }
+
+ umask(originalUmask);
+
+ if (-1 == listen(sockfd, 5)) {
+ int err = errno;
+ close(sockfd);
+ LogError("Error in listen: " << errnoToString(err));
+ ThrowMsg(Exception::InitFailed, "Error in listen: " << errnoToString(err));
+ }
+
+ return sockfd;
}
void SocketManager::CreateDomainSocket(
- GenericSocketService *service,
- const GenericSocketService::ServiceDescription &desc)
+ GenericSocketService *service,
+ const GenericSocketService::ServiceDescription &desc)
{
- int sockfd = GetSocketFromSystemD(desc);
- if (-1 == sockfd)
- sockfd = CreateDomainSocketHelp(desc);
+ int sockfd = GetSocketFromSystemD(desc);
+
+ if (-1 == sockfd)
+ sockfd = CreateDomainSocketHelp(desc);
+
+ auto &description = CreateDefaultReadSocketDescription(sockfd, false);
+ description.isListen = true;
+ description.interfaceID = desc.interfaceID;
+ description.useSendMsg = desc.useSendMsg;
+ description.service = service;
+ LogDebug("Listen on socket: " << sockfd <<
+ " Handler: " << desc.serviceHandlerPath.c_str());
+}
- auto &description = CreateDefaultReadSocketDescription(sockfd, false);
+void SocketManager::RegisterSocketService(GenericSocketService *service)
+{
+ service->SetSocketManager(this);
+ auto serviceVector = service->GetServiceDescription();
+ Try {
+ for (auto iter = serviceVector.begin(); iter != serviceVector.end(); ++iter) {
+ switch (iter->type) {
+ case GenericSocketService::ServiceDescription::SOCKET_SERVICE:
+ CreateDomainSocket(service, *iter);
+ break;
+
+ case GenericSocketService::ServiceDescription::FILE_DESC_SERVICE:
+ CreateDefaultReadSocketDescription(iter->fileDesc, false, iter->interfaceID, service);
+ break;
+
+ default:
+ ThrowMsg(Exception::InitFailed, "Wrong service type in service description: " << iter->type);
+ break;
+ }
+ }
+ } Catch(Exception::Base) {
+ for (int i = 0; i < (int)m_socketDescriptionVector.size(); ++i) {
+ auto &desc = m_socketDescriptionVector[i];
+
+ if (desc.service == service && desc.isOpen) {
+ close(i);
+ desc.isOpen = false;
+ }
+ }
+
+ ReThrow(Exception::Base);
+ }
+}
- description.isListen = true;
- description.interfaceID = desc.interfaceID;
- description.useSendMsg = desc.useSendMsg;
- description.service = service;
+void SocketManager::Close(ConnectionID connectionID)
+{
+ do {
+ std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
+ m_closeQueue.push(connectionID);
+ } while (false);
- LogDebug("Listen on socket: " << sockfd <<
- " Handler: " << desc.serviceHandlerPath.c_str());
+ NotifyMe();
}
-void SocketManager::RegisterSocketService(GenericSocketService *service) {
- service->SetSocketManager(this);
- auto serviceVector = service->GetServiceDescription();
- Try {
- for (auto iter = serviceVector.begin(); iter != serviceVector.end(); ++iter)
- {
- switch(iter->type)
- {
- case GenericSocketService::ServiceDescription::SOCKET_SERVICE:
- CreateDomainSocket(service, *iter);
- break;
- case GenericSocketService::ServiceDescription::FILE_DESC_SERVICE:
- CreateDefaultReadSocketDescription(iter->fileDesc, false, iter->interfaceID, service);
- break;
- default:
- ThrowMsg(Exception::InitFailed, "Wrong service type in service description: " << iter->type);
- break;
- }
- }
- } Catch (Exception::Base) {
- for (int i =0; i < (int)m_socketDescriptionVector.size(); ++i)
- {
- auto &desc = m_socketDescriptionVector[i];
- if (desc.service == service && desc.isOpen) {
- close(i);
- desc.isOpen = false;
- }
- }
- ReThrow(Exception::Base);
- }
-}
+void SocketManager::Write(ConnectionID connectionID, const RawBuffer &rawBuffer)
+{
+ WriteBuffer buffer;
+ buffer.connectionID = connectionID;
+ buffer.rawBuffer = rawBuffer;
-void SocketManager::Close(ConnectionID connectionID) {
- {
- std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
- m_closeQueue.push(connectionID);
- }
- NotifyMe();
-}
+ do {
+ std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
+ m_writeBufferQueue.push(buffer);
+ } while (false);
-void SocketManager::Write(ConnectionID connectionID, const RawBuffer &rawBuffer) {
- WriteBuffer buffer;
- buffer.connectionID = connectionID;
- buffer.rawBuffer = rawBuffer;
- {
- std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
- m_writeBufferQueue.push(buffer);
- }
- NotifyMe();
+ NotifyMe();
}
-void SocketManager::Write(ConnectionID connectionID, const SendMsgData &sendMsgData) {
- WriteData data;
- data.connectionID = connectionID;
- data.sendMsgData = sendMsgData;
- {
- std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
- m_writeDataQueue.push(data);
- }
- NotifyMe();
+void SocketManager::Write(ConnectionID connectionID, const SendMsgData &sendMsgData)
+{
+ WriteData data;
+ data.connectionID = connectionID;
+ data.sendMsgData = sendMsgData;
+
+ do {
+ std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
+ m_writeDataQueue.push(data);
+ } while (false);
+
+ NotifyMe();
}
-void SocketManager::NotifyMe() {
- TEMP_FAILURE_RETRY(write(m_notifyMe[1], "You have message ;-)", 1));
+void SocketManager::NotifyMe()
+{
+ TEMP_FAILURE_RETRY(write(m_notifyMe[1], "You have message ;-)", 1));
}
-void SocketManager::ProcessQueue() {
- WriteBuffer buffer;
- WriteData data;
- {
- std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
- while (!m_writeBufferQueue.empty()) {
- buffer = m_writeBufferQueue.front();
- m_writeBufferQueue.pop();
-
- auto &desc = m_socketDescriptionVector[buffer.connectionID.sock];
-
- if (!desc.isOpen) {
- LogDebug("Received packet for write but connection is closed. Packet ignored!");
- continue;
- }
-
- if (desc.counter != buffer.connectionID.counter)
- {
- LogDebug("Received packet for write but counter is broken. Packet ignored!");
- continue;
- }
-
- if (desc.useSendMsg) {
- LogError("Some service tried to push rawdata to socket that usees sendmsg!");
- continue;
- }
-
- std::copy(
- buffer.rawBuffer.begin(),
- buffer.rawBuffer.end(),
- std::back_inserter(desc.rawBuffer));
-
- FD_SET(buffer.connectionID.sock, &m_writeSet);
- }
-
- while(!m_writeDataQueue.empty()) {
- data = m_writeDataQueue.front();
- m_writeDataQueue.pop();
-
- auto &desc = m_socketDescriptionVector[data.connectionID.sock];
-
- if (!desc.isOpen) {
- LogDebug("Received packet for sendmsg but connection is closed. Packet ignored!");
- continue;
- }
-
- if (desc.counter != data.connectionID.counter)
- {
- LogDebug("Received packet for write but counter is broken. Packet ignored!");
- continue;
- }
-
- if (!desc.useSendMsg) {
- LogError("Some service tries to push SendMsgData to socket that uses write!");
- continue;
- }
-
- desc.sendMsgDataQueue.push(data.sendMsgData);
-
- FD_SET(data.connectionID.sock, &m_writeSet);
- }
- }
-
- while (1) {
- ConnectionID connection;
- {
- std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
- if (m_closeQueue.empty())
- return;
- connection = m_closeQueue.front();
- m_closeQueue.pop();
- }
-
- if (!m_socketDescriptionVector[connection.sock].isOpen)
- continue;
-
- if (connection.counter != m_socketDescriptionVector[connection.sock].counter)
- continue;
-
- CloseSocket(connection.sock);
- }
+void SocketManager::ProcessQueue()
+{
+ do {
+ std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
+
+ WriteBuffer buffer;
+ WriteData data;
+
+ while (!m_writeBufferQueue.empty()) {
+ buffer = m_writeBufferQueue.front();
+ m_writeBufferQueue.pop();
+ auto &desc = m_socketDescriptionVector[buffer.connectionID.sock];
+
+ if (!desc.isOpen) {
+ LogDebug("Received packet for write but connection is closed. Packet ignored!");
+ continue;
+ }
+
+ if (desc.counter != buffer.connectionID.counter) {
+ LogDebug("Received packet for write but counter is broken. Packet ignored!");
+ continue;
+ }
+
+ if (desc.useSendMsg) {
+ LogError("Some service tried to push rawdata to socket that usees sendmsg!");
+ continue;
+ }
+
+ std::copy(
+ buffer.rawBuffer.begin(),
+ buffer.rawBuffer.end(),
+ std::back_inserter(desc.rawBuffer));
+ FD_SET(buffer.connectionID.sock, &m_writeSet);
+ }
+
+ while (!m_writeDataQueue.empty()) {
+ data = m_writeDataQueue.front();
+ m_writeDataQueue.pop();
+ auto &desc = m_socketDescriptionVector[data.connectionID.sock];
+
+ if (!desc.isOpen) {
+ LogDebug("Received packet for sendmsg but connection is closed. Packet ignored!");
+ continue;
+ }
+
+ if (desc.counter != data.connectionID.counter) {
+ LogDebug("Received packet for write but counter is broken. Packet ignored!");
+ continue;
+ }
+
+ if (!desc.useSendMsg) {
+ LogError("Some service tries to push SendMsgData to socket that uses write!");
+ continue;
+ }
+
+ desc.sendMsgDataQueue.push(data.sendMsgData);
+ FD_SET(data.connectionID.sock, &m_writeSet);
+ }
+ } while (false);
+
+ while (true) {
+ ConnectionID connection;
+ do {
+ std::lock_guard<std::mutex> ulock(m_eventQueueMutex);
+
+ if (m_closeQueue.empty())
+ return;
+
+ connection = m_closeQueue.front();
+ m_closeQueue.pop();
+ } while (false);
+
+ if (!m_socketDescriptionVector[connection.sock].isOpen)
+ continue;
+
+ if (connection.counter != m_socketDescriptionVector[connection.sock].counter)
+ continue;
+
+ CloseSocket(connection.sock);
+ }
}
-void SocketManager::CloseSocket(int sock) {
-// LogInfo("Closing socket: " << sock);
- auto &desc = m_socketDescriptionVector[sock];
-
- if (!(desc.isOpen)) {
- // This may happend when some information was waiting for write to the
- // socket and in the same time socket was closed by the client.
- LogError("Socket " << sock << " is not open. Nothing to do!");
- return;
- }
-
- GenericSocketService::CloseEvent event;
- event.connectionID.sock = sock;
- event.connectionID.counter = desc.counter;
- auto service = desc.service;
-
- desc.isOpen = false;
- desc.service = NULL;
- desc.interfaceID = -1;
- desc.rawBuffer.clear();
- while(!desc.sendMsgDataQueue.empty())
- desc.sendMsgDataQueue.pop();
-
- if (service)
- service->Event(event);
- else
- LogError("Critical! Service is NULL! This should never happen!");
-
- TEMP_FAILURE_RETRY(close(sock));
- FD_CLR(sock, &m_readSet);
- FD_CLR(sock, &m_writeSet);
+void SocketManager::CloseSocket(int sock)
+{
+ // LogInfo("Closing socket: " << sock);
+ auto &desc = m_socketDescriptionVector[sock];
+
+ if (!(desc.isOpen)) {
+ // This may happend when some information was waiting for write to the
+ // socket and in the same time socket was closed by the client.
+ LogError("Socket " << sock << " is not open. Nothing to do!");
+ return;
+ }
+
+ GenericSocketService::CloseEvent event;
+ event.connectionID.sock = sock;
+ event.connectionID.counter = desc.counter;
+ auto service = desc.service;
+ desc.isOpen = false;
+ desc.service = NULL;
+ desc.interfaceID = -1;
+ desc.rawBuffer.clear();
+
+ while (!desc.sendMsgDataQueue.empty())
+ desc.sendMsgDataQueue.pop();
+
+ if (service)
+ service->Event(event);
+ else
+ LogError("Critical! Service is NULL! This should never happen!");
+
+ TEMP_FAILURE_RETRY(close(sock));
+ FD_CLR(sock, &m_readSet);
+ FD_CLR(sock, &m_writeSet);
}
} // namespace AuthPasswd
int socket_get_user(int sockfd, unsigned int &user)
{
- struct ucred cr;
- socklen_t len = sizeof(struct ucred);
- if (getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &len)) {
- LogError("getsockopt() failed");
- return 1;
- }
- user = cr.uid;
- return 0;
+ struct ucred cr;
+ socklen_t len = sizeof(struct ucred);
+
+ if (getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &len)) {
+ LogError("getsockopt() failed");
+ return 1;
+ }
+
+ user = cr.uid;
+ return 0;
}
} // namespace AuthPasswd
#include <dpl/exception.h>
-namespace AuthPasswd
-{
- class PasswordException
- {
- public:
- DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
- DECLARE_EXCEPTION_TYPE(Base, OutOfData)
- DECLARE_EXCEPTION_TYPE(Base, NoData)
- DECLARE_EXCEPTION_TYPE(Base, FStreamOpenError)
- DECLARE_EXCEPTION_TYPE(Base, FStreamWriteError)
- DECLARE_EXCEPTION_TYPE(Base, FStreamReadError)
- DECLARE_EXCEPTION_TYPE(Base, MemoryError)
- DECLARE_EXCEPTION_TYPE(Base, NoPasswords)
- DECLARE_EXCEPTION_TYPE(Base, PasswordNotActive)
- DECLARE_EXCEPTION_TYPE(Base, MakeDirError)
- DECLARE_EXCEPTION_TYPE(Base, ChmodError)
- DECLARE_EXCEPTION_TYPE(Base, RemoveError)
- DECLARE_EXCEPTION_TYPE(Base, TimerError)
- };
+namespace AuthPasswd {
+class PasswordException {
+public:
+ DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
+ DECLARE_EXCEPTION_TYPE(Base, OutOfData)
+ DECLARE_EXCEPTION_TYPE(Base, NoData)
+ DECLARE_EXCEPTION_TYPE(Base, FStreamOpenError)
+ DECLARE_EXCEPTION_TYPE(Base, FStreamWriteError)
+ DECLARE_EXCEPTION_TYPE(Base, FStreamReadError)
+ DECLARE_EXCEPTION_TYPE(Base, MemoryError)
+ DECLARE_EXCEPTION_TYPE(Base, NoPasswords)
+ DECLARE_EXCEPTION_TYPE(Base, PasswordNotActive)
+ DECLARE_EXCEPTION_TYPE(Base, MakeDirError)
+ DECLARE_EXCEPTION_TYPE(Base, ChmodError)
+ DECLARE_EXCEPTION_TYPE(Base, RemoveError)
+ DECLARE_EXCEPTION_TYPE(Base, TimerError)
+};
} //namespace AuthPasswd
#endif //_PASSWORD_EXCEPTION_H_
#include <dpl/serialization.h>
-namespace AuthPasswd
-{
- class PasswordFileBuffer: public IStream
- {
- public:
- PasswordFileBuffer();
+namespace AuthPasswd {
+class PasswordFileBuffer: public IStream {
+public:
+ PasswordFileBuffer();
- virtual void Read(size_t num, void *bytes);
- virtual void Write(size_t num, const void *bytes);
+ virtual void Read(size_t num, void *bytes);
+ virtual void Write(size_t num, const void *bytes);
- void Save(const std::string &path);
- void Load(const std::string &path);
+ void Save(const std::string &path);
+ void Load(const std::string &path);
- private:
- typedef std::vector<char> DataBuffer;
+private:
+ typedef std::vector<char> DataBuffer;
- DataBuffer m_buffer;
- size_t m_bufferReadBytes;
- };
+ DataBuffer m_buffer;
+ size_t m_bufferReadBytes;
+};
} //namespace AuthPasswd
#endif
#include <dpl/serialization.h>
-namespace AuthPasswd
-{
- extern const time_t PASSWORD_INFINITE_EXPIRATION_TIME;
+namespace AuthPasswd {
+extern const time_t PASSWORD_INFINITE_EXPIRATION_TIME;
- struct IPassword: public ISerializable
- {
- typedef std::vector<unsigned char> RawHash;
+struct IPassword: public ISerializable {
+ typedef std::vector<unsigned char> RawHash;
- enum class PasswordType : unsigned int
- {
- NONE = 0,
- SHA256 = 1,
- };
+ enum class PasswordType : unsigned int {
+ NONE = 0,
+ SHA256 = 1,
+ };
- virtual bool match(const std::string &password) const = 0;
- };
+ virtual bool match(const std::string &password) const = 0;
+};
- typedef std::shared_ptr<IPassword> IPasswordPtr;
- typedef std::list<IPasswordPtr> PasswordList;
+typedef std::shared_ptr<IPassword> IPasswordPtr;
+typedef std::list<IPasswordPtr> PasswordList;
- class PasswordFile
- {
- public:
- PasswordFile(unsigned int user);
+class PasswordFile {
+public:
+ PasswordFile(unsigned int user);
- void writeMemoryToFile() const;
- void writeAttemptToFile() const;
+ void writeMemoryToFile() const;
+ void writeAttemptToFile() const;
- void setPassword(unsigned int passwdType, const std::string &password);
- bool checkPassword(unsigned int passwdType, const std::string &password) const;
+ void setPassword(unsigned int passwdType, const std::string &password);
+ bool checkPassword(unsigned int passwdType, const std::string &password) const;
- bool isPasswordActive(unsigned int passwdType) const;
+ bool isPasswordActive(unsigned int passwdType) const;
- void setMaxHistorySize(unsigned int history);
- unsigned int getMaxHistorySize() const;
+ void setMaxHistorySize(unsigned int history);
+ unsigned int getMaxHistorySize() const;
- unsigned int getExpireTime() const;
- void setExpireTime(unsigned int expireTime);
+ unsigned int getExpireTime() const;
+ void setExpireTime(unsigned int expireTime);
- unsigned int getExpireTimeLeft() const;
- void setExpireTimeLeft(time_t expireTimeLeft);
+ unsigned int getExpireTimeLeft() const;
+ void setExpireTimeLeft(time_t expireTimeLeft);
- //attempt manipulating functions
- unsigned int getAttempt() const;
- void resetAttempt();
- void incrementAttempt();
- int getMaxAttempt() const;
- void setMaxAttempt(unsigned int maxAttempt);
+ //attempt manipulating functions
+ unsigned int getAttempt() const;
+ void resetAttempt();
+ void incrementAttempt();
+ int getMaxAttempt() const;
+ void setMaxAttempt(unsigned int maxAttempt);
- bool isPasswordReused(const std::string &password) const;
+ bool isPasswordReused(const std::string &password) const;
- bool checkExpiration() const;
- bool checkIfAttemptsExceeded() const;
- bool isIgnorePeriod() const;
+ bool checkExpiration() const;
+ bool checkIfAttemptsExceeded() const;
+ bool isIgnorePeriod() const;
- bool isHistoryActive() const;
+ bool isHistoryActive() const;
- private:
+private:
#if (__GNUC__ > 4) || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 7))
- typedef std::chrono::steady_clock ClockType;
+ typedef std::chrono::steady_clock ClockType;
#else
- typedef std::chrono::monotonic_clock ClockType;
+ typedef std::chrono::monotonic_clock ClockType;
#endif
- typedef std::chrono::duration<double> TimeDiff;
- typedef std::chrono::time_point<ClockType, TimeDiff> TimePoint;
-
- void loadMemoryFromFile();
- bool tryLoadMemoryFromOldFormatFile();
-
- void resetTimer();
- void preparePwdFile();
- void prepareAttemptFile();
- void resetState();
- bool fileExists(const std::string &filename) const;
- bool dirExists(const std::string &dirpath) const;
- std::string createDir(const std::string &dir, unsigned int user) const;
-
- mutable TimePoint m_retryTimerStart;
-
- //user name
- const unsigned int m_user;
-
- //password file data
- IPasswordPtr m_passwordCurrent;
- IPasswordPtr m_passwordRecovery;
- PasswordList m_passwordHistory;
- unsigned int m_maxAttempt;
- unsigned int m_maxHistorySize;
- unsigned int m_expireTime;
- time_t m_expireTimeLeft;
- bool m_passwordActive;
- bool m_passwordRcvActive;
-
- //attempt file data
- unsigned int m_attempt;
- };
+ typedef std::chrono::duration<double> TimeDiff;
+ typedef std::chrono::time_point<ClockType, TimeDiff> TimePoint;
+
+ void loadMemoryFromFile();
+ bool tryLoadMemoryFromOldFormatFile();
+
+ void resetTimer();
+ void preparePwdFile();
+ void prepareAttemptFile();
+ void resetState();
+ bool fileExists(const std::string &filename) const;
+ bool dirExists(const std::string &dirpath) const;
+ std::string createDir(const std::string &dir, unsigned int user) const;
+
+ mutable TimePoint m_retryTimerStart;
+
+ //user name
+ const unsigned int m_user;
+
+ //password file data
+ IPasswordPtr m_passwordCurrent;
+ IPasswordPtr m_passwordRecovery;
+ PasswordList m_passwordHistory;
+ unsigned int m_maxAttempt;
+ unsigned int m_maxHistorySize;
+ unsigned int m_expireTime;
+ time_t m_expireTimeLeft;
+ bool m_passwordActive;
+ bool m_passwordRcvActive;
+
+ //attempt file data
+ unsigned int m_attempt;
+};
} //namespace AuthPasswd
#endif
#include <password-file.h>
-namespace AuthPasswd
-{
- class PasswordManager
- {
- public:
- typedef std::map<unsigned int, PasswordFile> PasswordFileMap;
+namespace AuthPasswd {
+class PasswordManager {
+public:
+ typedef std::map<unsigned int, PasswordFile> PasswordFileMap;
- //checking functions
- //no const in checkPassword, attempts are update
- int checkPassword(unsigned int passwdType, const std::string &challenge,
- unsigned int currentUser, unsigned int ¤tAttempt,
- unsigned int &maxAttempt, unsigned int &expirationTime);
- int isPwdValid(unsigned int passwdType, unsigned int currentUser,
- unsigned int ¤tAttempt, unsigned int &maxAttempt,
- unsigned int &expirationTime);
- int isPwdReused(unsigned int passwdType, const std::string &passwd,
- unsigned int currentUser, bool &isReused);
+ //checking functions
+ //no const in checkPassword, attempts are update
+ int checkPassword(unsigned int passwdType, const std::string &challenge,
+ unsigned int currentUser, unsigned int ¤tAttempt,
+ unsigned int &maxAttempt, unsigned int &expirationTime);
+ int isPwdValid(unsigned int passwdType, unsigned int currentUser,
+ unsigned int ¤tAttempt, unsigned int &maxAttempt,
+ unsigned int &expirationTime);
+ int isPwdReused(unsigned int passwdType, const std::string &passwd,
+ unsigned int currentUser, bool &isReused);
- //setting functions
- int setPassword(unsigned int passwdType, const std::string ¤tPassword,
- const std::string &newPassword, unsigned int currentUser);
- int setPasswordRecovery(const std::string &curRcvPassword, const std::string &newPassword,
- unsigned int currentUser);
+ //setting functions
+ int setPassword(unsigned int passwdType, const std::string ¤tPassword,
+ const std::string &newPassword, unsigned int currentUser);
+ int setPasswordRecovery(const std::string &curRcvPassword, const std::string &newPassword,
+ unsigned int currentUser);
- //resetting functions
- int resetPassword(unsigned int passwdType, const std::string &newPassword,
- unsigned int receivedUser);
+ //resetting functions
+ int resetPassword(unsigned int passwdType, const std::string &newPassword,
+ unsigned int receivedUser);
- //setting policy on the current passwd
- void setPasswordMaxAttempts(unsigned int receivedUser,
- unsigned int receivedAttempts);
- void setPasswordValidity(unsigned int receivedUser, unsigned int receivedDays);
- void setPasswordHistory(unsigned int receivedUser, unsigned int receivedHistory);
+ //setting policy on the current passwd
+ void setPasswordMaxAttempts(unsigned int receivedUser,
+ unsigned int receivedAttempts);
+ void setPasswordValidity(unsigned int receivedUser, unsigned int receivedDays);
+ void setPasswordHistory(unsigned int receivedUser, unsigned int receivedHistory);
- private:
- //managing functions
- void addPassword(unsigned int user);
- void removePassword(unsigned int user);
- void existPassword(unsigned int user);
+private:
+ //managing functions
+ void addPassword(unsigned int user);
+ void removePassword(unsigned int user);
+ void existPassword(unsigned int user);
- PasswordFileMap m_pwdFile;
- };
+ PasswordFileMap m_pwdFile;
+};
} //namespace AuthPasswd
#endif
#include <password-manager.h>
#include <policy-manager.h>
-namespace AuthPasswd
-{
- class PasswordService
- : public AuthPasswd::GenericSocketService
- , public AuthPasswd::ServiceThread<PasswordService>
- {
- public:
- class Exception
- {
- public:
- DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
- DECLARE_EXCEPTION_TYPE(Base, IncorrectHeader)
- };
+namespace AuthPasswd {
+class PasswordService
+ : public AuthPasswd::GenericSocketService
+ , public AuthPasswd::ServiceThread<PasswordService> {
+public:
+ class Exception {
+ public:
+ DECLARE_EXCEPTION_TYPE(AuthPasswd::Exception, Base)
+ DECLARE_EXCEPTION_TYPE(Base, IncorrectHeader)
+ };
- //service functions
- ServiceDescriptionVector GetServiceDescription();
+ //service functions
+ ServiceDescriptionVector GetServiceDescription();
- void Start();
- void Stop();
+ void Start();
+ void Stop();
- DECLARE_THREAD_EVENT(AcceptEvent, accept)
- DECLARE_THREAD_EVENT(WriteEvent, write)
- DECLARE_THREAD_EVENT(ReadEvent, process)
- DECLARE_THREAD_EVENT(CloseEvent, close)
+ DECLARE_THREAD_EVENT(AcceptEvent, accept)
+ DECLARE_THREAD_EVENT(WriteEvent, write)
+ DECLARE_THREAD_EVENT(ReadEvent, process)
+ DECLARE_THREAD_EVENT(CloseEvent, close)
- void accept(const AcceptEvent &event);
- void write(const WriteEvent &event);
- void process(const ReadEvent &event);
- void close(const CloseEvent &event);
+ void accept(const AcceptEvent &event);
+ void write(const WriteEvent &event);
+ void process(const ReadEvent &event);
+ void close(const CloseEvent &event);
- private:
- //internal service functions
- bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
- int processCheckFunctions(PasswordHdrs hdr, MessageBuffer& buffer,
- unsigned int cur_user, unsigned int &cur_att,
- unsigned int &max_att, unsigned int &exp_time);
- int processSetFunctions(PasswordHdrs hdr, MessageBuffer& buffer,
- unsigned int cur_user, bool &isPwdReused);
- int processResetFunctions(PasswordHdrs hdr, MessageBuffer& buffer);
- int processPolicyFunctions(PasswordHdrs hdr, MessageBuffer& buffer);
+private:
+ //internal service functions
+ bool processOne(const ConnectionID &conn, MessageBuffer &buffer, InterfaceID interfaceID);
+ int processCheckFunctions(PasswordHdrs hdr, MessageBuffer &buffer,
+ unsigned int cur_user, unsigned int &cur_att,
+ unsigned int &max_att, unsigned int &exp_time);
+ int processSetFunctions(PasswordHdrs hdr, MessageBuffer &buffer,
+ unsigned int cur_user, bool &isPwdReused);
+ int processResetFunctions(PasswordHdrs hdr, MessageBuffer &buffer);
+ int processPolicyFunctions(PasswordHdrs hdr, MessageBuffer &buffer);
- // service attributes
- PasswordManager m_pwdManager;
- PolicyManager m_policyManager;
- ConnectionInfoMap m_connectionInfoMap;
- };
+ // service attributes
+ PasswordManager m_pwdManager;
+ PolicyManager m_policyManager;
+ ConnectionInfoMap m_connectionInfoMap;
+};
} // namespace AuthPasswd
#endif // _PASSWORD_H_
#include <policy.h>
-namespace AuthPasswd
-{
- class PolicyFile
- {
- public:
- PolicyFile(unsigned int user);
+namespace AuthPasswd {
+class PolicyFile {
+public:
+ PolicyFile(unsigned int user);
- void enable();
- void disable();
+ void enable();
+ void disable();
- bool isPolicyActive() const;
+ bool isPolicyActive() const;
- void writeMemoryToFile() const;
+ void writeMemoryToFile() const;
- bool checkMinLength(const std::string &password) const;
- void setMinLength(unsigned int minLength);
+ bool checkMinLength(const std::string &password) const;
+ void setMinLength(unsigned int minLength);
- bool checkMinComplexCharNumber(const std::string &password) const;
- void setMinComplexCharNumber(unsigned int minComplexCharNumber);
+ bool checkMinComplexCharNumber(const std::string &password) const;
+ void setMinComplexCharNumber(unsigned int minComplexCharNumber);
- bool checkMaxCharOccurrences(const std::string &password) const;
- void setMaxCharOccurrences(unsigned int maxCharOccurrences);
+ bool checkMaxCharOccurrences(const std::string &password) const;
+ void setMaxCharOccurrences(unsigned int maxCharOccurrences);
- bool checkMaxNumSeqLength(const std::string &password) const;
- void setMaxNumSeqLength(unsigned int maxNumSeqLength);
+ bool checkMaxNumSeqLength(const std::string &password) const;
+ void setMaxNumSeqLength(unsigned int maxNumSeqLength);
- bool checkQualityType(const std::string &password) const;
- void setQualityType(unsigned int qualityType);
+ bool checkQualityType(const std::string &password) const;
+ void setQualityType(unsigned int qualityType);
- bool isValidPattern(const std::string &pattern) const;
- bool checkPattern(const std::string &password) const;
- void setPattern(const std::string &pattern);
+ bool isValidPattern(const std::string &pattern) const;
+ bool checkPattern(const std::string &password) const;
+ void setPattern(const std::string &pattern);
- bool checkForbiddenPasswds(const std::string &password) const;
- void setForbiddenPasswds(std::set<std::string> forbiddenPasswds);
+ bool checkForbiddenPasswds(const std::string &password) const;
+ void setForbiddenPasswds(std::set<std::string> forbiddenPasswds);
- private:
- void loadMemoryFromFile();
- void preparePolicyFile();
- void resetState();
- bool fileExists(const std::string &filename) const;
- bool dirExists(const std::string &dirpath) const;
- std::string createDir(const std::string &dir, unsigned int user) const;
+private:
+ void loadMemoryFromFile();
+ void preparePolicyFile();
+ void resetState();
+ bool fileExists(const std::string &filename) const;
+ bool dirExists(const std::string &dirpath) const;
+ std::string createDir(const std::string &dir, unsigned int user) const;
- //user name
- unsigned int m_user;
+ //user name
+ unsigned int m_user;
- bool m_enable;
+ bool m_enable;
- //policy file data
- Policy m_policy;
- };
+ //policy file data
+ Policy m_policy;
+};
} //namespace AuthPasswd
#endif
#include <policy-file.h>
-namespace AuthPasswd
-{
- class PolicyManager
- {
- public:
- typedef std::map<unsigned int, PolicyFile> PolicyFileMap;
-
- // policy checking functions
- int checkPolicy(unsigned int passwdType,
- const std::string ¤tPassword,
- const std::string &newPassword,
- unsigned int user);
-
- // policy setting functions
- int setPolicy(Policy policy);
-
- // policy disabling functions
- int disablePolicy(unsigned int user);
-
- private:
- // managing functions
- void addPolicy(unsigned int user);
- void removePolicy(unsigned int user);
- void existPolicy(unsigned int user);
-
- PolicyFileMap m_policyFile;
- };
+namespace AuthPasswd {
+class PolicyManager {
+public:
+ typedef std::map<unsigned int, PolicyFile> PolicyFileMap;
+
+ // policy checking functions
+ int checkPolicy(unsigned int passwdType,
+ const std::string ¤tPassword,
+ const std::string &newPassword,
+ unsigned int user);
+
+ // policy setting functions
+ int setPolicy(Policy policy);
+
+ // policy disabling functions
+ int disablePolicy(unsigned int user);
+
+private:
+ // managing functions
+ void addPolicy(unsigned int user);
+ void removePolicy(unsigned int user);
+ void existPolicy(unsigned int user);
+
+ PolicyFileMap m_policyFile;
+};
} //namespace AuthPasswd
#endif
#include <string.h>
#include <unistd.h>
-namespace AuthPasswd
+namespace AuthPasswd {
+PasswordFileBuffer::PasswordFileBuffer(): m_bufferReadBytes(0) {}
+
+void PasswordFileBuffer::Read(size_t num, void *bytes)
+{
+ if (m_buffer.empty()) {
+ LogError("Buffer doesn't contain any data.");
+ Throw(PasswordException::NoData);
+ }
+
+ if ((m_bufferReadBytes + num) > m_buffer.size()) {
+ LogError("Not enough buffer to read " << num << " data.");
+ Throw(PasswordException::OutOfData);
+ }
+
+ void *ret = memcpy(bytes, &m_buffer[m_bufferReadBytes], num);
+
+ if (ret == 0) {
+ LogError("Failed to read " << num << " bytes.");
+ Throw(PasswordException::MemoryError);
+ }
+
+ m_bufferReadBytes += num;
+}
+
+void PasswordFileBuffer::Write(size_t num, const void *bytes)
+{
+ const char *buffer = static_cast<const char *>(bytes);
+ std::copy(buffer, buffer + num, std::back_inserter(m_buffer));
+}
+
+void PasswordFileBuffer::Save(const std::string &path)
+{
+ std::ofstream file(path, std::ofstream::trunc);
+
+ if (!file.good()) {
+ LogError("Error while opening file stream.");
+ Throw(PasswordException::FStreamOpenError);
+ }
+
+ file.write(m_buffer.data(), m_buffer.size());
+
+ if (!file) {
+ LogError("Failed to write data.");
+ Throw(PasswordException::FStreamWriteError);
+ }
+
+ file.flush();
+ fsync(DPL::FstreamAccessors<std::ofstream>::GetFd(file)); // flush kernel space buffer
+ file.close();
+}
+
+void PasswordFileBuffer::Load(const std::string &path)
{
- PasswordFileBuffer::PasswordFileBuffer(): m_bufferReadBytes(0) {}
-
- void PasswordFileBuffer::Read(size_t num, void *bytes)
- {
- if(m_buffer.empty()) {
- LogError("Buffer doesn't contain any data.");
- Throw(PasswordException::NoData);
- }
-
- if((m_bufferReadBytes + num) > m_buffer.size()) {
- LogError("Not enough buffer to read " << num << " data.");
- Throw(PasswordException::OutOfData);
- }
-
- void* ret = memcpy(bytes, &m_buffer[m_bufferReadBytes], num);
-
- if(ret == 0) {
- LogError("Failed to read " << num << " bytes.");
- Throw(PasswordException::MemoryError);
- }
-
- m_bufferReadBytes += num;
- }
-
- void PasswordFileBuffer::Write(size_t num, const void *bytes)
- {
- const char* buffer = static_cast<const char*>(bytes);
- std::copy(buffer, buffer+num, std::back_inserter(m_buffer));
- }
-
- void PasswordFileBuffer::Save(const std::string &path)
- {
- std::ofstream file(path, std::ofstream::trunc);
-
- if(!file.good()) {
- LogError("Error while opening file stream.");
- Throw(PasswordException::FStreamOpenError);
- }
-
- file.write(m_buffer.data(), m_buffer.size());
- if(!file) {
- LogError("Failed to write data.");
- Throw(PasswordException::FStreamWriteError);
- }
-
- file.flush();
- fsync(DPL::FstreamAccessors<std::ofstream>::GetFd(file)); // flush kernel space buffer
- file.close();
- }
-
- void PasswordFileBuffer::Load(const std::string &path)
- {
- std::ifstream file(path, std::ifstream::binary);
-
- if(!file.good()) {
- LogError("Error while opening file stream.");
- Throw(PasswordException::FStreamOpenError);
- }
-
- //reset read bytes counter
- m_bufferReadBytes = 0;
-
- m_buffer.assign(std::istreambuf_iterator<char>(file),
- std::istreambuf_iterator<char>());
-
- if(!file) {
- LogError("Failed to read data. Failbit: " << file.fail() << ", Badbit: " << file.bad());
- Throw(PasswordException::FStreamReadError);
- }
- }
+ std::ifstream file(path, std::ifstream::binary);
+
+ if (!file.good()) {
+ LogError("Error while opening file stream.");
+ Throw(PasswordException::FStreamOpenError);
+ }
+
+ //reset read bytes counter
+ m_bufferReadBytes = 0;
+ m_buffer.assign(std::istreambuf_iterator<char>(file),
+ std::istreambuf_iterator<char>());
+
+ if (!file) {
+ LogError("Failed to read data. Failbit: " << file.fail() << ", Badbit: " << file.bad());
+ Throw(PasswordException::FStreamReadError);
+ }
+}
} //namespace AuthPasswd
#include <password-file-buffer.h>
namespace {
- const std::string PASSWORD_FILE = "/password";
- const std::string OLD_VERSION_PASSWORD_FILE = "/password.old";
- const std::string ATTEMPT_FILE = "/attempt";
- const double RETRY_TIMEOUT = 0.5;
- const mode_t FILE_MODE = S_IRUSR | S_IWUSR;
- const unsigned int CURRENT_FILE_VERSION = 1;
+const std::string PASSWORD_FILE = "/password";
+const std::string OLD_VERSION_PASSWORD_FILE = "/password.old";
+const std::string ATTEMPT_FILE = "/attempt";
+const double RETRY_TIMEOUT = 0.5;
+const mode_t FILE_MODE = S_IRUSR | S_IWUSR;
+const unsigned int CURRENT_FILE_VERSION = 1;
} // namespace anonymous
-namespace AuthPasswd
-{
- const time_t PASSWORD_INFINITE_EXPIRATION_TIME = std::numeric_limits<time_t>::max();
-
- class NoPassword: public IPassword
- {
- public:
- NoPassword(IStream&) {}
- NoPassword() {}
-
- void Serialize(IStream &stream) const
- {
- Serialization::Serialize(stream, static_cast<unsigned int>(PasswordType::NONE));
- }
-
- bool match(const std::string &pass) const
- {
- return pass.empty();
- }
- };
-
- class SHA256Password: public IPassword
- {
- public:
- SHA256Password(IStream& stream)
- {
- Deserialization::Deserialize(stream, m_hash);
- }
-
- SHA256Password(const std::string &password)
- : m_hash(hash(password)) {}
-
- SHA256Password(const RawHash& paramHash)
- : m_hash(paramHash) {}
-
- void Serialize(IStream &stream) const
- {
- Serialization::Serialize(stream, static_cast<unsigned int>(PasswordType::SHA256));
- Serialization::Serialize(stream, m_hash);
- }
-
- bool match(const std::string &password) const
- {
- return m_hash == hash(password);
- }
- private:
- RawHash m_hash;
-
- static RawHash hash(const std::string &password)
- {
- RawHash result(SHA256_DIGEST_LENGTH);
-
- SHA256_CTX context;
- SHA256_Init(&context);
- SHA256_Update(&context, reinterpret_cast<const unsigned char*>(password.c_str()),
- password.size());
- SHA256_Final(result.data(), &context);
-
- return result;
- }
- };
-
- // deserialization of new password format
- template <>
- void Deserialization::Deserialize(IStream& stream, IPasswordPtr& ptr)
- {
- unsigned int algorithm;
- Deserialization::Deserialize(stream, algorithm);
- switch (algorithm) {
- case (unsigned int)IPassword::PasswordType::NONE:
- ptr.reset(new NoPassword());
- break;
- case (unsigned int)IPassword::PasswordType::SHA256:
- ptr.reset(new SHA256Password(stream));
- break;
- default:
- Throw(PasswordException::FStreamReadError);
- }
- }
-
- PasswordFile::PasswordFile(unsigned int user): m_user(user),
- m_passwordCurrent(new NoPassword()),
- m_passwordRecovery(new NoPassword()),
- m_maxAttempt(PASSWORD_INFINITE_ATTEMPT_COUNT),
- m_maxHistorySize(0),
- m_expireTime(PASSWORD_INFINITE_EXPIRATION_DAYS),
- m_expireTimeLeft(PASSWORD_INFINITE_EXPIRATION_TIME),
- m_passwordActive(false),
- m_passwordRcvActive(false),
- m_attempt(0)
- {
- // check if data directory exists
- // if not create it
- std::string userDir = createDir(RW_DATA_DIR, m_user);
-
- if (!dirExists(RW_DATA_DIR)) {
- if(mkdir(RW_DATA_DIR, 0700)) {
- LogError("Failed to create directory for files. Error: " << errnoToString());
- Throw(PasswordException::MakeDirError);
- }
- }
-
- if (!dirExists(userDir.c_str())) {
- if(mkdir(userDir.c_str(), 0700)) {
- LogError("Failed to create directory for files. Error: " << errnoToString());
- Throw(PasswordException::MakeDirError);
- }
- }
-
- preparePwdFile();
- prepareAttemptFile();
- resetTimer();
- }
-
- void PasswordFile::resetState()
- {
- m_maxAttempt = PASSWORD_INFINITE_ATTEMPT_COUNT;
- m_maxHistorySize = 0;
- m_expireTime = PASSWORD_INFINITE_EXPIRATION_DAYS;
- m_expireTimeLeft = PASSWORD_INFINITE_EXPIRATION_TIME;
- m_passwordRcvActive = false;
- m_passwordRecovery.reset(new NoPassword());
- m_passwordActive = false;
- m_passwordCurrent.reset(new NoPassword());
- }
-
- void PasswordFile::resetTimer()
- {
- m_retryTimerStart = ClockType::now();
- m_retryTimerStart -= TimeDiff(RETRY_TIMEOUT);
- }
-
- void PasswordFile::preparePwdFile()
- {
- std::string pwdFile = createDir(RW_DATA_DIR, m_user) + PASSWORD_FILE;
- std::string oldVersionPwdFile = createDir(RW_DATA_DIR, m_user) + OLD_VERSION_PASSWORD_FILE;
-
- // check if password file exists
- if (!fileExists(pwdFile)) {
- // if old format file exist - load it
- if (tryLoadMemoryFromOldFormatFile()) {
- // save in new format
- writeMemoryToFile();
- // and remove old file
- if (remove(oldVersionPwdFile.c_str())) {
- LogError("Failed to remove file" << oldVersionPwdFile <<
- " Error: " << errnoToString());
- Throw(PasswordException::RemoveError);
- }
- return;
- }
- LogSecureDebug("PWD_DBG not found " << m_user << " password file. Creating.");
-
- //create file
- writeMemoryToFile();
- } else { //if file exists, load data
- LogSecureDebug("PWD_DBG found " << m_user << " password file. Opening.");
- try {
- loadMemoryFromFile();
- } catch (...) {
- LogError("Invalid " << pwdFile << " file format");
- resetState();
- writeMemoryToFile();
- }
- }
- }
-
- void PasswordFile::prepareAttemptFile()
- {
- std::string attemptFile = createDir(RW_DATA_DIR, m_user) + ATTEMPT_FILE;
-
- // check if attempt file exists
- // if not create it
- if (!fileExists(attemptFile)) {
- LogSecureDebug("PWD_DBG not found " << m_user << " attempt file. Creating.");
- writeAttemptToFile();
- } else {
- LogSecureDebug("PWD_DBG found " << m_user << " attempt file. Opening.");
- std::ifstream AttemptFile(attemptFile);
- if(!AttemptFile) {
- LogError("Failed to open " << m_user << " attempt file.");
- // ignore error
- return;
- }
-
- AttemptFile.read(reinterpret_cast<char*>(&m_attempt), sizeof(unsigned int));
- if(!AttemptFile) {
- LogError("Failed to read " << m_user <<" attempt count.");
- // ignore error
- resetAttempt();
- }
- }
- }
-
- bool PasswordFile::fileExists(const std::string &filename) const
- {
- struct stat buf;
-
- return ((stat(filename.c_str(), &buf) == 0));
- }
-
- bool PasswordFile::dirExists(const std::string &dirpath) const
- {
- struct stat buf;
-
- return ((stat(dirpath.c_str(), &buf) == 0) && (((buf.st_mode) & S_IFMT) == S_IFDIR));
- }
-
- std::string PasswordFile::createDir(const std::string &dir, unsigned int user) const
- {
- std::string User = std::to_string(user);
- return dir + "/" + User;
- }
-
- void PasswordFile::writeMemoryToFile() const
- {
- PasswordFileBuffer pwdBuffer;
-
- LogSecureDebug("User: " << m_user << ", saving max_att: " << m_maxAttempt <<
- ", history_size: " << m_maxHistorySize << ", m_expireTime: " <<
- m_expireTime << ", m_expireTimeLeft: " << m_expireTimeLeft <<
- ", isActive: " << m_passwordActive << ", isRcvActive: " <<
- m_passwordRcvActive);
-
- //serialize password attributes
- Serialization::Serialize(pwdBuffer, CURRENT_FILE_VERSION);
- Serialization::Serialize(pwdBuffer, m_maxAttempt);
- Serialization::Serialize(pwdBuffer, m_maxHistorySize);
- Serialization::Serialize(pwdBuffer, m_expireTime);
- Serialization::Serialize(pwdBuffer, m_expireTimeLeft);
- Serialization::Serialize(pwdBuffer, m_passwordRcvActive);
- Serialization::Serialize(pwdBuffer, m_passwordRecovery);
- Serialization::Serialize(pwdBuffer, m_passwordActive);
- Serialization::Serialize(pwdBuffer, m_passwordCurrent);
- Serialization::Serialize(pwdBuffer, m_passwordHistory);
-
- std::string pwdFile = createDir(RW_DATA_DIR, m_user) + PASSWORD_FILE;
- pwdBuffer.Save(pwdFile);
-
- if (chmod(pwdFile.c_str(), FILE_MODE)) {
- LogError("Failed to chmod for " << pwdFile << " Error: " << errnoToString());
- Throw(PasswordException::ChmodError);
- }
- }
-
- void PasswordFile::loadMemoryFromFile()
- {
- PasswordFileBuffer pwdBuffer;
- std::string pwdFile = createDir(RW_DATA_DIR, m_user) + PASSWORD_FILE;
-
- pwdBuffer.Load(pwdFile);
-
- unsigned int fileVersion = 0;
- Deserialization::Deserialize(pwdBuffer, fileVersion);
- if (fileVersion != CURRENT_FILE_VERSION)
- Throw(PasswordException::FStreamReadError);
-
- m_passwordHistory.clear();
-
- Deserialization::Deserialize(pwdBuffer, m_maxAttempt);
- Deserialization::Deserialize(pwdBuffer, m_maxHistorySize);
- Deserialization::Deserialize(pwdBuffer, m_expireTime);
- Deserialization::Deserialize(pwdBuffer, m_expireTimeLeft);
- Deserialization::Deserialize(pwdBuffer, m_passwordRcvActive);
- Deserialization::Deserialize(pwdBuffer, m_passwordRecovery);
- Deserialization::Deserialize(pwdBuffer, m_passwordActive);
- Deserialization::Deserialize(pwdBuffer, m_passwordCurrent);
- Deserialization::Deserialize(pwdBuffer, m_passwordHistory);
-
- LogSecureDebug("User: " << m_user << ", loaded max_att: " << m_maxAttempt <<
- ", history_size: " << m_maxHistorySize << ", m_expireTime: " <<
- m_expireTime << ", m_expireTimeLeft: " << m_expireTimeLeft <<
- ", isActive: " << m_passwordActive << ", isRcvActive: " <<
- m_passwordRcvActive);
- }
-
- bool PasswordFile::tryLoadMemoryFromOldFormatFile()
- {
- struct stat oldFileStat;
- std::string oldVersionPwdFile = createDir(RW_DATA_DIR, m_user) + OLD_VERSION_PASSWORD_FILE;
-
- if (stat(oldVersionPwdFile.c_str(), &oldFileStat) != 0)
- return false;
-
- static const int ELEMENT_SIZE = sizeof(unsigned) + SHA256_DIGEST_LENGTH;
- static const int VERSION_1_REMAINING = sizeof(unsigned) * 4;
- static const int VERSION_2_REMAINING = VERSION_1_REMAINING + sizeof(bool);
- int remaining = oldFileStat.st_size % ELEMENT_SIZE;
-
- if (remaining != VERSION_1_REMAINING && remaining != VERSION_2_REMAINING)
- return false;
-
- try {
- PasswordFileBuffer pwdBuffer;
- pwdBuffer.Load(oldVersionPwdFile);
-
- Deserialization::Deserialize(pwdBuffer, m_maxAttempt);
- Deserialization::Deserialize(pwdBuffer, m_maxHistorySize);
- Deserialization::Deserialize(pwdBuffer, m_expireTimeLeft);
- if (m_expireTimeLeft == 0)
- m_expireTimeLeft = PASSWORD_INFINITE_EXPIRATION_TIME;
-
- if (remaining == VERSION_2_REMAINING)
- Deserialization::Deserialize(pwdBuffer, m_passwordActive);
- else
- m_passwordActive = true;
-
- // deserialize passwords in old format
- struct OldPassword {
- OldPassword() {}
- OldPassword(IStream &stream)
- {
- Deserialization::Deserialize(stream, m_hash);
- }
- IPassword::RawHash m_hash;
- };
- std::list<OldPassword> oldFormatPasswords;
- Deserialization::Deserialize(pwdBuffer, oldFormatPasswords);
-
- // convert passwords to new format
- m_passwordHistory.clear();
- if (oldFormatPasswords.empty()) {
- m_passwordCurrent.reset(new NoPassword());
- m_passwordActive = false;
- } else {
- m_passwordCurrent.reset(new SHA256Password(oldFormatPasswords.front().m_hash));
- std::for_each(++oldFormatPasswords.begin(), oldFormatPasswords.end(),
- [&] (const OldPassword& pwd)
- {m_passwordHistory.push_back(IPasswordPtr(new SHA256Password(pwd.m_hash)));}
- );
- }
-
- m_expireTime = PASSWORD_INFINITE_EXPIRATION_DAYS;
- m_passwordRcvActive = false;
- m_passwordRecovery.reset(new NoPassword());
-
- } catch (...) {
- LogWarning("Invalid " << oldVersionPwdFile << " file format");
- resetState();
- return false;
- }
-
- return true;
- }
-
- void PasswordFile::writeAttemptToFile() const
- {
- std::string attemptFile = createDir(RW_DATA_DIR, m_user) + ATTEMPT_FILE;
-
- std::ofstream AttemptFile(attemptFile, std::ofstream::trunc);
-
- if(!AttemptFile.good()) {
- LogError("Failed to open " << m_user << " attempt file.");
- Throw(PasswordException::FStreamOpenError);
- }
-
- AttemptFile.write(reinterpret_cast<const char*>(&m_attempt), sizeof(unsigned int));
- if(!AttemptFile) {
- LogError("Failed to write " << m_user << " attempt count.");
- Throw(PasswordException::FStreamWriteError);
- }
-
- AttemptFile.flush();
- fsync(DPL::FstreamAccessors<std::ofstream>::GetFd(AttemptFile)); // flush kernel space buffer
- AttemptFile.close();
- }
-
- bool PasswordFile::isPasswordActive(unsigned int passwdType) const
- {
- bool ret = false;
-
- if (passwdType == AUTH_PWD_NORMAL)
- ret = m_passwordActive;
- else if (passwdType == AUTH_PWD_RECOVERY)
- ret = m_passwordRcvActive;
- return ret;
- }
-
- void PasswordFile::setMaxHistorySize(unsigned int history)
- {
- // put current password in history
- if (m_maxHistorySize == 0 && history > 0)
- m_passwordHistory.push_front(m_passwordCurrent);
-
- //setting history should be independent from password being set
- m_maxHistorySize = history;
-
- while(m_passwordHistory.size() > history)
- m_passwordHistory.pop_back();
- }
-
- unsigned int PasswordFile::getMaxHistorySize() const
- {
- return m_maxHistorySize;
- }
-
- unsigned int PasswordFile::getAttempt() const
- {
- return m_attempt;
- }
-
- void PasswordFile::resetAttempt()
- {
- m_attempt = 0;
- }
-
- void PasswordFile::incrementAttempt()
- {
- m_attempt++;
- }
-
- int PasswordFile::getMaxAttempt() const
- {
- return m_maxAttempt;
- }
-
- void PasswordFile::setMaxAttempt(unsigned int maxAttempt)
- {
- m_maxAttempt = maxAttempt;
- }
-
- bool PasswordFile::isPasswordReused(const std::string &password) const
- {
- LogSecureDebug("Checking if " << m_user << " pwd is reused. HistorySize: " <<
- m_passwordHistory.size() << ", MaxHistorySize: " << getMaxHistorySize());
-
- //go through history and check if password existed earlier
- if(std::any_of(m_passwordHistory.begin(), m_passwordHistory.end(),
- [&password](const IPasswordPtr& pwd) { return pwd->match(password); })) {
- LogSecureDebug(m_user << " passwords match!");
- return true;
- }
-
- LogSecureDebug("isPasswordReused: No passwords match, " << m_user <<
- " password not reused.");
- return false;
- }
-
- void PasswordFile::setPassword(unsigned int passwdType, const std::string &password)
- {
- if (passwdType == AUTH_PWD_NORMAL) {
- //replace current password with new one
- if (password.empty()) {
- m_passwordCurrent.reset(new NoPassword());
- m_passwordActive = false;
- } else {
- m_passwordCurrent.reset(new SHA256Password(password));
-
- //put current password to history
- m_passwordHistory.push_front(m_passwordCurrent);
-
- //erase last password if we exceed max history size
- if(m_passwordHistory.size() > getMaxHistorySize())
- m_passwordHistory.pop_back();
- m_passwordActive = true;
- }
- } else if (passwdType == AUTH_PWD_RECOVERY) {
- //replace current password with new one
- if (password.empty()) {
- m_passwordRecovery.reset(new NoPassword());
- m_passwordRcvActive = false;
- } else {
- m_passwordRecovery.reset(new SHA256Password(password));
- m_passwordRcvActive = true;
- }
- }
- }
-
- bool PasswordFile::checkPassword(unsigned int passwdType, const std::string &password) const
- {
- bool ret = false;
- if (passwdType == AUTH_PWD_NORMAL)
- ret = m_passwordCurrent->match(password);
- else if (passwdType == AUTH_PWD_RECOVERY)
- ret = m_passwordRecovery->match(password);
- return ret;
- }
-
- void PasswordFile::setExpireTime(unsigned int expireTime)
- {
- m_expireTime = expireTime;
- }
-
- unsigned int PasswordFile::getExpireTime() const
- {
- return m_expireTime;
- }
-
- void PasswordFile::setExpireTimeLeft(time_t expireTimeLeft)
- {
- m_expireTimeLeft = expireTimeLeft;
- }
-
- unsigned int PasswordFile::getExpireTimeLeft() const
- {
- if(m_expireTimeLeft != PASSWORD_INFINITE_EXPIRATION_TIME) {
- time_t timeLeft = m_expireTimeLeft - time(NULL);
- return (timeLeft < 0) ? 0 : static_cast<unsigned int>(timeLeft);
- } else
- return PASSWORD_API_NO_EXPIRATION;
- }
-
- bool PasswordFile::checkExpiration() const
- {
- //return true if expired, else false
- return ((m_expireTimeLeft != PASSWORD_INFINITE_EXPIRATION_TIME) && (time(NULL) > m_expireTimeLeft));
- }
-
- bool PasswordFile::checkIfAttemptsExceeded() const
- {
- return ((m_maxAttempt != PASSWORD_INFINITE_ATTEMPT_COUNT) && (m_attempt > m_maxAttempt));
- }
-
- bool PasswordFile::isIgnorePeriod() const
- {
- TimePoint retryTimerStop = ClockType::now();
- TimeDiff diff = retryTimerStop - m_retryTimerStart;
-
- m_retryTimerStart = retryTimerStop;
-
- return (diff.count() < RETRY_TIMEOUT);
- }
-
- bool PasswordFile::isHistoryActive() const
- {
- return (m_maxHistorySize != 0);
- }
-} //namespace AuthPasswd
+namespace AuthPasswd {
+const time_t PASSWORD_INFINITE_EXPIRATION_TIME = std::numeric_limits<time_t>::max();
+
+class NoPassword: public IPassword {
+public:
+ NoPassword(IStream &) {}
+ NoPassword() {}
+
+ void Serialize(IStream &stream) const {
+ Serialization::Serialize(stream, static_cast<unsigned int>(PasswordType::NONE));
+ }
+
+ bool match(const std::string &pass) const {
+ return pass.empty();
+ }
+};
+
+class SHA256Password: public IPassword {
+public:
+ SHA256Password(IStream &stream) {
+ Deserialization::Deserialize(stream, m_hash);
+ }
+
+ SHA256Password(const std::string &password) : m_hash(hash(password)) {}
+
+ SHA256Password(const RawHash ¶mHash) : m_hash(paramHash) {}
+
+ void Serialize(IStream &stream) const {
+ Serialization::Serialize(stream, static_cast<unsigned int>(PasswordType::SHA256));
+ Serialization::Serialize(stream, m_hash);
+ }
+
+ bool match(const std::string &password) const {
+ return m_hash == hash(password);
+ }
+
+private:
+ RawHash m_hash;
+
+ static RawHash hash(const std::string &password) {
+ RawHash result(SHA256_DIGEST_LENGTH);
+ SHA256_CTX context;
+ SHA256_Init(&context);
+ SHA256_Update(&context, reinterpret_cast<const unsigned char *>(password.c_str()),
+ password.size());
+ SHA256_Final(result.data(), &context);
+ return result;
+ }
+};
+
+// deserialization of new password format
+template <>
+void Deserialization::Deserialize(IStream &stream, IPasswordPtr &ptr)
+{
+ unsigned int algorithm;
+ Deserialization::Deserialize(stream, algorithm);
+
+ switch (algorithm) {
+ case (unsigned int)IPassword::PasswordType::NONE:
+ ptr.reset(new NoPassword());
+ break;
+
+ case (unsigned int)IPassword::PasswordType::SHA256:
+ ptr.reset(new SHA256Password(stream));
+ break;
+
+ default:
+ Throw(PasswordException::FStreamReadError);
+ }
+}
+
+PasswordFile::PasswordFile(unsigned int user) :
+ m_user(user),
+ m_passwordCurrent(new NoPassword()),
+ m_passwordRecovery(new NoPassword()),
+ m_maxAttempt(PASSWORD_INFINITE_ATTEMPT_COUNT),
+ m_maxHistorySize(0),
+ m_expireTime(PASSWORD_INFINITE_EXPIRATION_DAYS),
+ m_expireTimeLeft(PASSWORD_INFINITE_EXPIRATION_TIME),
+ m_passwordActive(false),
+ m_passwordRcvActive(false),
+ m_attempt(0)
+{
+ // check if data directory exists
+ // if not create it
+ std::string userDir = createDir(RW_DATA_DIR, m_user);
+
+ if (!dirExists(RW_DATA_DIR)) {
+ if (mkdir(RW_DATA_DIR, 0700)) {
+ LogError("Failed to create directory for files. Error: " << errnoToString());
+ Throw(PasswordException::MakeDirError);
+ }
+ }
+
+ if (!dirExists(userDir.c_str())) {
+ if (mkdir(userDir.c_str(), 0700)) {
+ LogError("Failed to create directory for files. Error: " << errnoToString());
+ Throw(PasswordException::MakeDirError);
+ }
+ }
+
+ preparePwdFile();
+ prepareAttemptFile();
+ resetTimer();
+}
+
+void PasswordFile::resetState()
+{
+ m_maxAttempt = PASSWORD_INFINITE_ATTEMPT_COUNT;
+ m_maxHistorySize = 0;
+ m_expireTime = PASSWORD_INFINITE_EXPIRATION_DAYS;
+ m_expireTimeLeft = PASSWORD_INFINITE_EXPIRATION_TIME;
+ m_passwordRcvActive = false;
+ m_passwordRecovery.reset(new NoPassword());
+ m_passwordActive = false;
+ m_passwordCurrent.reset(new NoPassword());
+}
+
+void PasswordFile::resetTimer()
+{
+ m_retryTimerStart = ClockType::now();
+ m_retryTimerStart -= TimeDiff(RETRY_TIMEOUT);
+}
+
+void PasswordFile::preparePwdFile()
+{
+ std::string pwdFile = createDir(RW_DATA_DIR, m_user) + PASSWORD_FILE;
+ std::string oldVersionPwdFile = createDir(RW_DATA_DIR, m_user) + OLD_VERSION_PASSWORD_FILE;
+
+ // check if password file exists
+ if (!fileExists(pwdFile)) {
+ // if old format file exist - load it
+ if (tryLoadMemoryFromOldFormatFile()) {
+ // save in new format
+ writeMemoryToFile();
+
+ // and remove old file
+ if (remove(oldVersionPwdFile.c_str())) {
+ LogError("Failed to remove file" << oldVersionPwdFile <<
+ " Error: " << errnoToString());
+ Throw(PasswordException::RemoveError);
+ }
+
+ return;
+ }
+
+ LogSecureDebug("PWD_DBG not found " << m_user << " password file. Creating.");
+ //create file
+ writeMemoryToFile();
+ } else { //if file exists, load data
+ LogSecureDebug("PWD_DBG found " << m_user << " password file. Opening.");
+
+ try {
+ loadMemoryFromFile();
+ } catch (...) {
+ LogError("Invalid " << pwdFile << " file format");
+ resetState();
+ writeMemoryToFile();
+ }
+ }
+}
+
+void PasswordFile::prepareAttemptFile()
+{
+ std::string attemptFile = createDir(RW_DATA_DIR, m_user) + ATTEMPT_FILE;
+
+ // check if attempt file exists
+ // if not create it
+ if (!fileExists(attemptFile)) {
+ LogSecureDebug("PWD_DBG not found " << m_user << " attempt file. Creating.");
+ writeAttemptToFile();
+ } else {
+ LogSecureDebug("PWD_DBG found " << m_user << " attempt file. Opening.");
+ std::ifstream AttemptFile(attemptFile);
+
+ if (!AttemptFile) {
+ LogError("Failed to open " << m_user << " attempt file.");
+ // ignore error
+ return;
+ }
+
+ AttemptFile.read(reinterpret_cast<char *>(&m_attempt), sizeof(unsigned int));
+
+ if (!AttemptFile) {
+ LogError("Failed to read " << m_user << " attempt count.");
+ // ignore error
+ resetAttempt();
+ }
+ }
+}
+
+bool PasswordFile::fileExists(const std::string &filename) const
+{
+ struct stat buf;
+ return ((stat(filename.c_str(), &buf) == 0));
+}
+
+bool PasswordFile::dirExists(const std::string &dirpath) const
+{
+ struct stat buf;
+ return ((stat(dirpath.c_str(), &buf) == 0) && (((buf.st_mode) & S_IFMT) == S_IFDIR));
+}
+
+std::string PasswordFile::createDir(const std::string &dir, unsigned int user) const
+{
+ std::string User = std::to_string(user);
+ return dir + "/" + User;
+}
+
+void PasswordFile::writeMemoryToFile() const
+{
+ PasswordFileBuffer pwdBuffer;
+ LogSecureDebug("User: " << m_user << ", saving max_att: " << m_maxAttempt <<
+ ", history_size: " << m_maxHistorySize << ", m_expireTime: " <<
+ m_expireTime << ", m_expireTimeLeft: " << m_expireTimeLeft <<
+ ", isActive: " << m_passwordActive << ", isRcvActive: " <<
+ m_passwordRcvActive);
+ //serialize password attributes
+ Serialization::Serialize(pwdBuffer, CURRENT_FILE_VERSION);
+ Serialization::Serialize(pwdBuffer, m_maxAttempt);
+ Serialization::Serialize(pwdBuffer, m_maxHistorySize);
+ Serialization::Serialize(pwdBuffer, m_expireTime);
+ Serialization::Serialize(pwdBuffer, m_expireTimeLeft);
+ Serialization::Serialize(pwdBuffer, m_passwordRcvActive);
+ Serialization::Serialize(pwdBuffer, m_passwordRecovery);
+ Serialization::Serialize(pwdBuffer, m_passwordActive);
+ Serialization::Serialize(pwdBuffer, m_passwordCurrent);
+ Serialization::Serialize(pwdBuffer, m_passwordHistory);
+ std::string pwdFile = createDir(RW_DATA_DIR, m_user) + PASSWORD_FILE;
+ pwdBuffer.Save(pwdFile);
+
+ if (chmod(pwdFile.c_str(), FILE_MODE)) {
+ LogError("Failed to chmod for " << pwdFile << " Error: " << errnoToString());
+ Throw(PasswordException::ChmodError);
+ }
+}
+
+void PasswordFile::loadMemoryFromFile()
+{
+ PasswordFileBuffer pwdBuffer;
+ std::string pwdFile = createDir(RW_DATA_DIR, m_user) + PASSWORD_FILE;
+ pwdBuffer.Load(pwdFile);
+ unsigned int fileVersion = 0;
+ Deserialization::Deserialize(pwdBuffer, fileVersion);
+
+ if (fileVersion != CURRENT_FILE_VERSION)
+ Throw(PasswordException::FStreamReadError);
+
+ m_passwordHistory.clear();
+ Deserialization::Deserialize(pwdBuffer, m_maxAttempt);
+ Deserialization::Deserialize(pwdBuffer, m_maxHistorySize);
+ Deserialization::Deserialize(pwdBuffer, m_expireTime);
+ Deserialization::Deserialize(pwdBuffer, m_expireTimeLeft);
+ Deserialization::Deserialize(pwdBuffer, m_passwordRcvActive);
+ Deserialization::Deserialize(pwdBuffer, m_passwordRecovery);
+ Deserialization::Deserialize(pwdBuffer, m_passwordActive);
+ Deserialization::Deserialize(pwdBuffer, m_passwordCurrent);
+ Deserialization::Deserialize(pwdBuffer, m_passwordHistory);
+ LogSecureDebug("User: " << m_user << ", loaded max_att: " << m_maxAttempt <<
+ ", history_size: " << m_maxHistorySize << ", m_expireTime: " <<
+ m_expireTime << ", m_expireTimeLeft: " << m_expireTimeLeft <<
+ ", isActive: " << m_passwordActive << ", isRcvActive: " <<
+ m_passwordRcvActive);
+}
+
+bool PasswordFile::tryLoadMemoryFromOldFormatFile()
+{
+ struct stat oldFileStat;
+ std::string oldVersionPwdFile = createDir(RW_DATA_DIR, m_user) + OLD_VERSION_PASSWORD_FILE;
+
+ if (stat(oldVersionPwdFile.c_str(), &oldFileStat) != 0)
+ return false;
+
+ static const int ELEMENT_SIZE = sizeof(unsigned) + SHA256_DIGEST_LENGTH;
+ static const int VERSION_1_REMAINING = sizeof(unsigned) * 4;
+ static const int VERSION_2_REMAINING = VERSION_1_REMAINING + sizeof(bool);
+ int remaining = oldFileStat.st_size % ELEMENT_SIZE;
+
+ if (remaining != VERSION_1_REMAINING && remaining != VERSION_2_REMAINING)
+ return false;
+
+ try {
+ PasswordFileBuffer pwdBuffer;
+ pwdBuffer.Load(oldVersionPwdFile);
+ Deserialization::Deserialize(pwdBuffer, m_maxAttempt);
+ Deserialization::Deserialize(pwdBuffer, m_maxHistorySize);
+ Deserialization::Deserialize(pwdBuffer, m_expireTimeLeft);
+
+ if (m_expireTimeLeft == 0)
+ m_expireTimeLeft = PASSWORD_INFINITE_EXPIRATION_TIME;
+
+ if (remaining == VERSION_2_REMAINING)
+ Deserialization::Deserialize(pwdBuffer, m_passwordActive);
+ else
+ m_passwordActive = true;
+
+ // deserialize passwords in old format
+ struct OldPassword {
+ OldPassword() {}
+ OldPassword(IStream &stream) {
+ Deserialization::Deserialize(stream, m_hash);
+ }
+ IPassword::RawHash m_hash;
+ };
+ std::list<OldPassword> oldFormatPasswords;
+ Deserialization::Deserialize(pwdBuffer, oldFormatPasswords);
+ // convert passwords to new format
+ m_passwordHistory.clear();
+
+ if (oldFormatPasswords.empty()) {
+ m_passwordCurrent.reset(new NoPassword());
+ m_passwordActive = false;
+ } else {
+ m_passwordCurrent.reset(new SHA256Password(oldFormatPasswords.front().m_hash));
+ std::for_each(
+ ++oldFormatPasswords.begin(),
+ oldFormatPasswords.end(),
+ [&](const OldPassword & pwd) {
+ m_passwordHistory.push_back(IPasswordPtr(new SHA256Password(pwd.m_hash)));
+ });
+ }
+
+ m_expireTime = PASSWORD_INFINITE_EXPIRATION_DAYS;
+ m_passwordRcvActive = false;
+ m_passwordRecovery.reset(new NoPassword());
+ } catch (...) {
+ LogWarning("Invalid " << oldVersionPwdFile << " file format");
+ resetState();
+ return false;
+ }
+
+ return true;
+}
+
+void PasswordFile::writeAttemptToFile() const
+{
+ std::string attemptFile = createDir(RW_DATA_DIR, m_user) + ATTEMPT_FILE;
+ std::ofstream AttemptFile(attemptFile, std::ofstream::trunc);
+
+ if (!AttemptFile.good()) {
+ LogError("Failed to open " << m_user << " attempt file.");
+ Throw(PasswordException::FStreamOpenError);
+ }
+
+ AttemptFile.write(reinterpret_cast<const char *>(&m_attempt), sizeof(unsigned int));
+
+ if (!AttemptFile) {
+ LogError("Failed to write " << m_user << " attempt count.");
+ Throw(PasswordException::FStreamWriteError);
+ }
+
+ AttemptFile.flush();
+ fsync(DPL::FstreamAccessors<std::ofstream>::GetFd(AttemptFile)); // flush kernel space buffer
+ AttemptFile.close();
+}
+
+bool PasswordFile::isPasswordActive(unsigned int passwdType) const
+{
+ switch (passwdType) {
+ case AUTH_PWD_NORMAL: return m_passwordActive;
+ case AUTH_PWD_RECOVERY: return m_passwordRcvActive;
+ default: return false;
+ }
+}
+
+void PasswordFile::setMaxHistorySize(unsigned int history)
+{
+ // put current password in history
+ if (m_maxHistorySize == 0 && history > 0)
+ m_passwordHistory.push_front(m_passwordCurrent);
+
+ //setting history should be independent from password being set
+ m_maxHistorySize = history;
+
+ while (m_passwordHistory.size() > history)
+ m_passwordHistory.pop_back();
+}
+
+unsigned int PasswordFile::getMaxHistorySize() const
+{
+ return m_maxHistorySize;
+}
+unsigned int PasswordFile::getAttempt() const
+{
+ return m_attempt;
+}
+
+void PasswordFile::resetAttempt()
+{
+ m_attempt = 0;
+}
+
+void PasswordFile::incrementAttempt()
+{
+ m_attempt++;
+}
+
+int PasswordFile::getMaxAttempt() const
+{
+ return m_maxAttempt;
+}
+
+void PasswordFile::setMaxAttempt(unsigned int maxAttempt)
+{
+ m_maxAttempt = maxAttempt;
+}
+
+bool PasswordFile::isPasswordReused(const std::string &password) const
+{
+ LogSecureDebug("Checking if " << m_user << " pwd is reused. HistorySize: " <<
+ m_passwordHistory.size() << ", MaxHistorySize: " << getMaxHistorySize());
+
+ // go through history and check if password existed earlier
+ if (std::any_of(
+ m_passwordHistory.begin(),
+ m_passwordHistory.end(),
+ [&password](const IPasswordPtr & pwd) {
+ return pwd->match(password);
+ })) {
+ LogSecureDebug(m_user << " passwords match!");
+ return true;
+ }
+
+ LogSecureDebug("isPasswordReused: No passwords match, " << m_user <<
+ " password not reused.");
+ return false;
+}
+
+void PasswordFile::setPassword(unsigned int passwdType, const std::string &password)
+{
+ if (passwdType == AUTH_PWD_NORMAL) {
+ //replace current password with new one
+ if (password.empty()) {
+ m_passwordCurrent.reset(new NoPassword());
+ m_passwordActive = false;
+ } else {
+ m_passwordCurrent.reset(new SHA256Password(password));
+ //put current password to history
+ m_passwordHistory.push_front(m_passwordCurrent);
+
+ //erase last password if we exceed max history size
+ if (m_passwordHistory.size() > getMaxHistorySize())
+ m_passwordHistory.pop_back();
+
+ m_passwordActive = true;
+ }
+ } else if (passwdType == AUTH_PWD_RECOVERY) {
+ //replace current password with new one
+ if (password.empty()) {
+ m_passwordRecovery.reset(new NoPassword());
+ m_passwordRcvActive = false;
+ } else {
+ m_passwordRecovery.reset(new SHA256Password(password));
+ m_passwordRcvActive = true;
+ }
+ }
+}
+
+bool PasswordFile::checkPassword(unsigned int passwdType, const std::string &password) const
+{
+ switch (passwdType) {
+ case AUTH_PWD_NORMAL: return m_passwordCurrent->match(password);
+ case AUTH_PWD_RECOVERY: return m_passwordRecovery->match(password);
+ default: return false;
+ }
+}
+
+void PasswordFile::setExpireTime(unsigned int expireTime)
+{
+ m_expireTime = expireTime;
+}
+
+unsigned int PasswordFile::getExpireTime() const
+{
+ return m_expireTime;
+}
+
+void PasswordFile::setExpireTimeLeft(time_t expireTimeLeft)
+{
+ m_expireTimeLeft = expireTimeLeft;
+}
+
+unsigned int PasswordFile::getExpireTimeLeft() const
+{
+ if (m_expireTimeLeft != PASSWORD_INFINITE_EXPIRATION_TIME) {
+ time_t timeLeft = m_expireTimeLeft - time(NULL);
+ return (timeLeft < 0) ? 0 : static_cast<unsigned int>(timeLeft);
+ } else {
+ return PASSWORD_API_NO_EXPIRATION;
+ }
+}
+
+bool PasswordFile::checkExpiration() const
+{
+ //return true if expired, else false
+ return ((m_expireTimeLeft != PASSWORD_INFINITE_EXPIRATION_TIME) && (time(NULL) > m_expireTimeLeft));
+}
+
+bool PasswordFile::checkIfAttemptsExceeded() const
+{
+ return ((m_maxAttempt != PASSWORD_INFINITE_ATTEMPT_COUNT) && (m_attempt > m_maxAttempt));
+}
+
+bool PasswordFile::isIgnorePeriod() const
+{
+ TimePoint retryTimerStop = ClockType::now();
+ TimeDiff diff = retryTimerStop - m_retryTimerStart;
+ m_retryTimerStart = retryTimerStop;
+ return (diff.count() < RETRY_TIMEOUT);
+}
+
+bool PasswordFile::isHistoryActive() const
+{
+ return (m_maxHistorySize != 0);
+}
+} //namespace AuthPasswd
#include <policy.h>
namespace {
- void calculateExpiredTime(unsigned int receivedDays, time_t &validSecs)
- {
- validSecs = AuthPasswd::PASSWORD_INFINITE_EXPIRATION_TIME;
-
- //when receivedDays means infinite expiration, return default validSecs value.
- if(receivedDays == AuthPasswd::PASSWORD_INFINITE_EXPIRATION_DAYS)
- return;
-
- time_t curTime = time(NULL);
- validSecs = (curTime + (receivedDays * 86400));
- return;
- }
+void calculateExpiredTime(unsigned int receivedDays, time_t &validSecs)
+{
+ validSecs = AuthPasswd::PASSWORD_INFINITE_EXPIRATION_TIME;
+
+ //when receivedDays means infinite expiration, return default validSecs value.
+ if (receivedDays == AuthPasswd::PASSWORD_INFINITE_EXPIRATION_DAYS)
+ return;
+
+ time_t curTime = time(NULL);
+ validSecs = (curTime + (receivedDays * 86400));
+ return;
+}
} //namespace
-namespace AuthPasswd
+namespace AuthPasswd {
+void PasswordManager::addPassword(unsigned int user)
+{
+ m_pwdFile.insert(PasswordFileMap::value_type(user, PasswordFile(user)));
+}
+
+void PasswordManager::removePassword(unsigned int user)
+{
+ m_pwdFile.erase(user);
+}
+
+void PasswordManager::existPassword(unsigned int user)
{
- void PasswordManager::addPassword(unsigned int user)
- {
- m_pwdFile.insert(PasswordFileMap::value_type(user, PasswordFile(user)));
- }
-
- void PasswordManager::removePassword(unsigned int user)
- {
- m_pwdFile.erase(user);
- }
-
- void PasswordManager::existPassword(unsigned int user)
- {
- PasswordFileMap::iterator itPwd = m_pwdFile.find(user);
- if (itPwd != m_pwdFile.end())
- return;
-
- addPassword(user);
- return;
- }
-
- int PasswordManager::checkPassword(unsigned int passwdType,
- const std::string &challenge,
- unsigned int currentUser,
- unsigned int ¤tAttempt,
- unsigned int &maxAttempt,
- unsigned int &expirationTime)
- {
- LogSecureDebug("Inside checkPassword function.");
-
- existPassword(currentUser);
- PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
-
- if (itPwd->second.isIgnorePeriod()) {
- LogError("Retry timeout occurred.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_RETRY_TIMER;
- }
- if (!itPwd->second.isPasswordActive(passwdType) && !challenge.empty()) {
- LogError("Password not active.");
- return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
- }
-
- switch(passwdType) {
- case AUTH_PWD_NORMAL:
-
- itPwd->second.incrementAttempt();
- itPwd->second.writeAttemptToFile();
-
- currentAttempt = itPwd->second.getAttempt();
- maxAttempt = itPwd->second.getMaxAttempt();
- expirationTime = itPwd->second.getExpireTimeLeft();
-
- if (itPwd->second.checkIfAttemptsExceeded()) {
- LogError("Too many tries.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
- }
- if (!itPwd->second.checkPassword(AUTH_PWD_NORMAL, challenge)) {
- LogError("Wrong password.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
- }
-
- // Password maches and attempt number is fine - time to reset counter.
- itPwd->second.resetAttempt();
- itPwd->second.writeAttemptToFile();
-
- // Password is too old. You must change it before login.
- if (itPwd->second.checkExpiration()) {
- LogError("Password expired.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_EXPIRED;
- }
- break;
-
- case AUTH_PWD_RECOVERY:
- if (!itPwd->second.checkPassword(AUTH_PWD_RECOVERY, challenge)) {
- LogError("Wrong password.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
- }
- break;
-
- default:
- LogError("Not supported password type.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- return AUTH_PASSWD_API_SUCCESS;
- }
-
- int PasswordManager::isPwdValid(unsigned int passwdType, unsigned int currentUser,
- unsigned int ¤tAttempt, unsigned int &maxAttempt,
- unsigned int &expirationTime)
- {
- existPassword(currentUser);
- PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
-
- if (!itPwd->second.isPasswordActive(passwdType)) {
- LogError("Current password not active.");
- return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
- }
-
- switch(passwdType) {
- case AUTH_PWD_NORMAL:
- currentAttempt = itPwd->second.getAttempt();
- maxAttempt = itPwd->second.getMaxAttempt();
- expirationTime = itPwd->second.getExpireTimeLeft();
- break;
-
- case AUTH_PWD_RECOVERY:
- // there are no maxAttempt and expirationTime for recovery password
- currentAttempt = PASSWORD_INFINITE_ATTEMPT_COUNT;
- maxAttempt = PASSWORD_INFINITE_ATTEMPT_COUNT;
- expirationTime = PASSWORD_API_NO_EXPIRATION;
- break;
-
- default:
- LogError("Not supported password type.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- return AUTH_PASSWD_API_SUCCESS;
- }
-
- int PasswordManager::isPwdReused(unsigned int passwdType, const std::string &passwd,
- unsigned int currentUser, bool &isReused)
- {
- existPassword(currentUser);
- PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
-
- isReused = false;
-
- switch(passwdType) {
- case AUTH_PWD_NORMAL:
- // check history, however only if history is active and password is not empty
- if (itPwd->second.isHistoryActive() && !passwd.empty())
- isReused = itPwd->second.isPasswordReused(passwd);
- break;
-
- case AUTH_PWD_RECOVERY:
- break;
-
- default:
- LogError("Not supported password type.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- return AUTH_PASSWD_API_SUCCESS;
- }
-
- int PasswordManager::setPassword(unsigned int passwdType,
- const std::string ¤tPassword,
- const std::string &newPassword,
- unsigned int currentUser)
- {
- LogSecureDebug("curUser = " << currentUser << ", pwdType = " << passwdType <<
- ", curPwd = " << currentPassword << ", newPwd = " << newPassword);
-
- unsigned int receivedDays = PASSWORD_INFINITE_EXPIRATION_DAYS;
- time_t valid_secs = 0;
-
- existPassword(currentUser);
- PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
-
- if (itPwd->second.isIgnorePeriod()) {
- LogError("Retry timeout occured.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_RETRY_TIMER;
- }
-
- // check delivered currentPassword
- // when m_passwordActive flag is false, current password should be empty
- if (!currentPassword.empty() && !itPwd->second.isPasswordActive(passwdType)) {
- LogError("Password not active.");
- return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
- }
-
- switch(passwdType) {
- case AUTH_PWD_NORMAL:
-
- //increment attempt count before checking it against max attempt count
- itPwd->second.incrementAttempt();
- itPwd->second.writeAttemptToFile();
-
- if (itPwd->second.checkIfAttemptsExceeded()) {
- LogError("Too many tries.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
- }
-
- if (!itPwd->second.checkPassword(AUTH_PWD_NORMAL, currentPassword)) {
- LogError("Wrong password.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
- }
-
- //here we are sure that user knows current password - we can reset attempt counter
- itPwd->second.resetAttempt();
- itPwd->second.writeAttemptToFile();
-
- // check history, however only if history is active and new password is not empty
- if (itPwd->second.isHistoryActive() && !newPassword.empty()) {
- if (itPwd->second.isPasswordReused(newPassword)) {
- LogError("Password reused.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_REUSED;
- }
- }
-
- if (!newPassword.empty())
- receivedDays = itPwd->second.getExpireTime();
-
- calculateExpiredTime(receivedDays, valid_secs);
-
- //setting password
- itPwd->second.setPassword(AUTH_PWD_NORMAL, newPassword);
- itPwd->second.setExpireTimeLeft(valid_secs);
- itPwd->second.writeMemoryToFile();
- break;
-
- case AUTH_PWD_RECOVERY:
- if (!itPwd->second.checkPassword(AUTH_PWD_RECOVERY, currentPassword)) {
- LogError("Wrong password.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
- }
- itPwd->second.setPassword(AUTH_PWD_RECOVERY, newPassword);
- itPwd->second.writeMemoryToFile();
- break;
-
- default:
- LogError("Not supported password type.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- return AUTH_PASSWD_API_SUCCESS;
- }
-
- int PasswordManager::setPasswordRecovery(const std::string &curRcvPassword,
- const std::string &newPassword,
- unsigned int currentUser)
- {
- LogSecureDebug("curUser = " << currentUser << ", curPwd = " << curRcvPassword <<
- ", newPwd = " << newPassword);
-
- unsigned int receivedDays = PASSWORD_INFINITE_EXPIRATION_DAYS;
- time_t valid_secs = 0;
-
- existPassword(currentUser);
- PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
-
- if (itPwd->second.isIgnorePeriod()) {
- LogError("Retry timeout occured.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_RETRY_TIMER;
- }
-
- //check if passwords are correct
- if (curRcvPassword.empty() || newPassword.empty()) {
- LogError("Incorrect input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
-
- // current recovery password should be existed.
- if (!itPwd->second.isPasswordActive(AUTH_PWD_RECOVERY)) {
- LogError("Password not active.");
- return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
- }
-
- receivedDays = itPwd->second.getExpireTime();
-
- // don't recovery password if MaxAttempt value is not infinite.
- if (receivedDays != PASSWORD_INFINITE_EXPIRATION_DAYS)
- return AUTH_PASSWD_API_ERROR_RECOVERY_PASSWORD_RESTRICTED;
-
- if (!itPwd->second.checkPassword(AUTH_PWD_RECOVERY, curRcvPassword)) {
- LogError("Wrong password.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
- }
-
- // check history, however only if history is active and new password is not empty
- if (itPwd->second.isHistoryActive()) {
- if (itPwd->second.isPasswordReused(newPassword)) {
- LogError("Password reused.");
- return AUTH_PASSWD_API_ERROR_PASSWORD_REUSED;
- }
- }
-
- calculateExpiredTime(receivedDays, valid_secs);
-
- itPwd->second.resetAttempt();
- itPwd->second.writeAttemptToFile();
-
- //setting password
- itPwd->second.setPassword(AUTH_PWD_NORMAL, newPassword);
- itPwd->second.setExpireTimeLeft(valid_secs);
- itPwd->second.writeMemoryToFile();
-
- return AUTH_PASSWD_API_SUCCESS;
- }
-
- int PasswordManager::resetPassword(unsigned int passwdType,
- const std::string &newPassword,
- unsigned int receivedUser)
- {
- unsigned int receivedDays = PASSWORD_INFINITE_EXPIRATION_DAYS;
- time_t valid_secs = 0;
-
- existPassword(receivedUser);
- PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
-
- switch(passwdType) {
- case AUTH_PWD_NORMAL:
-
- if (!newPassword.empty())
- receivedDays = itPwd->second.getExpireTime();
-
- calculateExpiredTime(receivedDays, valid_secs);
-
- itPwd->second.resetAttempt();
- itPwd->second.writeAttemptToFile();
-
- itPwd->second.setPassword(AUTH_PWD_NORMAL, newPassword);
- itPwd->second.setExpireTimeLeft(valid_secs);
- itPwd->second.writeMemoryToFile();
- break;
-
- case AUTH_PWD_RECOVERY:
- itPwd->second.setPassword(AUTH_PWD_RECOVERY, newPassword);
- itPwd->second.writeMemoryToFile();
- break;
-
- default:
- LogError("Not supported password type.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- return AUTH_PASSWD_API_SUCCESS;
- }
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(user);
- void PasswordManager::setPasswordMaxAttempts(unsigned int receivedUser,
- unsigned int receivedAttempts)
- {
- LogSecureDebug("received_attempts: " << receivedAttempts);
+ if (itPwd != m_pwdFile.end())
+ return;
- existPassword(receivedUser);
- PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
+ addPassword(user);
+ return;
+}
- itPwd->second.setMaxAttempt(receivedAttempts);
- itPwd->second.writeMemoryToFile();
+int PasswordManager::checkPassword(unsigned int passwdType,
+ const std::string &challenge,
+ unsigned int currentUser,
+ unsigned int ¤tAttempt,
+ unsigned int &maxAttempt,
+ unsigned int &expirationTime)
+{
+ LogSecureDebug("Inside checkPassword function.");
+ existPassword(currentUser);
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
+
+ if (itPwd->second.isIgnorePeriod()) {
+ LogError("Retry timeout occurred.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_RETRY_TIMER;
+ }
+
+ if (!itPwd->second.isPasswordActive(passwdType) && !challenge.empty()) {
+ LogError("Password not active.");
+ return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
+ }
+
+ switch (passwdType) {
+ case AUTH_PWD_NORMAL:
+ itPwd->second.incrementAttempt();
+ itPwd->second.writeAttemptToFile();
+ currentAttempt = itPwd->second.getAttempt();
+ maxAttempt = itPwd->second.getMaxAttempt();
+ expirationTime = itPwd->second.getExpireTimeLeft();
+
+ if (itPwd->second.checkIfAttemptsExceeded()) {
+ LogError("Too many tries.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
+ }
+
+ if (!itPwd->second.checkPassword(AUTH_PWD_NORMAL, challenge)) {
+ LogError("Wrong password.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
+ }
+
+ // Password maches and attempt number is fine - time to reset counter.
+ itPwd->second.resetAttempt();
+ itPwd->second.writeAttemptToFile();
+
+ // Password is too old. You must change it before login.
+ if (itPwd->second.checkExpiration()) {
+ LogError("Password expired.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_EXPIRED;
+ }
+
+ break;
+
+ case AUTH_PWD_RECOVERY:
+ if (!itPwd->second.checkPassword(AUTH_PWD_RECOVERY, challenge)) {
+ LogError("Wrong password.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
+ }
+
+ break;
+
+ default:
+ LogError("Not supported password type.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ return AUTH_PASSWD_API_SUCCESS;
+}
+
+int PasswordManager::isPwdValid(unsigned int passwdType, unsigned int currentUser,
+ unsigned int ¤tAttempt, unsigned int &maxAttempt,
+ unsigned int &expirationTime)
+{
+ existPassword(currentUser);
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
+
+ if (!itPwd->second.isPasswordActive(passwdType)) {
+ LogError("Current password not active.");
+ return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
+ }
+
+ switch (passwdType) {
+ case AUTH_PWD_NORMAL:
+ currentAttempt = itPwd->second.getAttempt();
+ maxAttempt = itPwd->second.getMaxAttempt();
+ expirationTime = itPwd->second.getExpireTimeLeft();
+ break;
+
+ case AUTH_PWD_RECOVERY:
+ // there are no maxAttempt and expirationTime for recovery password
+ currentAttempt = PASSWORD_INFINITE_ATTEMPT_COUNT;
+ maxAttempt = PASSWORD_INFINITE_ATTEMPT_COUNT;
+ expirationTime = PASSWORD_API_NO_EXPIRATION;
+ break;
+
+ default:
+ LogError("Not supported password type.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ return AUTH_PASSWD_API_SUCCESS;
+}
+
+int PasswordManager::isPwdReused(unsigned int passwdType, const std::string &passwd,
+ unsigned int currentUser, bool &isReused)
+{
+ existPassword(currentUser);
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
+ isReused = false;
- itPwd->second.resetAttempt();
- itPwd->second.writeAttemptToFile();
- }
+ switch (passwdType) {
+ case AUTH_PWD_NORMAL:
- void PasswordManager::setPasswordValidity(unsigned int receivedUser,
- unsigned int receivedDays)
- {
- LogSecureDebug("received_days: " << receivedDays);
+ // check history, however only if history is active and password is not empty
+ if (itPwd->second.isHistoryActive() && !passwd.empty())
+ isReused = itPwd->second.isPasswordReused(passwd);
- time_t valid_secs = 0;
+ break;
- existPassword(receivedUser);
- PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
+ case AUTH_PWD_RECOVERY:
+ break;
- calculateExpiredTime(receivedDays, valid_secs);
+ default:
+ LogError("Not supported password type.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
- if (itPwd->second.isPasswordActive(AUTH_PWD_NORMAL))
- itPwd->second.setExpireTimeLeft(valid_secs);
+ return AUTH_PASSWD_API_SUCCESS;
+}
- itPwd->second.setExpireTime(receivedDays);
- itPwd->second.writeMemoryToFile();
- }
+int PasswordManager::setPassword(unsigned int passwdType,
+ const std::string ¤tPassword,
+ const std::string &newPassword,
+ unsigned int currentUser)
+{
+ LogSecureDebug("curUser = " << currentUser << ", pwdType = " << passwdType <<
+ ", curPwd = " << currentPassword << ", newPwd = " << newPassword);
+ unsigned int receivedDays = PASSWORD_INFINITE_EXPIRATION_DAYS;
+ time_t valid_secs = 0;
+ existPassword(currentUser);
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
+
+ if (itPwd->second.isIgnorePeriod()) {
+ LogError("Retry timeout occured.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_RETRY_TIMER;
+ }
+
+ // check delivered currentPassword
+ // when m_passwordActive flag is false, current password should be empty
+ if (!currentPassword.empty() && !itPwd->second.isPasswordActive(passwdType)) {
+ LogError("Password not active.");
+ return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
+ }
+
+ switch (passwdType) {
+ case AUTH_PWD_NORMAL:
+ //increment attempt count before checking it against max attempt count
+ itPwd->second.incrementAttempt();
+ itPwd->second.writeAttemptToFile();
+
+ if (itPwd->second.checkIfAttemptsExceeded()) {
+ LogError("Too many tries.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
+ }
+
+ if (!itPwd->second.checkPassword(AUTH_PWD_NORMAL, currentPassword)) {
+ LogError("Wrong password.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
+ }
+
+ //here we are sure that user knows current password - we can reset attempt counter
+ itPwd->second.resetAttempt();
+ itPwd->second.writeAttemptToFile();
+
+ // check history, however only if history is active and new password is not empty
+ if (itPwd->second.isHistoryActive() && !newPassword.empty()) {
+ if (itPwd->second.isPasswordReused(newPassword)) {
+ LogError("Password reused.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_REUSED;
+ }
+ }
+
+ if (!newPassword.empty())
+ receivedDays = itPwd->second.getExpireTime();
+
+ calculateExpiredTime(receivedDays, valid_secs);
+ //setting password
+ itPwd->second.setPassword(AUTH_PWD_NORMAL, newPassword);
+ itPwd->second.setExpireTimeLeft(valid_secs);
+ itPwd->second.writeMemoryToFile();
+ break;
+
+ case AUTH_PWD_RECOVERY:
+ if (!itPwd->second.checkPassword(AUTH_PWD_RECOVERY, currentPassword)) {
+ LogError("Wrong password.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
+ }
+
+ itPwd->second.setPassword(AUTH_PWD_RECOVERY, newPassword);
+ itPwd->second.writeMemoryToFile();
+ break;
+
+ default:
+ LogError("Not supported password type.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ return AUTH_PASSWD_API_SUCCESS;
+}
+
+int PasswordManager::setPasswordRecovery(const std::string &curRcvPassword,
+ const std::string &newPassword,
+ unsigned int currentUser)
+{
+ LogSecureDebug("curUser = " << currentUser << ", curPwd = " << curRcvPassword <<
+ ", newPwd = " << newPassword);
+ unsigned int receivedDays = PASSWORD_INFINITE_EXPIRATION_DAYS;
+ time_t valid_secs = 0;
+ existPassword(currentUser);
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(currentUser);
+
+ if (itPwd->second.isIgnorePeriod()) {
+ LogError("Retry timeout occured.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_RETRY_TIMER;
+ }
+
+ //check if passwords are correct
+ if (curRcvPassword.empty() || newPassword.empty()) {
+ LogError("Incorrect input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ // current recovery password should be existed.
+ if (!itPwd->second.isPasswordActive(AUTH_PWD_RECOVERY)) {
+ LogError("Password not active.");
+ return AUTH_PASSWD_API_ERROR_NO_PASSWORD;
+ }
+
+ receivedDays = itPwd->second.getExpireTime();
+
+ // don't recovery password if MaxAttempt value is not infinite.
+ if (receivedDays != PASSWORD_INFINITE_EXPIRATION_DAYS)
+ return AUTH_PASSWD_API_ERROR_RECOVERY_PASSWORD_RESTRICTED;
+
+ if (!itPwd->second.checkPassword(AUTH_PWD_RECOVERY, curRcvPassword)) {
+ LogError("Wrong password.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH;
+ }
+
+ // check history, however only if history is active and new password is not empty
+ if (itPwd->second.isHistoryActive()) {
+ if (itPwd->second.isPasswordReused(newPassword)) {
+ LogError("Password reused.");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_REUSED;
+ }
+ }
+
+ calculateExpiredTime(receivedDays, valid_secs);
+ itPwd->second.resetAttempt();
+ itPwd->second.writeAttemptToFile();
+ //setting password
+ itPwd->second.setPassword(AUTH_PWD_NORMAL, newPassword);
+ itPwd->second.setExpireTimeLeft(valid_secs);
+ itPwd->second.writeMemoryToFile();
+ return AUTH_PASSWD_API_SUCCESS;
+}
+
+int PasswordManager::resetPassword(unsigned int passwdType,
+ const std::string &newPassword,
+ unsigned int receivedUser)
+{
+ unsigned int receivedDays = PASSWORD_INFINITE_EXPIRATION_DAYS;
+ time_t valid_secs = 0;
+ existPassword(receivedUser);
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
+
+ switch (passwdType) {
+ case AUTH_PWD_NORMAL:
+ if (!newPassword.empty())
+ receivedDays = itPwd->second.getExpireTime();
+
+ calculateExpiredTime(receivedDays, valid_secs);
+ itPwd->second.resetAttempt();
+ itPwd->second.writeAttemptToFile();
+ itPwd->second.setPassword(AUTH_PWD_NORMAL, newPassword);
+ itPwd->second.setExpireTimeLeft(valid_secs);
+ itPwd->second.writeMemoryToFile();
+ break;
+
+ case AUTH_PWD_RECOVERY:
+ itPwd->second.setPassword(AUTH_PWD_RECOVERY, newPassword);
+ itPwd->second.writeMemoryToFile();
+ break;
+
+ default:
+ LogError("Not supported password type.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ return AUTH_PASSWD_API_SUCCESS;
+}
+
+void PasswordManager::setPasswordMaxAttempts(unsigned int receivedUser,
+ unsigned int receivedAttempts)
+{
+ LogSecureDebug("received_attempts: " << receivedAttempts);
+ existPassword(receivedUser);
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
+ itPwd->second.setMaxAttempt(receivedAttempts);
+ itPwd->second.writeMemoryToFile();
+ itPwd->second.resetAttempt();
+ itPwd->second.writeAttemptToFile();
+}
+
+void PasswordManager::setPasswordValidity(unsigned int receivedUser,
+ unsigned int receivedDays)
+{
+ LogSecureDebug("received_days: " << receivedDays);
+ time_t valid_secs = 0;
+ existPassword(receivedUser);
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
+ calculateExpiredTime(receivedDays, valid_secs);
- void PasswordManager::setPasswordHistory(unsigned int receivedUser,
- unsigned int receivedHistory)
- {
- LogSecureDebug("received_historySize: " << receivedHistory);
+ if (itPwd->second.isPasswordActive(AUTH_PWD_NORMAL))
+ itPwd->second.setExpireTimeLeft(valid_secs);
- existPassword(receivedUser);
- PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
+ itPwd->second.setExpireTime(receivedDays);
+ itPwd->second.writeMemoryToFile();
+}
- itPwd->second.setMaxHistorySize(receivedHistory);
- itPwd->second.writeMemoryToFile();
- }
+void PasswordManager::setPasswordHistory(unsigned int receivedUser,
+ unsigned int receivedHistory)
+{
+ LogSecureDebug("received_historySize: " << receivedHistory);
+ existPassword(receivedUser);
+ PasswordFileMap::iterator itPwd = m_pwdFile.find(receivedUser);
+ itPwd->second.setMaxHistorySize(receivedHistory);
+ itPwd->second.writeMemoryToFile();
+}
} //namespace AuthPasswd
GenericSocketService::ServiceDescriptionVector PasswordService::GetServiceDescription()
{
- return ServiceDescriptionVector {
- {SERVICE_SOCKET_PASSWD_CHECK, "*", SOCKET_ID_CHECK},
- {SERVICE_SOCKET_PASSWD_SET, "*", SOCKET_ID_SET},
- {SERVICE_SOCKET_PASSWD_RESET, "*", SOCKET_ID_RESET},
- {SERVICE_SOCKET_PASSWD_POLICY, "*", SOCKET_ID_POLICY}
- };
+ return ServiceDescriptionVector {
+ {SERVICE_SOCKET_PASSWD_CHECK, "*", SOCKET_ID_CHECK},
+ {SERVICE_SOCKET_PASSWD_SET, "*", SOCKET_ID_SET},
+ {SERVICE_SOCKET_PASSWD_RESET, "*", SOCKET_ID_RESET},
+ {SERVICE_SOCKET_PASSWD_POLICY, "*", SOCKET_ID_POLICY}
+ };
}
-void PasswordService::Start() {
- Create();
+void PasswordService::Start()
+{
+ Create();
}
-void PasswordService::Stop() {
- Join();
+void PasswordService::Stop()
+{
+ Join();
}
void PasswordService::accept(const AcceptEvent &event)
{
- LogSecureDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
- << " ConnectionID.counter: " << event.connectionID.counter
- << " ServiceID: " << event.interfaceID);
-
- auto &info = m_connectionInfoMap[event.connectionID.counter];
- info.interfaceID = event.interfaceID;
+ LogSecureDebug("Accept event. ConnectionID.sock: " << event.connectionID.sock
+ << " ConnectionID.counter: " << event.connectionID.counter
+ << " ServiceID: " << event.interfaceID);
+ auto &info = m_connectionInfoMap[event.connectionID.counter];
+ info.interfaceID = event.interfaceID;
}
void PasswordService::write(const WriteEvent &event)
{
- LogSecureDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
- " Size: " << event.size << " Left: " << event.left);
- if (event.left == 0)
- m_serviceManager->Close(event.connectionID);
+ LogSecureDebug("WriteEvent. ConnectionID: " << event.connectionID.sock <<
+ " Size: " << event.size << " Left: " << event.left);
+
+ if (event.left == 0)
+ m_serviceManager->Close(event.connectionID);
}
void PasswordService::process(const ReadEvent &event)
{
- LogSecureDebug("Read event for counter: " << event.connectionID.counter);
- auto &info = m_connectionInfoMap[event.connectionID.counter];
- info.buffer.Push(event.rawBuffer);
+ LogSecureDebug("Read event for counter: " << event.connectionID.counter);
+ auto &info = m_connectionInfoMap[event.connectionID.counter];
+ info.buffer.Push(event.rawBuffer);
- // We can get several requests in one package.
- // Extract and process them all
- while(processOne(event.connectionID, info.buffer, info.interfaceID));
+ // We can get several requests in one package.
+ // Extract and process them all
+ while (processOne(event.connectionID, info.buffer, info.interfaceID));
}
void PasswordService::close(const CloseEvent &event)
{
- LogSecureDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
- m_connectionInfoMap.erase(event.connectionID.counter);
+ LogSecureDebug("CloseEvent. ConnectionID: " << event.connectionID.sock);
+ m_connectionInfoMap.erase(event.connectionID.counter);
}
-int PasswordService::processCheckFunctions(PasswordHdrs hdr, MessageBuffer& buffer,
- unsigned int cur_user, unsigned int &cur_att,
- unsigned int &max_att, unsigned int &exp_time)
+int PasswordService::processCheckFunctions(PasswordHdrs hdr, MessageBuffer &buffer,
+ unsigned int cur_user, unsigned int &cur_att,
+ unsigned int &max_att, unsigned int &exp_time)
{
- int result = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
-
- switch (hdr) {
- case PasswordHdrs::HDR_CHK_PASSWD: {
- unsigned int passwdType = 0;
- std::string challenge;
- Deserialization::Deserialize(buffer, passwdType);
- Deserialization::Deserialize(buffer, challenge);
- result = m_pwdManager.checkPassword(passwdType, challenge, cur_user, cur_att, max_att,
- exp_time);
- break;
- }
-
- case PasswordHdrs::HDR_CHK_PASSWD_STATE: {
- unsigned int passwdType = 0;
- Deserialization::Deserialize(buffer, passwdType);
- result = m_pwdManager.isPwdValid(passwdType, cur_user, cur_att, max_att, exp_time);
- break;
- }
-
- default:
- LogError("Unknown msg header.");
- Throw(Exception::IncorrectHeader);
- }
- return result;
+ int result = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
+
+ switch (hdr) {
+ case PasswordHdrs::HDR_CHK_PASSWD: {
+ unsigned int passwdType = 0;
+ std::string challenge;
+ Deserialization::Deserialize(buffer, passwdType);
+ Deserialization::Deserialize(buffer, challenge);
+ result = m_pwdManager.checkPassword(passwdType, challenge, cur_user, cur_att, max_att,
+ exp_time);
+ break;
+ }
+
+ case PasswordHdrs::HDR_CHK_PASSWD_STATE: {
+ unsigned int passwdType = 0;
+ Deserialization::Deserialize(buffer, passwdType);
+ result = m_pwdManager.isPwdValid(passwdType, cur_user, cur_att, max_att, exp_time);
+ break;
+ }
+
+ default:
+ LogError("Unknown msg header.");
+ Throw(Exception::IncorrectHeader);
+ }
+
+ return result;
}
-int PasswordService::processSetFunctions(PasswordHdrs hdr, MessageBuffer& buffer,
- unsigned int cur_user, bool &isPwdReused)
+int PasswordService::processSetFunctions(PasswordHdrs hdr, MessageBuffer &buffer,
+ unsigned int cur_user, bool &isPwdReused)
{
- int result = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
-
- switch (hdr) {
- case PasswordHdrs::HDR_SET_PASSWD: {
- std::string curPasswd, newPasswd;
- unsigned int passwdType = 0;
- Deserialization::Deserialize(buffer, passwdType);
- Deserialization::Deserialize(buffer, curPasswd);
- Deserialization::Deserialize(buffer, newPasswd);
- result = m_policyManager.checkPolicy(passwdType, curPasswd, newPasswd, cur_user);
- if (result == AUTH_PASSWD_API_SUCCESS)
- result = m_pwdManager.setPassword(passwdType, curPasswd, newPasswd, cur_user);
- break;
- }
-
- case PasswordHdrs::HDR_SET_PASSWD_RECOVERY: {
- std::string curRcvPasswd, newPasswd;
- Deserialization::Deserialize(buffer, curRcvPasswd);
- Deserialization::Deserialize(buffer, newPasswd);
- result = m_policyManager.checkPolicy(AUTH_PWD_NORMAL, curRcvPasswd, newPasswd, cur_user);
- if (result == AUTH_PASSWD_API_SUCCESS)
- result = m_pwdManager.setPasswordRecovery(curRcvPasswd, newPasswd, cur_user);
- break;
- }
-
- case PasswordHdrs::HDR_CHK_PASSWD_REUSED: {
- unsigned int passwdType = 0;
- std::string passwd;
- Deserialization::Deserialize(buffer, passwdType);
- Deserialization::Deserialize(buffer, passwd);
- result = m_pwdManager.isPwdReused(passwdType, passwd, cur_user, isPwdReused);
- break;
- }
-
- default:
- LogError("Unknown msg header.");
- Throw(Exception::IncorrectHeader);
- }
- return result;
+ int result = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
+
+ switch (hdr) {
+ case PasswordHdrs::HDR_SET_PASSWD: {
+ std::string curPasswd, newPasswd;
+ unsigned int passwdType = 0;
+ Deserialization::Deserialize(buffer, passwdType);
+ Deserialization::Deserialize(buffer, curPasswd);
+ Deserialization::Deserialize(buffer, newPasswd);
+ result = m_policyManager.checkPolicy(passwdType, curPasswd, newPasswd, cur_user);
+
+ if (result == AUTH_PASSWD_API_SUCCESS)
+ result = m_pwdManager.setPassword(passwdType, curPasswd, newPasswd, cur_user);
+
+ break;
+ }
+
+ case PasswordHdrs::HDR_SET_PASSWD_RECOVERY: {
+ std::string curRcvPasswd, newPasswd;
+ Deserialization::Deserialize(buffer, curRcvPasswd);
+ Deserialization::Deserialize(buffer, newPasswd);
+ result = m_policyManager.checkPolicy(AUTH_PWD_NORMAL, curRcvPasswd, newPasswd, cur_user);
+
+ if (result == AUTH_PASSWD_API_SUCCESS)
+ result = m_pwdManager.setPasswordRecovery(curRcvPasswd, newPasswd, cur_user);
+
+ break;
+ }
+
+ case PasswordHdrs::HDR_CHK_PASSWD_REUSED: {
+ unsigned int passwdType = 0;
+ std::string passwd;
+ Deserialization::Deserialize(buffer, passwdType);
+ Deserialization::Deserialize(buffer, passwd);
+ result = m_pwdManager.isPwdReused(passwdType, passwd, cur_user, isPwdReused);
+ break;
+ }
+
+ default:
+ LogError("Unknown msg header.");
+ Throw(Exception::IncorrectHeader);
+ }
+
+ return result;
}
-int PasswordService::processResetFunctions(PasswordHdrs hdr, MessageBuffer& buffer)
+int PasswordService::processResetFunctions(PasswordHdrs hdr, MessageBuffer &buffer)
{
- int result = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
-
- std::string newPasswd, emptyStr="";
- unsigned int passwdType = 0;
- uid_t rec_user = 0;
-
- switch (hdr) {
- case PasswordHdrs::HDR_RST_PASSWD:
- Deserialization::Deserialize(buffer, passwdType);
- Deserialization::Deserialize(buffer, rec_user);
- Deserialization::Deserialize(buffer, newPasswd);
- result = m_pwdManager.resetPassword(passwdType, newPasswd, rec_user);
- break;
-
- default:
- LogError("Unknown msg header.");
- Throw(Exception::IncorrectHeader);
- }
- return result;
+ int result = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
+ std::string newPasswd, emptyStr = "";
+ unsigned int passwdType = 0;
+ uid_t rec_user = 0;
+
+ switch (hdr) {
+ case PasswordHdrs::HDR_RST_PASSWD:
+ Deserialization::Deserialize(buffer, passwdType);
+ Deserialization::Deserialize(buffer, rec_user);
+ Deserialization::Deserialize(buffer, newPasswd);
+ result = m_pwdManager.resetPassword(passwdType, newPasswd, rec_user);
+ break;
+
+ default:
+ LogError("Unknown msg header.");
+ Throw(Exception::IncorrectHeader);
+ }
+
+ return result;
}
-int PasswordService::processPolicyFunctions(PasswordHdrs hdr, MessageBuffer& buffer)
+int PasswordService::processPolicyFunctions(PasswordHdrs hdr, MessageBuffer &buffer)
{
- int result = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
-
- switch (hdr) {
- case PasswordHdrs::HDR_SET_PASSWD_POLICY: {
- Policy policy;
-
- Deserialization::Deserialize(buffer, policy.flag);
- Deserialization::Deserialize(buffer, policy.uid);
- Deserialization::Deserialize(buffer, policy.maxAttempts);
- Deserialization::Deserialize(buffer, policy.validPeriod);
- Deserialization::Deserialize(buffer, policy.historySize);
- Deserialization::Deserialize(buffer, policy.minLength);
- Deserialization::Deserialize(buffer, policy.minComplexCharNumber);
- Deserialization::Deserialize(buffer, policy.maxCharOccurrences);
- Deserialization::Deserialize(buffer, policy.maxNumSeqLength);
- Deserialization::Deserialize(buffer, policy.qualityType);
- Deserialization::Deserialize(buffer, policy.pattern);
- Deserialization::Deserialize(buffer, policy.forbiddenPasswds);
-
- result = m_policyManager.setPolicy(policy);
-
- if (result == AUTH_PASSWD_API_SUCCESS) {
- if (policy.isFlagOn(POLICY_MAX_ATTEMPTS))
- m_pwdManager.setPasswordMaxAttempts(policy.uid, policy.maxAttempts);
- if (policy.isFlagOn(POLICY_VALID_PERIOD))
- m_pwdManager.setPasswordValidity(policy.uid, policy.validPeriod);
- if (policy.isFlagOn(POLICY_HISTORY_SIZE))
- m_pwdManager.setPasswordHistory(policy.uid, policy.historySize);
- }
- break;
- }
-
- case PasswordHdrs::HDR_DIS_PASSWD_POLICY: {
- uid_t rec_user = 0;
- Deserialization::Deserialize(buffer, rec_user);
- result = m_policyManager.disablePolicy(rec_user);
- if (result == AUTH_PASSWD_API_SUCCESS) {
- m_pwdManager.setPasswordMaxAttempts(rec_user, PASSWORD_INFINITE_ATTEMPT_COUNT);
- m_pwdManager.setPasswordValidity(rec_user, PASSWORD_INFINITE_EXPIRATION_DAYS);
- m_pwdManager.setPasswordHistory(rec_user, 0);
- }
- break;
- }
-
- default:
- LogError("Unknown msg header.");
- Throw(Exception::IncorrectHeader);
- }
-
- return result;
+ int result = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
+
+ switch (hdr) {
+ case PasswordHdrs::HDR_SET_PASSWD_POLICY: {
+ Policy policy;
+ Deserialization::Deserialize(buffer, policy.flag);
+ Deserialization::Deserialize(buffer, policy.uid);
+ Deserialization::Deserialize(buffer, policy.maxAttempts);
+ Deserialization::Deserialize(buffer, policy.validPeriod);
+ Deserialization::Deserialize(buffer, policy.historySize);
+ Deserialization::Deserialize(buffer, policy.minLength);
+ Deserialization::Deserialize(buffer, policy.minComplexCharNumber);
+ Deserialization::Deserialize(buffer, policy.maxCharOccurrences);
+ Deserialization::Deserialize(buffer, policy.maxNumSeqLength);
+ Deserialization::Deserialize(buffer, policy.qualityType);
+ Deserialization::Deserialize(buffer, policy.pattern);
+ Deserialization::Deserialize(buffer, policy.forbiddenPasswds);
+ result = m_policyManager.setPolicy(policy);
+
+ if (result == AUTH_PASSWD_API_SUCCESS) {
+ if (policy.isFlagOn(POLICY_MAX_ATTEMPTS))
+ m_pwdManager.setPasswordMaxAttempts(policy.uid, policy.maxAttempts);
+
+ if (policy.isFlagOn(POLICY_VALID_PERIOD))
+ m_pwdManager.setPasswordValidity(policy.uid, policy.validPeriod);
+
+ if (policy.isFlagOn(POLICY_HISTORY_SIZE))
+ m_pwdManager.setPasswordHistory(policy.uid, policy.historySize);
+ }
+
+ break;
+ }
+
+ case PasswordHdrs::HDR_DIS_PASSWD_POLICY: {
+ uid_t rec_user = 0;
+ Deserialization::Deserialize(buffer, rec_user);
+ result = m_policyManager.disablePolicy(rec_user);
+
+ if (result == AUTH_PASSWD_API_SUCCESS) {
+ m_pwdManager.setPasswordMaxAttempts(rec_user, PASSWORD_INFINITE_ATTEMPT_COUNT);
+ m_pwdManager.setPasswordValidity(rec_user, PASSWORD_INFINITE_EXPIRATION_DAYS);
+ m_pwdManager.setPasswordHistory(rec_user, 0);
+ }
+
+ break;
+ }
+
+ default:
+ LogError("Unknown msg header.");
+ Throw(Exception::IncorrectHeader);
+ }
+
+ return result;
}
bool PasswordService::processOne(const ConnectionID &conn, MessageBuffer &buffer,
- InterfaceID interfaceID)
+ InterfaceID interfaceID)
{
- LogSecureDebug("Iteration begin");
-
- MessageBuffer sendBuffer;
-
- int retCode = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
- unsigned int cur_user = 0, cur_att = 0, max_att = 0, exp_time = 0;
- bool isPwdReused;
-
- if (!buffer.Ready())
- return false;
-
- Try { //try..catch for MessageBuffer errors, closes connection when exception is thrown
- int tempHdr;
- Deserialization::Deserialize(buffer, tempHdr);
- PasswordHdrs hdr = static_cast<PasswordHdrs>(tempHdr);
-
- try { //try..catch for internal service errors, assigns error code for returning.
- switch (interfaceID) {
- case SOCKET_ID_CHECK:
- if(socket_get_user(conn.sock, cur_user))
- retCode = AUTH_PASSWD_API_ERROR_NO_USER;
- else
- retCode = processCheckFunctions(hdr, buffer, cur_user, cur_att, max_att, exp_time);
- break;
-
- case SOCKET_ID_SET:
- if(socket_get_user(conn.sock, cur_user))
- retCode = AUTH_PASSWD_API_ERROR_NO_USER;
- else
- retCode = processSetFunctions(hdr, buffer, cur_user, isPwdReused);
- break;
-
- case SOCKET_ID_RESET:
- retCode = processResetFunctions(hdr, buffer);
- break;
-
- case SOCKET_ID_POLICY:
- retCode = processPolicyFunctions(hdr, buffer);
- break;
-
- default:
- LogError("Wrong interfaceID.");
- Throw(Exception::IncorrectHeader);
- }
- } catch (PasswordException::Base &e) {
- LogError("Password error: " << e.DumpToString());
- retCode = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
- } catch (std::exception &e) {
- LogError("STD error: " << e.what());
- retCode = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
- }
-
- //everything is OK, send return code and extra data
- Serialization::Serialize(sendBuffer, retCode);
-
- //Returning additional information should occur only when checking functions
- //are called, and under certain return values
- if (interfaceID == SOCKET_ID_CHECK)
- {
- switch(retCode)
- {
- case AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH:
- case AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
- case AUTH_PASSWD_API_ERROR_PASSWORD_EXPIRED:
- case AUTH_PASSWD_API_SUCCESS:
- Serialization::Serialize(sendBuffer, cur_att);
- Serialization::Serialize(sendBuffer, max_att);
- Serialization::Serialize(sendBuffer, exp_time);
- break;
- default:
- break;
- }
- } else if (interfaceID == SOCKET_ID_SET) {
- if (hdr == PasswordHdrs::HDR_CHK_PASSWD_REUSED && retCode == AUTH_PASSWD_API_SUCCESS) {
- Serialization::Serialize(sendBuffer, (int)isPwdReused);
- }
- }
-
- m_serviceManager->Write(conn, sendBuffer.Pop());
- } Catch (MessageBuffer::Exception::Base) {
- LogError("Broken protocol. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- } Catch (PasswordService::Exception::Base) {
- LogError("Incorrect message header. Closing socket.");
- m_serviceManager->Close(conn);
- return false;
- }
-
- return true;
+ LogSecureDebug("Iteration begin");
+ MessageBuffer sendBuffer;
+ int retCode = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
+ unsigned int cur_user = 0, cur_att = 0, max_att = 0, exp_time = 0;
+ bool isPwdReused;
+
+ if (!buffer.Ready())
+ return false;
+
+ Try { //try..catch for MessageBuffer errors, closes connection when exception is thrown
+ int tempHdr;
+ Deserialization::Deserialize(buffer, tempHdr);
+ PasswordHdrs hdr = static_cast<PasswordHdrs>(tempHdr);
+
+ try { //try..catch for internal service errors, assigns error code for returning.
+ switch (interfaceID) {
+ case SOCKET_ID_CHECK:
+ if (socket_get_user(conn.sock, cur_user))
+ retCode = AUTH_PASSWD_API_ERROR_NO_USER;
+ else
+ retCode = processCheckFunctions(hdr, buffer, cur_user, cur_att, max_att, exp_time);
+
+ break;
+
+ case SOCKET_ID_SET:
+ if (socket_get_user(conn.sock, cur_user))
+ retCode = AUTH_PASSWD_API_ERROR_NO_USER;
+ else
+ retCode = processSetFunctions(hdr, buffer, cur_user, isPwdReused);
+
+ break;
+
+ case SOCKET_ID_RESET:
+ retCode = processResetFunctions(hdr, buffer);
+ break;
+
+ case SOCKET_ID_POLICY:
+ retCode = processPolicyFunctions(hdr, buffer);
+ break;
+
+ default:
+ LogError("Wrong interfaceID.");
+ Throw(Exception::IncorrectHeader);
+ }
+ } catch (PasswordException::Base &e) {
+ LogError("Password error: " << e.DumpToString());
+ retCode = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
+ } catch (std::exception &e) {
+ LogError("STD error: " << e.what());
+ retCode = AUTH_PASSWD_API_ERROR_SERVER_ERROR;
+ }
+
+ //everything is OK, send return code and extra data
+ Serialization::Serialize(sendBuffer, retCode);
+
+ //Returning additional information should occur only when checking functions
+ //are called, and under certain return values
+ if (interfaceID == SOCKET_ID_CHECK) {
+ switch (retCode) {
+ case AUTH_PASSWD_API_ERROR_PASSWORD_MISMATCH:
+ case AUTH_PASSWD_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
+ case AUTH_PASSWD_API_ERROR_PASSWORD_EXPIRED:
+ case AUTH_PASSWD_API_SUCCESS:
+ Serialization::Serialize(sendBuffer, cur_att);
+ Serialization::Serialize(sendBuffer, max_att);
+ Serialization::Serialize(sendBuffer, exp_time);
+ break;
+
+ default:
+ break;
+ }
+ } else if (interfaceID == SOCKET_ID_SET) {
+ if (hdr == PasswordHdrs::HDR_CHK_PASSWD_REUSED && retCode == AUTH_PASSWD_API_SUCCESS)
+ Serialization::Serialize(sendBuffer, (int)isPwdReused);
+ }
+
+ m_serviceManager->Write(conn, sendBuffer.Pop());
+ } Catch(MessageBuffer::Exception::Base) {
+ LogError("Broken protocol. Closing socket.");
+ m_serviceManager->Close(conn);
+ return false;
+ } Catch(PasswordService::Exception::Base) {
+ LogError("Incorrect message header. Closing socket.");
+ m_serviceManager->Close(conn);
+ return false;
+ }
+ return true;
}
} // namespace AuthPasswd
#include <password-file-buffer.h>
namespace {
- const std::string POLICY_FILE = "/policy";
- const mode_t FILE_MODE = S_IRUSR | S_IWUSR;
- const unsigned int CURRENT_FILE_VERSION = 1;
+const std::string POLICY_FILE = "/policy";
+const mode_t FILE_MODE = S_IRUSR | S_IWUSR;
+const unsigned int CURRENT_FILE_VERSION = 1;
} // namespace anonymous
-namespace AuthPasswd
+namespace AuthPasswd {
+PolicyFile::PolicyFile(unsigned int user): m_user(user), m_enable(false)
{
- PolicyFile::PolicyFile(unsigned int user): m_user(user), m_enable(false)
- {
- // check if data directory exists
- // if not create it
- std::string userDir = createDir(RW_DATA_DIR, m_user);
-
- if (!dirExists(RW_DATA_DIR)) {
- if(mkdir(RW_DATA_DIR, 0700)) {
- LogError("Failed to create directory for files. Error: " << errnoToString());
- Throw(PasswordException::MakeDirError);
- }
- }
-
- if (!dirExists(userDir.c_str())) {
- if(mkdir(userDir.c_str(), 0700)) {
- LogError("Failed to create directory for files. Error: " << errnoToString());
- Throw(PasswordException::MakeDirError);
- }
- }
-
- preparePolicyFile();
- }
-
- void PolicyFile::resetState()
- {
- m_enable = false;
- m_policy = Policy();
- }
-
- void PolicyFile::preparePolicyFile()
- {
- std::string policyFile = createDir(RW_DATA_DIR, m_user) + POLICY_FILE;
-
- // check if policy file exists
- if (!fileExists(policyFile)) {
- LogSecureDebug("POLICY_DBG not found " << m_user << " policy file. Creating.");
-
- //create file
- writeMemoryToFile();
- } else { //if file exists, load data
- LogSecureDebug("POLICY_DBG found " << m_user << " policy file. Opening.");
- try {
- loadMemoryFromFile();
- } catch (...) {
- LogError("Invalid " << policyFile << " file format");
- resetState();
- writeMemoryToFile();
- }
- }
- }
-
- bool PolicyFile::fileExists(const std::string &filename) const
- {
- struct stat buf;
-
- return ((stat(filename.c_str(), &buf) == 0));
- }
-
- bool PolicyFile::dirExists(const std::string &dirpath) const
- {
- struct stat buf;
-
- return ((stat(dirpath.c_str(), &buf) == 0) && (((buf.st_mode) & S_IFMT) == S_IFDIR));
- }
-
- std::string PolicyFile::createDir(const std::string &dir, unsigned int user) const
- {
- std::string User = std::to_string(user);
- return dir + "/" + User;
- }
-
- void PolicyFile::writeMemoryToFile() const
- {
- PasswordFileBuffer policyBuffer;
-
- LogSecureDebug("User: " << m_user << "Policy: " << m_policy.info());
-
- // serialize policy attributes
- Serialization::Serialize(policyBuffer, CURRENT_FILE_VERSION);
- Serialization::Serialize(policyBuffer, m_enable);
-
- PolicySerializable policys(m_policy);
- policys.Serialize(policyBuffer);
-
- std::string policyFile = createDir(RW_DATA_DIR, m_user) + POLICY_FILE;
- policyBuffer.Save(policyFile);
-
- if (chmod(policyFile.c_str(), FILE_MODE)) {
- LogError("Failed to chmod for " << policyFile << " Error: " << errnoToString());
- Throw(PasswordException::ChmodError);
- }
- }
-
- void PolicyFile::loadMemoryFromFile()
- {
- PasswordFileBuffer policyBuffer;
- std::string policyFile = createDir(RW_DATA_DIR, m_user) + POLICY_FILE;
-
- policyBuffer.Load(policyFile);
-
- // deserialize policy attributes
- unsigned int fileVersion = 0;
- Deserialization::Deserialize(policyBuffer, fileVersion);
- if (fileVersion != CURRENT_FILE_VERSION)
- Throw(PasswordException::FStreamReadError);
-
- Deserialization::Deserialize(policyBuffer, m_enable);
- PolicySerializable policys(policyBuffer);
- m_policy = *(dynamic_cast<Policy *>(&policys));
-
- LogSecureDebug("User: " << m_user << "Policy: " << m_policy.info());
- }
-
- void PolicyFile::enable()
- {
- m_enable = true;
- }
-
- void PolicyFile::disable()
- {
- m_enable = false;
- resetState();
- }
-
- bool PolicyFile::isPolicyActive() const
- {
- return m_enable;
- }
-
- // policy minLength
- bool PolicyFile::checkMinLength(const std::string &password) const
- {
- return (password.size() >= m_policy.minLength);
- }
-
- void PolicyFile::setMinLength(unsigned int minLength)
- {
- m_policy.minLength = minLength;
- }
-
- // policy minComplexCharNumber
- bool PolicyFile::checkMinComplexCharNumber(const std::string &password) const
- {
- unsigned int i = 0, cnt = 0;
- char ch;
-
- if (m_policy.minComplexCharNumber == 0)
- return true;
-
- for (i = 0; i < password.size(); i++) {
- ch = password[i];
- if( ch < 'A' || ( 'Z' < ch && ch < 'a') || 'z' < ch)
- cnt++;
- }
- return (cnt >= m_policy.minComplexCharNumber);
- }
-
- void PolicyFile::setMinComplexCharNumber(unsigned int minComplexCharNumber)
- {
- m_policy.minComplexCharNumber = minComplexCharNumber;
- }
-
- bool PolicyFile::checkMaxCharOccurrences(const std::string &password) const
- {
- std::vector<unsigned int> occurrence(256, 0);
-
- if (m_policy.maxCharOccurrences == 0)
- return true;
-
- for (auto ch : password)
- occurrence[static_cast<unsigned char>(ch)]++;
-
- for (auto item : occurrence)
- if (item > m_policy.maxCharOccurrences)
- return false;
-
- return true;
- }
-
- void PolicyFile::setMaxCharOccurrences(unsigned int maxCharOccurrences)
- {
- m_policy.maxCharOccurrences = maxCharOccurrences;
- }
-
- // policy maxNumSeqLength
- bool PolicyFile::checkMaxNumSeqLength(const std::string &password) const
- {
- char curr_ch = 0, prev_num = 0;
- unsigned int i, num_cnt=0, max_num_seq_len = 0, curr_num_seq_len = 0;
- unsigned int len = password.size();
- int order = -2; // -2: not set, -1 : decreasing, 0 : same, +1: increasing
-
- if (m_policy.maxNumSeqLength == 0)
- return true;
-
- for (i = 0; i < len; i++) {
- curr_ch = password[i];
- if ('0' <= curr_ch && curr_ch <= '9') {
- num_cnt++;
- if (order == -2) { // not set, fist or second char of a sequence
- if (prev_num == 0) { // fist second char
- curr_num_seq_len = 1;
- } else if (curr_ch == prev_num - 1) { // decreasing order
- order = -1;
- curr_num_seq_len = 2;
- } else if (curr_ch == prev_num + 0) { // same order
- order = 0;
- curr_num_seq_len = 2;
- } else if (curr_ch == prev_num + 1) { // increasing order
- order = 1;
- curr_num_seq_len = 2;
- } else { // order restarts again
- if (max_num_seq_len < curr_num_seq_len)
- max_num_seq_len = curr_num_seq_len;
-
- order = -2;
- curr_num_seq_len = 1;
- }
- } else if (curr_ch == prev_num + order) { // order is still working
- curr_num_seq_len++;
- } else { // order changed
- if (max_num_seq_len < curr_num_seq_len)
- max_num_seq_len = curr_num_seq_len;
- order = -2;
- curr_num_seq_len = 1;
- }
- prev_num = curr_ch;
- } else { // order reset
- if (max_num_seq_len < curr_num_seq_len)
- max_num_seq_len = curr_num_seq_len;
-
- order = -2;
- curr_num_seq_len = 0;
- prev_num = 0;
- }
- }
- return max_num_seq_len <= m_policy.maxNumSeqLength;
- }
-
- void PolicyFile::setMaxNumSeqLength(unsigned int maxNumSeqLength)
- {
- m_policy.maxNumSeqLength = maxNumSeqLength;
- }
-
- // policy qalityType
- bool PolicyFile::checkQualityType(const std::string &password) const
- {
- std::string pattern;
-
- switch (m_policy.qualityType) {
- case AUTH_PWD_QUALITY_UNSPECIFIED:
- pattern = REGEX_QUALITY_UNSPECIFIED;
- break;
-
- case AUTH_PWD_QUALITY_SOMETHING:
- pattern = REGEX_QUALITY_SOMETHING;
- break;
-
- case AUTH_PWD_QUALITY_NUMERIC:
- pattern = REGEX_QUALITY_NUMERIC;
- break;
-
- case AUTH_PWD_QUALITY_ALPHABETIC:
- pattern = REGEX_QUALITY_ALPHABETIC;
- break;
-
- case AUTH_PWD_QUALITY_ALPHANUMERIC:
- pattern = REGEX_QUALITY_ALPHANUMERIC;
- break;
-
- default:
- return false;
- }
-
- regex_t re;
- if (regcomp(&re, pattern.c_str(), REG_EXTENDED|REG_NEWLINE) != 0)
- return false;
- return (regexec(&re, password.c_str(), 0, NULL, 0) == 0);
- }
-
- void PolicyFile::setQualityType(unsigned int qualityType)
- {
- m_policy.qualityType = qualityType;
- }
-
- // policy pattern
- bool PolicyFile::isValidPattern(const std::string &pattern) const
- {
- if (pattern.empty())
- return true;
-
- regex_t re;
- return (regcomp(&re, pattern.c_str(), REG_EXTENDED|REG_NEWLINE) == 0);
- }
-
- bool PolicyFile::checkPattern(const std::string &password) const
- {
- if (m_policy.pattern.empty())
- return true;
-
- regex_t re;
- if (regcomp(&re, m_policy.pattern.c_str(), REG_EXTENDED|REG_NEWLINE) != 0)
- return false;
-
- return (regexec(&re, password.c_str(), 0, NULL, 0) == 0);
- }
-
- void PolicyFile::setPattern(const std::string &pattern)
- {
- m_policy.pattern = pattern;
- }
-
- // policy forbiddenPasswds
- bool PolicyFile::checkForbiddenPasswds(const std::string &password) const
- {
- return password.empty() || m_policy.forbiddenPasswds.count(password) == 0;
- }
-
- void PolicyFile::setForbiddenPasswds(std::set<std::string> forbiddenPasswds)
- {
- for (auto &passwd : forbiddenPasswds) {
- if (!passwd.empty())
- m_policy.forbiddenPasswds.insert(passwd);
- }
- }
+ // check if data directory exists
+ // if not create it
+ std::string userDir = createDir(RW_DATA_DIR, m_user);
+
+ if (!dirExists(RW_DATA_DIR)) {
+ if (mkdir(RW_DATA_DIR, 0700)) {
+ LogError("Failed to create directory for files. Error: " << errnoToString());
+ Throw(PasswordException::MakeDirError);
+ }
+ }
+
+ if (!dirExists(userDir.c_str())) {
+ if (mkdir(userDir.c_str(), 0700)) {
+ LogError("Failed to create directory for files. Error: " << errnoToString());
+ Throw(PasswordException::MakeDirError);
+ }
+ }
+
+ preparePolicyFile();
+}
+
+void PolicyFile::resetState()
+{
+ m_enable = false;
+ m_policy = Policy();
+}
+
+void PolicyFile::preparePolicyFile()
+{
+ std::string policyFile = createDir(RW_DATA_DIR, m_user) + POLICY_FILE;
+
+ // check if policy file exists
+ if (!fileExists(policyFile)) {
+ LogSecureDebug("POLICY_DBG not found " << m_user << " policy file. Creating.");
+ //create file
+ writeMemoryToFile();
+ } else { //if file exists, load data
+ LogSecureDebug("POLICY_DBG found " << m_user << " policy file. Opening.");
+
+ try {
+ loadMemoryFromFile();
+ } catch (...) {
+ LogError("Invalid " << policyFile << " file format");
+ resetState();
+ writeMemoryToFile();
+ }
+ }
+}
+
+bool PolicyFile::fileExists(const std::string &filename) const
+{
+ struct stat buf;
+ return ((stat(filename.c_str(), &buf) == 0));
+}
+
+bool PolicyFile::dirExists(const std::string &dirpath) const
+{
+ struct stat buf;
+ return ((stat(dirpath.c_str(), &buf) == 0) && (((buf.st_mode) & S_IFMT) == S_IFDIR));
+}
+
+std::string PolicyFile::createDir(const std::string &dir, unsigned int user) const
+{
+ std::string User = std::to_string(user);
+ return dir + "/" + User;
+}
+
+void PolicyFile::writeMemoryToFile() const
+{
+ PasswordFileBuffer policyBuffer;
+ LogSecureDebug("User: " << m_user << "Policy: " << m_policy.info());
+ // serialize policy attributes
+ Serialization::Serialize(policyBuffer, CURRENT_FILE_VERSION);
+ Serialization::Serialize(policyBuffer, m_enable);
+ PolicySerializable policys(m_policy);
+ policys.Serialize(policyBuffer);
+ std::string policyFile = createDir(RW_DATA_DIR, m_user) + POLICY_FILE;
+ policyBuffer.Save(policyFile);
+
+ if (chmod(policyFile.c_str(), FILE_MODE)) {
+ LogError("Failed to chmod for " << policyFile << " Error: " << errnoToString());
+ Throw(PasswordException::ChmodError);
+ }
+}
+
+void PolicyFile::loadMemoryFromFile()
+{
+ PasswordFileBuffer policyBuffer;
+ std::string policyFile = createDir(RW_DATA_DIR, m_user) + POLICY_FILE;
+ policyBuffer.Load(policyFile);
+ // deserialize policy attributes
+ unsigned int fileVersion = 0;
+ Deserialization::Deserialize(policyBuffer, fileVersion);
+
+ if (fileVersion != CURRENT_FILE_VERSION)
+ Throw(PasswordException::FStreamReadError);
+
+ Deserialization::Deserialize(policyBuffer, m_enable);
+ PolicySerializable policys(policyBuffer);
+ m_policy = *(dynamic_cast<Policy *>(&policys));
+ LogSecureDebug("User: " << m_user << "Policy: " << m_policy.info());
+}
+
+void PolicyFile::enable()
+{
+ m_enable = true;
+}
+
+void PolicyFile::disable()
+{
+ m_enable = false;
+ resetState();
+}
+
+bool PolicyFile::isPolicyActive() const
+{
+ return m_enable;
+}
+
+// policy minLength
+bool PolicyFile::checkMinLength(const std::string &password) const
+{
+ return (password.size() >= m_policy.minLength);
+}
+
+void PolicyFile::setMinLength(unsigned int minLength)
+{
+ m_policy.minLength = minLength;
+}
+
+// policy minComplexCharNumber
+bool PolicyFile::checkMinComplexCharNumber(const std::string &password) const
+{
+ unsigned int i = 0, cnt = 0;
+ char ch;
+
+ if (m_policy.minComplexCharNumber == 0)
+ return true;
+
+ for (i = 0; i < password.size(); i++) {
+ ch = password[i];
+
+ if (ch < 'A' || ('Z' < ch && ch < 'a') || 'z' < ch)
+ cnt++;
+ }
+
+ return (cnt >= m_policy.minComplexCharNumber);
+}
+
+void PolicyFile::setMinComplexCharNumber(unsigned int minComplexCharNumber)
+{
+ m_policy.minComplexCharNumber = minComplexCharNumber;
+}
+
+bool PolicyFile::checkMaxCharOccurrences(const std::string &password) const
+{
+ std::vector<unsigned int> occurrence(256, 0);
+
+ if (m_policy.maxCharOccurrences == 0)
+ return true;
+
+ for (auto ch : password)
+ occurrence[static_cast<unsigned char>(ch)]++;
+
+ for (auto item : occurrence)
+ if (item > m_policy.maxCharOccurrences)
+ return false;
+
+ return true;
+}
+
+void PolicyFile::setMaxCharOccurrences(unsigned int maxCharOccurrences)
+{
+ m_policy.maxCharOccurrences = maxCharOccurrences;
+}
+
+// policy maxNumSeqLength
+bool PolicyFile::checkMaxNumSeqLength(const std::string &password) const
+{
+ char curr_ch = 0, prev_num = 0;
+ unsigned int i, num_cnt = 0, max_num_seq_len = 0, curr_num_seq_len = 0;
+ unsigned int len = password.size();
+ int order = -2; // -2: not set, -1 : decreasing, 0 : same, +1: increasing
+
+ if (m_policy.maxNumSeqLength == 0)
+ return true;
+
+ for (i = 0; i < len; i++) {
+ curr_ch = password[i];
+
+ if ('0' <= curr_ch && curr_ch <= '9') {
+ num_cnt++;
+
+ if (order == -2) { // not set, fist or second char of a sequence
+ if (prev_num == 0) // fist second char
+ curr_num_seq_len = 1;
+ else if (curr_ch == prev_num - 1) { // decreasing order
+ order = -1;
+ curr_num_seq_len = 2;
+ } else if (curr_ch == prev_num + 0) { // same order
+ order = 0;
+ curr_num_seq_len = 2;
+ } else if (curr_ch == prev_num + 1) { // increasing order
+ order = 1;
+ curr_num_seq_len = 2;
+ } else { // order restarts again
+ if (max_num_seq_len < curr_num_seq_len)
+ max_num_seq_len = curr_num_seq_len;
+
+ order = -2;
+ curr_num_seq_len = 1;
+ }
+ } else if (curr_ch == prev_num + order) // order is still working
+ curr_num_seq_len++;
+ else { // order changed
+ if (max_num_seq_len < curr_num_seq_len)
+ max_num_seq_len = curr_num_seq_len;
+
+ order = -2;
+ curr_num_seq_len = 1;
+ }
+
+ prev_num = curr_ch;
+ } else { // order reset
+ if (max_num_seq_len < curr_num_seq_len)
+ max_num_seq_len = curr_num_seq_len;
+
+ order = -2;
+ curr_num_seq_len = 0;
+ prev_num = 0;
+ }
+ }
+
+ return max_num_seq_len <= m_policy.maxNumSeqLength;
+}
+
+void PolicyFile::setMaxNumSeqLength(unsigned int maxNumSeqLength)
+{
+ m_policy.maxNumSeqLength = maxNumSeqLength;
+}
+
+// policy qalityType
+bool PolicyFile::checkQualityType(const std::string &password) const
+{
+ std::string pattern;
+
+ switch (m_policy.qualityType) {
+ case AUTH_PWD_QUALITY_UNSPECIFIED:
+ pattern = REGEX_QUALITY_UNSPECIFIED;
+ break;
+
+ case AUTH_PWD_QUALITY_SOMETHING:
+ pattern = REGEX_QUALITY_SOMETHING;
+ break;
+
+ case AUTH_PWD_QUALITY_NUMERIC:
+ pattern = REGEX_QUALITY_NUMERIC;
+ break;
+
+ case AUTH_PWD_QUALITY_ALPHABETIC:
+ pattern = REGEX_QUALITY_ALPHABETIC;
+ break;
+
+ case AUTH_PWD_QUALITY_ALPHANUMERIC:
+ pattern = REGEX_QUALITY_ALPHANUMERIC;
+ break;
+
+ default:
+ return false;
+ }
+
+ regex_t re;
+
+ if (regcomp(&re, pattern.c_str(), REG_EXTENDED | REG_NEWLINE) != 0)
+ return false;
+
+ return (regexec(&re, password.c_str(), 0, NULL, 0) == 0);
+}
+
+void PolicyFile::setQualityType(unsigned int qualityType)
+{
+ m_policy.qualityType = qualityType;
+}
+
+// policy pattern
+bool PolicyFile::isValidPattern(const std::string &pattern) const
+{
+ if (pattern.empty())
+ return true;
+
+ regex_t re;
+ return (regcomp(&re, pattern.c_str(), REG_EXTENDED | REG_NEWLINE) == 0);
+}
+
+bool PolicyFile::checkPattern(const std::string &password) const
+{
+ if (m_policy.pattern.empty())
+ return true;
+
+ regex_t re;
+
+ if (regcomp(&re, m_policy.pattern.c_str(), REG_EXTENDED | REG_NEWLINE) != 0)
+ return false;
+
+ return (regexec(&re, password.c_str(), 0, NULL, 0) == 0);
+}
+
+void PolicyFile::setPattern(const std::string &pattern)
+{
+ m_policy.pattern = pattern;
+}
+
+// policy forbiddenPasswds
+bool PolicyFile::checkForbiddenPasswds(const std::string &password) const
+{
+ return password.empty() || m_policy.forbiddenPasswds.count(password) == 0;
+}
+
+void PolicyFile::setForbiddenPasswds(std::set<std::string> forbiddenPasswds)
+{
+ for (auto &passwd : forbiddenPasswds) {
+ if (!passwd.empty())
+ m_policy.forbiddenPasswds.insert(passwd);
+ }
+}
} //namespace AuthPasswd
#include <auth-passwd-policy-types.h>
#include <auth-passwd-error.h>
-namespace AuthPasswd
+namespace AuthPasswd {
+void PolicyManager::addPolicy(unsigned int user)
{
- void PolicyManager::addPolicy(unsigned int user)
- {
- m_policyFile.insert(PolicyFileMap::value_type(user, PolicyFile(user)));
- }
-
- void PolicyManager::removePolicy(unsigned int user)
- {
- m_policyFile.erase(user);
- }
-
- void PolicyManager::existPolicy(unsigned int user)
- {
- PolicyFileMap::iterator itPwd = m_policyFile.find(user);
- if (itPwd != m_policyFile.end())
- return;
-
- addPolicy(user);
- return;
- }
-
- int PolicyManager::checkPolicy(unsigned int passwdType,
- const std::string ¤tPassword,
- const std::string &newPassword,
- unsigned int user)
- {
- LogSecureDebug("Inside checkPolicy function.");
-
- // check if passwords are correct
- if (currentPassword.size() > MAX_PASSWORD_LEN) {
- LogError("Current password length failed.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- if (newPassword.size() > MAX_PASSWORD_LEN) {
- LogError("New password length failed.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
-
- existPolicy(user);
- PolicyFileMap::iterator itPolicy = m_policyFile.find(user);
-
- if (!itPolicy->second.isPolicyActive() || (passwdType != AUTH_PWD_NORMAL))
- return AUTH_PASSWD_API_SUCCESS;
-
- if (!itPolicy->second.checkMinLength(newPassword)) {
- LogError("new passwd's minLength is invalid");
- return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
- }
- if (!itPolicy->second.checkMinComplexCharNumber(newPassword)) {
- LogError("new passwd's minComplexCharNumber is invalid");
- return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
- }
- if (!itPolicy->second.checkMaxCharOccurrences(newPassword)) {
- LogError("new passwd's maxCharOccurrences is invalid");
- return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
- }
- if (!itPolicy->second.checkMaxNumSeqLength(newPassword)) {
- LogError("new passwd's maxNumSeqLength is invalid");
- return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
- }
- if (!itPolicy->second.checkQualityType(newPassword)) {
- LogError("new passwd's qualityType is invalid");
- return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
- }
- if (!itPolicy->second.checkPattern(newPassword)) {
- LogError("new passwd's pattern is invalid");
- return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
- }
- if (!itPolicy->second.checkForbiddenPasswds(newPassword)) {
- LogError("new passwd is forbiddenPasswd");
- return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
- }
-
- return AUTH_PASSWD_API_SUCCESS;
- }
-
- int PolicyManager::setPolicy(Policy policy)
- {
- LogSecureDebug("Inside setPolicy function.");
-
- existPolicy(policy.uid);
- PolicyFileMap::iterator itPolicy = m_policyFile.find(policy.uid);
-
- // check if policies are correct
- for (int i = POLICY_TYPE_FIRST ; i < POLICY_TYPE_LAST+1 ; i++) {
- if (!policy.isFlagOn(static_cast<password_policy_type>(i)))
- continue;
-
- switch (i) {
- case POLICY_MAX_ATTEMPTS:
- break;
-
- case POLICY_VALID_PERIOD: {
- time_t curTime = time(NULL);
- if (policy.validPeriod > ((UINT_MAX - curTime) / 86400)) {
- LogError("Incorrect input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- break;
- }
-
- case POLICY_HISTORY_SIZE:
- if (policy.historySize > MAX_PASSWORD_HISTORY) {
- LogError("Incorrect input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- break;
-
- case POLICY_MIN_LENGTH:
- if (policy.minLength > MAX_PASSWORD_LEN) {
- LogError("Incorrect input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- break;
-
- case POLICY_MIN_COMPLEX_CHAR_NUMBER:
- if (policy.minComplexCharNumber > MAX_PASSWORD_LEN) {
- LogError("Incorrect input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- break;
-
- case POLICY_MAX_CHAR_OCCURRENCES:
- if (policy.maxCharOccurrences > MAX_PASSWORD_LEN) {
- LogError("Incorrect input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- break;
-
- case POLICY_MAX_NUMERIC_SEQ_LENGTH:
- if (policy.maxNumSeqLength > MAX_PASSWORD_LEN) {
- LogError("Incorrect input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- break;
-
- case POLICY_QUALITY_TYPE:
- if (policy.qualityType > AUTH_PWD_QUALITY_LAST) {
- LogError("Incorrect input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- break;
-
- case POLICY_PATTERN:
- if (!itPolicy->second.isValidPattern(policy.pattern)) {
- LogError("Incorrect input param.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- break;
-
- case POLICY_FORBIDDEN_PASSWDS:
- break;
-
- default:
- LogError("Not supported policy type.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- }
-
- // update policies
- for (int i = POLICY_TYPE_FIRST ; i < POLICY_TYPE_LAST+1 ; i++) {
- if (!policy.isFlagOn(static_cast<password_policy_type>(i)))
- continue;
-
- switch (i) {
- case POLICY_MAX_ATTEMPTS:
- LogSecureDebug("maxAttempts: " << policy.maxAttempts);
- break;
-
- case POLICY_VALID_PERIOD:
- LogSecureDebug("validPeriod: " << policy.validPeriod);
- break;
-
- case POLICY_HISTORY_SIZE:
- LogSecureDebug("historySize: " << policy.historySize);
- break;
-
- case POLICY_MIN_LENGTH:
- LogSecureDebug("minLength: " << policy.minLength);
- itPolicy->second.setMinLength(policy.minLength);
- break;
-
- case POLICY_MIN_COMPLEX_CHAR_NUMBER:
- LogSecureDebug("minComplexCharNumber: " << policy.minComplexCharNumber);
- itPolicy->second.setMinComplexCharNumber(policy.minComplexCharNumber);
- break;
-
- case POLICY_MAX_CHAR_OCCURRENCES:
- LogSecureDebug("maxCharOccurrences: " << policy.maxCharOccurrences);
- itPolicy->second.setMaxCharOccurrences(policy.maxCharOccurrences);
- break;
-
- case POLICY_MAX_NUMERIC_SEQ_LENGTH:
- LogSecureDebug("maxNumSeqLength: " << policy.maxNumSeqLength);
- itPolicy->second.setMaxNumSeqLength(policy.maxNumSeqLength);
- break;
-
- case POLICY_QUALITY_TYPE:
- LogSecureDebug("qualityType: " << policy.qualityType);
- itPolicy->second.setQualityType(policy.qualityType);
- break;
-
- case POLICY_PATTERN:
- LogSecureDebug("pattern: " << policy.pattern);
- itPolicy->second.setPattern(policy.pattern);
- break;
-
- case POLICY_FORBIDDEN_PASSWDS:
- LogSecureDebug("forbiddenPasswds number: " << policy.forbiddenPasswds.size());
- itPolicy->second.setForbiddenPasswds(policy.forbiddenPasswds);
- break;
-
- default:
- LogError("Not supported policy type.");
- return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
- }
- }
-
- itPolicy->second.enable();
- itPolicy->second.writeMemoryToFile();
-
- return AUTH_PASSWD_API_SUCCESS;
- }
-
- int PolicyManager::disablePolicy(unsigned int user)
- {
- LogSecureDebug("Inside disablePolicy function.");
-
- existPolicy(user);
- PolicyFileMap::iterator itPolicy = m_policyFile.find(user);
-
- itPolicy->second.disable();
- itPolicy->second.writeMemoryToFile();
-
- return AUTH_PASSWD_API_SUCCESS;
- }
+ m_policyFile.insert(PolicyFileMap::value_type(user, PolicyFile(user)));
+}
+
+void PolicyManager::removePolicy(unsigned int user)
+{
+ m_policyFile.erase(user);
+}
+
+void PolicyManager::existPolicy(unsigned int user)
+{
+ PolicyFileMap::iterator itPwd = m_policyFile.find(user);
+
+ if (itPwd != m_policyFile.end())
+ return;
+
+ addPolicy(user);
+ return;
+}
+
+int PolicyManager::checkPolicy(unsigned int passwdType,
+ const std::string ¤tPassword,
+ const std::string &newPassword,
+ unsigned int user)
+{
+ LogSecureDebug("Inside checkPolicy function.");
+
+ // check if passwords are correct
+ if (currentPassword.size() > MAX_PASSWORD_LEN) {
+ LogError("Current password length failed.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ if (newPassword.size() > MAX_PASSWORD_LEN) {
+ LogError("New password length failed.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ existPolicy(user);
+ PolicyFileMap::iterator itPolicy = m_policyFile.find(user);
+
+ if (!itPolicy->second.isPolicyActive() || (passwdType != AUTH_PWD_NORMAL))
+ return AUTH_PASSWD_API_SUCCESS;
+
+ if (!itPolicy->second.checkMinLength(newPassword)) {
+ LogError("new passwd's minLength is invalid");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
+ }
+
+ if (!itPolicy->second.checkMinComplexCharNumber(newPassword)) {
+ LogError("new passwd's minComplexCharNumber is invalid");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
+ }
+
+ if (!itPolicy->second.checkMaxCharOccurrences(newPassword)) {
+ LogError("new passwd's maxCharOccurrences is invalid");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
+ }
+
+ if (!itPolicy->second.checkMaxNumSeqLength(newPassword)) {
+ LogError("new passwd's maxNumSeqLength is invalid");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
+ }
+
+ if (!itPolicy->second.checkQualityType(newPassword)) {
+ LogError("new passwd's qualityType is invalid");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
+ }
+
+ if (!itPolicy->second.checkPattern(newPassword)) {
+ LogError("new passwd's pattern is invalid");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
+ }
+
+ if (!itPolicy->second.checkForbiddenPasswds(newPassword)) {
+ LogError("new passwd is forbiddenPasswd");
+ return AUTH_PASSWD_API_ERROR_PASSWORD_INVALID;
+ }
+
+ return AUTH_PASSWD_API_SUCCESS;
+}
+
+int PolicyManager::setPolicy(Policy policy)
+{
+ LogSecureDebug("Inside setPolicy function.");
+ existPolicy(policy.uid);
+ PolicyFileMap::iterator itPolicy = m_policyFile.find(policy.uid);
+
+ // check if policies are correct
+ for (int i = POLICY_TYPE_FIRST ; i < POLICY_TYPE_LAST + 1 ; i++) {
+ if (!policy.isFlagOn(static_cast<password_policy_type>(i)))
+ continue;
+
+ switch (i) {
+ case POLICY_MAX_ATTEMPTS:
+ break;
+
+ case POLICY_VALID_PERIOD: {
+ time_t curTime = time(NULL);
+
+ if (policy.validPeriod > ((UINT_MAX - curTime) / 86400)) {
+ LogError("Incorrect input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ break;
+ }
+
+ case POLICY_HISTORY_SIZE:
+ if (policy.historySize > MAX_PASSWORD_HISTORY) {
+ LogError("Incorrect input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ break;
+
+ case POLICY_MIN_LENGTH:
+ if (policy.minLength > MAX_PASSWORD_LEN) {
+ LogError("Incorrect input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ break;
+
+ case POLICY_MIN_COMPLEX_CHAR_NUMBER:
+ if (policy.minComplexCharNumber > MAX_PASSWORD_LEN) {
+ LogError("Incorrect input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ break;
+
+ case POLICY_MAX_CHAR_OCCURRENCES:
+ if (policy.maxCharOccurrences > MAX_PASSWORD_LEN) {
+ LogError("Incorrect input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ break;
+
+ case POLICY_MAX_NUMERIC_SEQ_LENGTH:
+ if (policy.maxNumSeqLength > MAX_PASSWORD_LEN) {
+ LogError("Incorrect input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ break;
+
+ case POLICY_QUALITY_TYPE:
+ if (policy.qualityType > AUTH_PWD_QUALITY_LAST) {
+ LogError("Incorrect input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ break;
+
+ case POLICY_PATTERN:
+ if (!itPolicy->second.isValidPattern(policy.pattern)) {
+ LogError("Incorrect input param.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+
+ break;
+
+ case POLICY_FORBIDDEN_PASSWDS:
+ break;
+
+ default:
+ LogError("Not supported policy type.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+ }
+
+ // update policies
+ for (int i = POLICY_TYPE_FIRST ; i < POLICY_TYPE_LAST + 1 ; i++) {
+ if (!policy.isFlagOn(static_cast<password_policy_type>(i)))
+ continue;
+
+ switch (i) {
+ case POLICY_MAX_ATTEMPTS:
+ LogSecureDebug("maxAttempts: " << policy.maxAttempts);
+ break;
+
+ case POLICY_VALID_PERIOD:
+ LogSecureDebug("validPeriod: " << policy.validPeriod);
+ break;
+
+ case POLICY_HISTORY_SIZE:
+ LogSecureDebug("historySize: " << policy.historySize);
+ break;
+
+ case POLICY_MIN_LENGTH:
+ LogSecureDebug("minLength: " << policy.minLength);
+ itPolicy->second.setMinLength(policy.minLength);
+ break;
+
+ case POLICY_MIN_COMPLEX_CHAR_NUMBER:
+ LogSecureDebug("minComplexCharNumber: " << policy.minComplexCharNumber);
+ itPolicy->second.setMinComplexCharNumber(policy.minComplexCharNumber);
+ break;
+
+ case POLICY_MAX_CHAR_OCCURRENCES:
+ LogSecureDebug("maxCharOccurrences: " << policy.maxCharOccurrences);
+ itPolicy->second.setMaxCharOccurrences(policy.maxCharOccurrences);
+ break;
+
+ case POLICY_MAX_NUMERIC_SEQ_LENGTH:
+ LogSecureDebug("maxNumSeqLength: " << policy.maxNumSeqLength);
+ itPolicy->second.setMaxNumSeqLength(policy.maxNumSeqLength);
+ break;
+
+ case POLICY_QUALITY_TYPE:
+ LogSecureDebug("qualityType: " << policy.qualityType);
+ itPolicy->second.setQualityType(policy.qualityType);
+ break;
+
+ case POLICY_PATTERN:
+ LogSecureDebug("pattern: " << policy.pattern);
+ itPolicy->second.setPattern(policy.pattern);
+ break;
+
+ case POLICY_FORBIDDEN_PASSWDS:
+ LogSecureDebug("forbiddenPasswds number: " << policy.forbiddenPasswds.size());
+ itPolicy->second.setForbiddenPasswds(policy.forbiddenPasswds);
+ break;
+
+ default:
+ LogError("Not supported policy type.");
+ return AUTH_PASSWD_API_ERROR_INPUT_PARAM;
+ }
+ }
+
+ itPolicy->second.enable();
+ itPolicy->second.writeMemoryToFile();
+ return AUTH_PASSWD_API_SUCCESS;
+}
+
+int PolicyManager::disablePolicy(unsigned int user)
+{
+ LogSecureDebug("Inside disablePolicy function.");
+ existPolicy(user);
+ PolicyFileMap::iterator itPolicy = m_policyFile.find(user);
+ itPolicy->second.disable();
+ itPolicy->second.writeMemoryToFile();
+ return AUTH_PASSWD_API_SUCCESS;
+}
} //namespace AuthPasswd