Replace time(NULL) with monotonic clock usage 82/200882/3
authorTomasz Swierczek <t.swierczek@samsung.com>
Tue, 5 Mar 2019 09:34:36 +0000 (10:34 +0100)
committerKrzysztof Jackiewicz <k.jackiewicz@samsung.com>
Mon, 11 Mar 2019 16:59:23 +0000 (16:59 +0000)
Calculating timeout for socket connections should
use monotonic clock.

Change-Id: If9c3d573b70d1faa1cf46b9215048a5853abbaaa

src/manager/main/socket-manager.cpp

index 60c7c77..f3f6e3f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
+ *  Copyright (c) 2000 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -68,6 +68,16 @@ int getCredentialsFromSocket(int sock, CKM::Credentials &cred)
        return 0;
 }
 
+time_t monotonicNow() {
+       struct timespec now;
+       if (clock_gettime(CLOCK_MONOTONIC_RAW, &now) == -1) {
+               int err = errno;
+               LogError("Can't access monotonic clock, error: " <<  CKM::GetErrnoString(err));
+               return 0;
+       }
+       return now.tv_sec;
+}
+
 } // namespace anonymous
 
 namespace CKM {
@@ -154,7 +164,7 @@ SocketManager::CreateDefaultReadSocketDescription(int sock, bool timeout)
        desc.counter = ++m_counter;
 
        if (timeout) {
-               desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+               desc.timeout = monotonicNow() + SOCKET_TIMEOUT;
                Timeout tm;
                tm.time = desc.timeout;
                tm.sock = sock;
@@ -323,7 +333,7 @@ void SocketManager::ReadyForRead(int sock)
        event.rawBuffer.resize(4096);
 
        auto &desc = m_socketDescriptionVector[sock];
-       desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+       desc.timeout = monotonicNow() + SOCKET_TIMEOUT;
 
        ssize_t size = read(sock, &event.rawBuffer[0], 4096);
 
@@ -379,7 +389,7 @@ void SocketManager::ReadyForWrite(int sock)
 
        desc.rawBuffer.erase(desc.rawBuffer.begin(), desc.rawBuffer.begin() + result);
 
-       desc.timeout = time(NULL) + SOCKET_TIMEOUT;
+       desc.timeout = monotonicNow() + SOCKET_TIMEOUT;
 
        if (desc.rawBuffer.empty())
                FD_CLR(sock, &m_writeSet);
@@ -434,7 +444,7 @@ void SocketManager::MainLoop()
                        LogDebug("No usaable timeout found.");
                        ptrTimeout = NULL; // select will wait without timeout
                } else {
-                       time_t currentTime = time(NULL);
+                       time_t currentTime = monotonicNow();
                        auto &pqTimeout = m_timeoutQueue.top();
 
                        // 0 means that select won't block and socket will be closed ;-)